1use std::{
4 fs, io, mem,
5 path::{Path, PathBuf},
6};
7
8use clap::*;
9use color_print::cstr;
10use convert_case::{Case, Casing};
11
12use crate::util::{self, unix_path};
13
14#[derive(Args, Debug)]
15pub struct NewArgs {
16 #[arg(num_args(0..))]
26 value: Vec<String>,
27
28 #[arg(short, long, default_value = "zng-ui/zng-template")]
35 template: String,
36
37 #[arg(short, long, num_args(0..))]
45 set: Vec<String>,
46
47 #[arg(short, long, action)]
49 keys: bool,
50}
51
52pub fn run(args: NewArgs) {
53 let template = parse_template(args.template);
54
55 if args.keys {
56 return print_keys(template);
57 }
58
59 let arg_keys = match parse_key_values(args.value, args.set) {
60 Ok(arg_keys) => {
61 if arg_keys.is_empty() || (!arg_keys[0].0.is_empty() && arg_keys.iter().all(|(k, _)| k != "app")) {
62 fatal!("missing required key `app`")
63 }
64 arg_keys
65 }
66 Err(e) => fatal!("{e}"),
67 };
68
69 let app = &arg_keys[0].1;
71 let project_name = util::clean_value(app, true)
72 .unwrap_or_else(|e| fatal!("{e}"))
73 .replace(' ', "-")
74 .to_lowercase();
75
76 if Path::new(project_name.as_str()).exists() {
77 let full_path = Path::new(project_name.as_str())
78 .canonicalize()
79 .map(|p| p.display().to_string())
80 .unwrap_or(project_name);
81 fatal!("destination `{full_path}` already exists");
82 }
83
84 if let Err(e) = util::cmd("cargo new --quiet --bin", &[project_name.as_str()], &[]) {
85 let _ = std::fs::remove_dir_all(&project_name);
86 fatal!("cannot init project folder, {e}");
87 }
88
89 if let Err(e) = cleanup_cargo_new(&project_name) {
90 fatal!("failed to cleanup `cargo new` template, {e}");
91 }
92
93 let template_temp = PathBuf::from(format!("{project_name}.zng_template.tmp"));
95
96 let fatal_cleanup = || {
97 let _ = fs::remove_dir_all(&template_temp);
98 let _ = fs::remove_dir_all(&project_name);
99 };
100
101 let (template_keys, ignore) = template.git_clone(&template_temp, false).unwrap_or_else(|e| {
102 fatal_cleanup();
103 fatal!("failed to clone template, {e}")
104 });
105
106 let cx = Context::new(&template_temp, template_keys, arg_keys, ignore).unwrap_or_else(|e| {
107 fatal_cleanup();
108 fatal!("cannot parse template, {e}")
109 });
110 if let Err(e) = apply_template(&cx, &project_name) {
112 error!("cannot generate, {e}");
113 fatal_cleanup();
114 util::exit();
115 }
116
117 if Path::new(&project_name).join("Cargo.toml").exists() {
119 if let Err(e) = std::env::set_current_dir(project_name) {
120 fatal!("cannot format generated project, {e}")
121 }
122 crate::fmt::run(crate::fmt::FmtArgs::default());
123 }
124}
125
126fn parse_key_values(value: Vec<String>, define: Vec<String>) -> io::Result<ArgsKeyMap> {
127 let mut r = Vec::with_capacity(value.len() + define.len());
128
129 for value in value {
130 r.push((String::new(), value));
131 }
132
133 for key_value in define {
134 if let Some((key, value)) = key_value.trim_matches('"').split_once('=') {
135 if !is_key(key) {
136 return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("invalid key `{key}`")));
137 }
138 r.push((key.to_owned(), value.to_owned()));
139 }
140 }
141
142 Ok(r)
143}
144
145fn print_keys(template: Template) {
146 for i in 0..100 {
147 let template_temp = std::env::temp_dir().join(format!("cargo-zng-template-keys-help-{i}"));
148 if template_temp.exists() {
149 continue;
150 }
151
152 match template.git_clone(&template_temp, true) {
153 Ok((keys, _)) => {
154 println!("TEMPLATE KEYS\n");
155 for kv in keys {
156 let value = match &kv.value {
157 Some(dft) => dft.as_str(),
158 None => cstr!("<bold><y>required</y></bold>"),
159 };
160 println!(cstr!("<bold>{}=</bold>{}"), kv.key, value);
161 if !kv.docs.is_empty() {
162 for line in kv.docs.lines() {
163 println!(" {line}");
164 }
165 println!();
166 }
167 }
168 }
169 Err(e) => {
170 error!("failed to clone template, {e}");
171 }
172 }
173 let _ = fs::remove_dir_all(&template_temp);
174 return;
175 }
176 fatal!("failed to clone template, no temp dir available");
177}
178
179fn parse_template(arg: String) -> Template {
180 let (arg, branch) = arg.rsplit_once('#').unwrap_or((&arg, ""));
181
182 if arg.ends_with(".git") {
183 return Template::Git(arg.to_owned(), branch.to_owned());
184 }
185
186 if arg.starts_with("./") {
187 return Template::Local(PathBuf::from(arg), branch.to_owned());
188 }
189
190 if let Some((owner, repo)) = arg.split_once('/')
191 && !owner.is_empty()
192 && !repo.is_empty()
193 && !repo.contains('/')
194 {
195 return Template::Git(format!("https://github.com/{owner}/{repo}.git"), branch.to_owned());
196 }
197
198 let path = PathBuf::from(arg);
199 if path.is_absolute() {
200 return Template::Local(path.to_owned(), branch.to_owned());
201 }
202
203 fatal!("--template must be a `.git` URL, `owner/repo`, `./local` or `/absolute/local`");
204}
205
206enum Template {
207 Git(String, String),
208 Local(PathBuf, String),
209}
210impl Template {
211 fn git_clone(self, to: &Path, include_docs: bool) -> io::Result<(KeyMap, Vec<globset::GlobMatcher>)> {
213 let (from, branch) = match self {
214 Template::Git(url, b) => (url, b),
215 Template::Local(path, b) => {
216 let path = dunce::canonicalize(path)?;
217 (path.display().to_string(), b)
218 }
219 };
220 let to_str = to.display().to_string();
221 let mut args = vec![from.as_str(), &to_str];
222 if !branch.is_empty() {
223 args.push("--branch");
224 args.push(&branch);
225 }
226 util::cmd_silent("git clone --depth 1", &args, &[])?;
227
228 let keys = match fs::read_to_string(to.join(".zng-template/keys")) {
229 Ok(s) => parse_keys(s, include_docs)?,
230 Err(e) => {
231 if e.kind() == io::ErrorKind::NotFound {
232 return Err(io::Error::new(
233 io::ErrorKind::NotFound,
234 "git repo is not a zng template, missing `.zng-template/keys`",
235 ));
236 }
237 return Err(e);
238 }
239 };
240
241 let mut ignore = vec![];
242 match fs::read_to_string(to.join(".zng-template/ignore")) {
243 Ok(i) => {
244 for glob in i.lines().map(|l| l.trim()).filter(|l| !l.is_empty() && !l.starts_with('#')) {
245 let glob = globset::GlobBuilder::new(glob)
246 .case_insensitive(true)
247 .build()
248 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
249 .compile_matcher();
250 ignore.push(glob);
251 }
252 }
253 Err(e) => {
254 if e.kind() != io::ErrorKind::NotFound {
255 return Err(e);
256 }
257 }
258 }
259
260 Ok((keys, ignore))
261 }
262}
263
264fn cleanup_cargo_new(path: &str) -> io::Result<()> {
265 for entry in fs::read_dir(path)? {
266 let path = entry?.path();
267 if path.components().any(|c| c.as_os_str() == ".git") {
268 continue;
269 }
270 if path.is_dir() {
271 fs::remove_dir_all(path)?;
272 } else if path.is_file() {
273 fs::remove_file(path)?;
274 }
275 }
276 Ok(())
277}
278
279fn apply_template(cx: &Context, package_name: &str) -> io::Result<()> {
280 let template_temp = &cx.template_root;
281
282 fs::remove_dir_all(template_temp.join(".git"))?;
284
285 let post = template_temp.join(".zng-template/post");
287 if post.is_dir() {
288 let post_replaced = template_temp.join(".zng-template/post-temp");
289 fs::create_dir_all(&post_replaced)?;
290 apply(cx, true, &post, &post_replaced)?;
291 fs::remove_dir_all(&post)?;
292 fs::rename(&post_replaced, &post)?;
293
294 unsafe {
295 std::env::set_var("ZNG_TEMPLATE_POST_DIR", &*unix_path(&post));
297 }
298 }
299
300 let to = PathBuf::from(package_name);
302 apply(cx, false, template_temp, &to)?;
303
304 let bash = post.join("post.sh");
305 if bash.is_file() {
306 let script = fs::read_to_string(bash)?;
307 crate::res::built_in::sh_run(script, false, Some(&to))?;
308 } else {
309 let manifest = post.join("Cargo.toml");
310 if manifest.exists() {
311 let s = std::process::Command::new("cargo")
312 .arg("run")
313 .arg("--quiet")
314 .arg("--manifest-path")
315 .arg(manifest)
316 .current_dir(to)
317 .status()?;
318 if !s.success() {}
319 } else if post.exists() {
320 return Err(io::Error::new(
321 io::ErrorKind::InvalidData,
322 ".zng-template/post does not contain 'post.sh' nor 'Cargo.toml'",
323 ));
324 }
325 }
326
327 fs::remove_dir_all(template_temp)
329}
330
331fn apply(cx: &Context, is_post: bool, from: &Path, to: &Path) -> io::Result<()> {
332 for entry in walkdir::WalkDir::new(from).min_depth(1).max_depth(1).sort_by_file_name() {
333 let entry = entry?;
334 let from = entry.path();
335 if cx.ignore(from, is_post) {
336 continue;
337 }
338 if from.is_dir() {
339 let from = cx.rename(from)?;
340 let to = to.join(from.file_name().unwrap());
341 println!(" {}", to.display());
342 fs::create_dir(&to)?;
343 apply(cx, is_post, &from, &to)?;
344 } else if from.is_file() {
345 let from = cx.rename(from)?;
346 let to = to.join(from.file_name().unwrap());
347 cx.rewrite(&from)?;
348 println!(" {}", to.display());
349 fs::rename(from, to).unwrap();
350 }
351 }
352 Ok(())
353}
354
355struct Context {
356 template_root: PathBuf,
357 replace: ReplaceMap,
358 ignore_workspace: globset::GlobMatcher,
359 ignore: Vec<globset::GlobMatcher>,
360}
361impl Context {
362 fn new(template_root: &Path, mut template_keys: KeyMap, arg_keys: ArgsKeyMap, ignore: Vec<globset::GlobMatcher>) -> io::Result<Self> {
363 for (i, (key, value)) in arg_keys.into_iter().enumerate() {
364 if key.is_empty() {
365 if i >= template_keys.len() {
366 return Err(io::Error::new(
367 io::ErrorKind::InvalidInput,
368 "more positional values them template keys",
369 ));
370 }
371 template_keys[i].value = Some(value);
372 } else if let Some(kv) = template_keys.iter_mut().find(|kv| kv.key == key) {
373 kv.value = Some(value);
374 } else {
375 return Err(io::Error::new(
376 io::ErrorKind::InvalidInput,
377 format!("unknown key `{key}`, not declared by template"),
378 ));
379 }
380 }
381 Ok(Self {
382 template_root: dunce::canonicalize(template_root)?,
383 replace: make_replacements(&template_keys)?,
384 ignore_workspace: globset::Glob::new(".zng-template").unwrap().compile_matcher(),
385 ignore,
386 })
387 }
388
389 fn ignore(&self, template_path: &Path, is_post: bool) -> bool {
390 let template_path = template_path.strip_prefix(&self.template_root).unwrap();
391
392 if !is_post && self.ignore_workspace.is_match(template_path) {
393 return true;
394 }
395
396 for glob in &self.ignore {
397 if glob.is_match(template_path) {
398 return true;
399 }
400 }
401 false
402 }
403
404 fn rename(&self, template_path: &Path) -> io::Result<PathBuf> {
405 let mut path = template_path.to_string_lossy().into_owned();
406 for (key, value) in &self.replace {
407 let s_value;
408 let value = if is_sanitized_key(key) {
409 value
410 } else {
411 s_value = sanitise_file_name::sanitize(value);
412 &s_value
413 };
414 path = path.replace(key, value);
415 }
416 let path = PathBuf::from(path);
417 if template_path != path {
418 fs::rename(template_path, &path)?;
419 }
420 Ok(path)
421 }
422
423 fn rewrite(&self, template_path: &Path) -> io::Result<()> {
424 match fs::read_to_string(template_path) {
425 Ok(txt) => {
426 let mut new_txt = txt.clone();
427 for (key, value) in &self.replace {
428 new_txt = new_txt.replace(key, value);
429 }
430 if new_txt != txt {
431 fs::write(template_path, new_txt.as_bytes())?;
432 }
433 Ok(())
434 }
435 Err(e) => {
436 if e.kind() == io::ErrorKind::InvalidData {
437 Ok(())
439 } else {
440 Err(e)
441 }
442 }
443 }
444 }
445}
446
447static PATTERNS: &[(&str, &str, Option<Case>)] = &[
448 ("t-key-t", "kebab-case", Some(Case::Kebab)),
449 ("T-KEY-T", "UPPER-KEBAB-CASE", Some(Case::UpperKebab)),
450 ("t_key_t", "snake_case", Some(Case::Snake)),
451 ("T_KEY_T", "UPPER_SNAKE_CASE", Some(Case::UpperSnake)),
452 ("T-Key-T", "Train-Case", Some(Case::Train)),
453 ("t.key.t", "lower case", Some(Case::Lower)),
454 ("T.KEY.T", "UPPER CASE", Some(Case::Upper)),
455 ("T.Key.T", "Title Case", Some(Case::Title)),
456 ("ttKeyTt", "camelCase", Some(Case::Camel)),
457 ("TtKeyTt", "PascalCase", Some(Case::Pascal)),
458 ("{{key}}", "Unchanged", None),
459 ("f-key-f", "Sanitized", None),
460 ("F-Key-F", "Title Sanitized", None),
461];
462
463type KeyMap = Vec<TemplateKey>;
464type ArgsKeyMap = Vec<(String, String)>;
465type ReplaceMap = Vec<(String, String)>;
466
467struct TemplateKey {
468 docs: String,
469 key: String,
470 value: Option<String>,
471 required: bool,
472}
473
474fn is_key(s: &str) -> bool {
475 s.len() >= 3 && s.is_ascii() && s.chars().all(|c| c.is_ascii_alphabetic() && c.is_lowercase())
476}
477
478fn parse_keys(zng_template_v1: String, include_docs: bool) -> io::Result<KeyMap> {
479 let mut r = vec![];
480
481 let mut docs = String::new();
482
483 for (i, line) in zng_template_v1.lines().enumerate() {
484 let line = line.trim();
485 if line.is_empty() {
486 docs.clear();
487 continue;
488 }
489
490 if line.starts_with('#') {
491 if include_docs {
492 let mut line = line.trim_start_matches('#');
493 if line.starts_with(' ') {
494 line = &line[1..];
495 }
496 docs.push_str(line);
497 docs.push('\n');
498 }
499 continue;
500 }
501
502 if r.is_empty() && line != "app=" {
503 return Err(io::Error::new(
504 io::ErrorKind::InvalidData,
505 "broken template, first key must be `app=`",
506 ));
507 }
508
509 let docs = mem::take(&mut docs);
510 if let Some((key, val)) = line.split_once('=')
511 && is_key(key)
512 {
513 if val.is_empty() {
514 r.push(TemplateKey {
515 docs,
516 key: key.to_owned(),
517 value: None,
518 required: true,
519 });
520 continue;
521 } else if val.starts_with('"') && val.ends_with('"') {
522 r.push(TemplateKey {
523 docs,
524 key: key.to_owned(),
525 value: Some(val[1..val.len() - 1].to_owned()),
526 required: false,
527 });
528 continue;
529 }
530 }
531 return Err(io::Error::new(
532 io::ErrorKind::InvalidData,
533 format!("broken template, invalid syntax in `.zng-template:{}`", i + 1),
534 ));
535 }
536
537 Ok(r)
538}
539fn make_replacements(keys: &KeyMap) -> io::Result<ReplaceMap> {
540 let mut r = Vec::with_capacity(keys.len() * PATTERNS.len());
541 for kv in keys {
542 let value = match &kv.value {
543 Some(v) => v,
544 None => {
545 return Err(io::Error::new(
546 io::ErrorKind::InvalidInput,
547 format!("missing required key `{}`", kv.key),
548 ));
549 }
550 };
551 let clean_value = util::clean_value(value, kv.required)?;
552
553 for (pattern, _, case) in PATTERNS {
554 let prefix = &pattern[..2];
555 let suffix = &pattern[pattern.len() - 2..];
556 let (key, value) = if let Some(case) = case {
557 let key_case = match case {
558 Case::Camel => Case::Pascal,
559 c => *c,
560 };
561 let value = match !pattern.contains('.') && !pattern.contains('{') {
562 true => &clean_value,
563 false => value,
564 };
565 (kv.key.to_case(key_case), value.to_case(*case))
566 } else {
567 (kv.key.to_owned(), value.to_owned())
568 };
569 let value = if is_sanitized_key(&key) {
570 sanitise_file_name::sanitize(&value)
571 } else {
572 value
573 };
574 let key = format!("{prefix}{key}{suffix}");
575 r.push((key, value));
576 }
577 }
578 Ok(r)
579}
580
581fn is_sanitized_key(key: &str) -> bool {
582 key.starts_with('f') || key.starts_with('F')
583}