1use std::path::Path;
6
7use vitrify_core::CoreError;
8
9use crate::cli::NewKind;
10use crate::home;
11use crate::out::{diag, emit};
12
13pub fn run(kind: NewKind, single: bool, name: Option<&str>) -> Result<u8, CoreError> {
14 let Some(home_dir) = super::home_dir() else {
15 return Err(CoreError::refusal(
16 1,
17 "error: cannot resolve the vitrify home (set VITRIFY_HOME or HOME)",
18 ));
19 };
20 let version = super::brief::VERSION;
21 let cwd = super::cwd();
22 let resolve = |rel: &str| home::resolve(&home_dir, version, rel).map(|(b, _)| b);
23
24 let refuse_existing = |p: &Path| -> Result<(), CoreError> {
25 if p.exists() {
26 Err(CoreError::refusal(
27 2,
28 format!("error: refusing to overwrite existing {}", p.display()),
29 ))
30 } else {
31 Ok(())
32 }
33 };
34 let write = |p: &Path, body: &str| -> Result<(), CoreError> {
35 if let Some(parent) = p.parent() {
36 std::fs::create_dir_all(parent).map_err(|source| CoreError::Io {
37 path: parent.to_path_buf(),
38 source,
39 })?;
40 }
41 std::fs::write(p, body).map_err(|source| CoreError::Io {
42 path: p.to_path_buf(),
43 source,
44 })
45 };
46
47 match kind {
48 NewKind::Tdd => {
49 let name = name.unwrap_or("tdd");
50 let target = cwd.join(format!("{name}.md"));
51 refuse_existing(&target)?;
52 write(&target, &resolve("templates/tdd-template.md")?)?;
53 diag(&format!("materialized {}", target.display()));
54 emit(&target.display().to_string());
55 diag(&format!(
56 "next: fill {} per vitrify schema show --tdd",
57 super::shown(&cwd, &target)
58 ));
59 }
60 NewKind::Sdd if single => {
61 let name = name.unwrap_or("scope");
62 let target = cwd.join(format!("{name}.sdd.md"));
63 refuse_existing(&target)?;
64 write(&target, &resolve("templates/sdd-template-single.md")?)?;
65 diag(&format!("materialized {}", target.display()));
66 emit(&target.display().to_string());
67 sdd_next(&super::shown(&cwd, &target));
68 }
69 NewKind::Sdd => {
70 let name = name.unwrap_or("scope");
72 let dir = cwd.join(name);
73 refuse_existing(&dir)?;
74 for (rel, out) in [
75 ("templates/sdd-template-bundle/sdd.md", "sdd.md"),
76 (
77 "templates/sdd-template-bundle/units/U-001-foundation.md",
78 "units/U-001-foundation.md",
79 ),
80 (
81 "templates/sdd-template-bundle/contracts/C-001-example.md",
82 "contracts/C-001-example.md",
83 ),
84 ("templates/sdd-template-bundle/changelog.md", "changelog.md"),
85 ("templates/sdd-template-bundle/decisions.md", "decisions.md"),
86 ] {
87 write(&dir.join(out), &resolve(rel)?)?;
88 }
89 diag(&format!("materialized bundle {}", dir.display()));
90 emit(&dir.display().to_string());
91 sdd_next(&super::shown(&cwd, &dir));
92 }
93 }
94 Ok(0)
95}
96
97fn sdd_next(path: &str) {
99 diag(&format!(
100 "next: fill {path} per vitrify schema show, then run vitrify lint --sdd {path}"
101 ));
102}