1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
mod app_config;
mod config;
mod emoji;
mod favorites;
mod git;
mod ignore_me;
mod include_exclude;
mod interactive;
mod log;
mod progressbar;
mod project_variables;
mod template;
mod template_variables;
use anyhow::{Context, Result};
use config::{Config, ConfigValues, CONFIG_FILE_NAME};
use console::style;
use favorites::{list_favorites, resolve_favorite};
use std::{
collections::HashMap,
env, fs,
path::{Path, PathBuf},
str::FromStr,
};
use structopt::StructOpt;
use crate::git::GitConfig;
use crate::template_variables::{CrateType, ProjectName};
#[derive(StructOpt)]
#[structopt(bin_name = "cargo")]
pub enum Cli {
#[structopt(name = "generate", visible_alias = "gen")]
Generate(Args),
}
#[derive(Debug, StructOpt)]
pub struct Args {
#[structopt(long)]
pub list_favorites: bool,
pub favorite: Option<String>,
#[structopt(short, long)]
pub git: Option<String>,
#[structopt(short, long)]
pub branch: Option<String>,
#[structopt(long, short)]
pub name: Option<String>,
#[structopt(long, short)]
pub force: bool,
#[structopt(long, short)]
pub verbose: bool,
#[structopt(long)]
pub template_values_file: Option<String>,
#[structopt(long, short, requires("name"))]
pub silent: bool,
#[structopt(short, long, parse(from_os_str))]
pub config: Option<PathBuf>,
#[structopt(long, default_value = "git")]
pub vcs: Vcs,
#[structopt(long, conflicts_with = "bin")]
pub lib: bool,
#[structopt(long, conflicts_with = "lib")]
pub bin: bool,
#[structopt(short = "i", long = "identity", parse(from_os_str))]
pub ssh_identity: Option<PathBuf>,
}
#[derive(Debug, StructOpt)]
pub enum Vcs {
None,
Git,
}
impl FromStr for Vcs {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_uppercase().as_str() {
"NONE" => Ok(Vcs::None),
"GIT" => Ok(Vcs::Git),
_ => Err(anyhow::anyhow!("Must be one of 'git' or 'none'")),
}
}
}
pub fn generate(mut args: Args) -> Result<()> {
if args.list_favorites {
return list_favorites(&args);
}
resolve_favorite(&mut args)?;
let name = match args.name {
Some(ref n) => ProjectName::new(n),
None if !args.silent => ProjectName::new(interactive::name()?),
None => anyhow::bail!(
"{} {} {}",
emoji::ERROR,
style("Project Name Error:").bold().red(),
style("Option `--silent` provided, but project name was not set. Please use `--project-name`.")
.bold()
.red(),
),
};
create_git(args, &name)?;
Ok(())
}
fn create_git(args: Args, name: &ProjectName) -> Result<()> {
let force = args.force;
let template_values = args
.template_values_file
.as_ref()
.map(|p| Path::new(p))
.map_or(Ok(Default::default()), |path| get_config_file_values(path))?;
let remote = args
.git
.clone()
.with_context(|| "Missing option git, or a favorite")?;
let git_config = GitConfig::new_abbr(
remote.into(),
args.branch.to_owned(),
args.ssh_identity.clone(),
)?;
if let Some(dir) = &create_project_dir(&name, force) {
match git::create(dir, git_config) {
Ok(branch) => {
progress(name, &template_values, dir, &branch, &args)?;
}
Err(e) => anyhow::bail!(
"{} {} {}",
emoji::ERROR,
style("Git Error:").bold().red(),
style(e).bold().red(),
),
};
} else {
anyhow::bail!(
"{} {}",
emoji::ERROR,
style("Target directory already exists, aborting!")
.bold()
.red(),
);
}
Ok(())
}
fn get_config_file_values(path: &Path) -> Result<HashMap<String, toml::Value>> {
match fs::read_to_string(path) {
Ok(ref contents) => toml::from_str::<ConfigValues>(contents)
.map(|v| v.values)
.map_err(|e| e.into()),
Err(e) => anyhow::bail!(
"{} {} {}",
emoji::ERROR,
style("Values File Error:").bold().red(),
style(e).bold().red(),
),
}
}
fn create_project_dir(name: &ProjectName, force: bool) -> Option<PathBuf> {
let dir_name = if force {
name.raw()
} else {
rename_warning(&name);
name.kebab_case()
};
let project_dir = env::current_dir()
.unwrap_or_else(|_e| ".".into())
.join(&dir_name);
println!(
"{} {} `{}`{}",
emoji::WRENCH,
style("Creating project called").bold(),
style(&dir_name).bold().yellow(),
style("...").bold()
);
if project_dir.exists() {
None
} else {
Some(project_dir)
}
}
fn progress(
name: &ProjectName,
template_values: &HashMap<String, toml::Value>,
dir: &Path,
branch: &str,
args: &Args,
) -> Result<()> {
let crate_type: CrateType = args.into();
let template = template::substitute(name, &crate_type, template_values, args.force)?;
let config_path = dir.join(CONFIG_FILE_NAME);
let template_config = Config::new(config_path)?;
let template = match template_config.as_ref() {
None => Ok(template),
Some(config) => {
project_variables::fill_project_variables(template, config, args.silent, |slot| {
interactive::variable(slot)
})
}
}?;
let mut pbar = progressbar::new();
ignore_me::remove_unneeded_files(dir, args.verbose);
template::walk_dir(
dir,
template,
template_config.and_then(|c| c.template),
&mut pbar,
)?;
pbar.join().unwrap();
match args.vcs {
Vcs::None => {}
Vcs::Git => {
git::init(dir, branch)?;
}
}
gen_success(dir);
Ok(())
}
fn gen_success(dir: &Path) {
let dir_string = dir.to_str().unwrap_or("");
println!(
"{} {} {} {}",
emoji::SPARKLE,
style("Done!").bold().green(),
style("New project created").bold(),
style(dir_string).underlined()
);
}
fn rename_warning(name: &ProjectName) {
if !name.is_crate_name() {
info!(
"{} `{}` {} `{}`{}",
style("Renaming project called").bold(),
style(&name.user_input).bold().yellow(),
style("to").bold(),
style(&name.kebab_case()).bold().green(),
style("...").bold()
);
}
}