Skip to main content

vertigo_cli/new/
mod.rs

1use clap::Args;
2use derive_more::Display;
3use include_dir::{Dir, include_dir};
4use std::{fs, path::Path};
5use walkdir::WalkDir;
6
7use crate::commons::ErrorCode;
8
9#[derive(clap::ValueEnum, Clone, Default, Display)]
10pub enum Template {
11    #[display("fullstack")]
12    Fullstack,
13    #[display("frontend")]
14    #[default]
15    Frontend,
16}
17
18impl Template {
19    pub fn get_dir(&self) -> Dir<'_> {
20        match self {
21            Template::Fullstack => include_dir!("$CARGO_MANIFEST_DIR/src/new/fs_template"),
22            Template::Frontend => include_dir!("$CARGO_MANIFEST_DIR/src/new/fe_template"),
23        }
24    }
25}
26
27/// Notes for coding agents, at the root of every template.
28const AGENT_FILES: [&str; 2] = ["AGENTS.md", "CLAUDE.md"];
29
30#[derive(Args)]
31pub struct NewOpts {
32    pub project_name: String,
33    #[arg(short, long, default_value_t = {Template::default()})]
34    pub template: Template,
35    #[arg(long, default_value_t = {"./".to_string()})]
36    pub dest_dir: String,
37    /// Leave out AGENTS.md and CLAUDE.md, the notes for coding agents
38    #[arg(long)]
39    pub no_agent_files: bool,
40}
41
42pub fn run(opts: NewOpts) -> Result<(), ErrorCode> {
43    log::info!("Creating {}", opts.project_name);
44
45    let target_path = Path::new(&opts.dest_dir).join(&opts.project_name);
46
47    // Check if dir is empty or non-existent
48    if let Ok(mut dir) = target_path.read_dir()
49        && dir.next().is_some()
50    {
51        log::error!(
52            "Destination dir ({}) is not empty",
53            target_path.to_string_lossy()
54        );
55        return Err(ErrorCode::NewProjectDirNotEmpty);
56    }
57
58    // Create directory
59    if let Err(err) = fs::create_dir_all(&target_path) {
60        log::error!(
61            "Can't create directory {}: {}",
62            target_path.to_string_lossy(),
63            err
64        );
65        return Err(ErrorCode::NewProjectCantCreateDir);
66    };
67
68    // Paste files into it
69    if let Err(err) = opts
70        .template
71        .get_dir()
72        .extract(Path::new(&opts.dest_dir).join(&opts.project_name))
73    {
74        log::error!(
75            "Can't unpack vertigo stub to {}: {}",
76            target_path.to_string_lossy(),
77            err
78        );
79        return Err(ErrorCode::NewProjectCantUnpackStub);
80    };
81
82    if opts.no_agent_files {
83        remove_agent_files(&target_path)?;
84    }
85
86    // Process all Cargo.toml_ files recursively
87    // (cargo packaging does not permit adding second Cargo.toml file)
88    process_cargo_toml_files(&target_path, &opts.project_name)?;
89
90    Ok(())
91}
92
93/// Remove the notes for coding agents from a project just unpacked.
94fn remove_agent_files(project_dir: &Path) -> Result<(), ErrorCode> {
95    for name in AGENT_FILES {
96        let path = project_dir.join(name);
97        if let Err(err) = fs::remove_file(&path) {
98            log::error!("Can't remove {}: {}", path.display(), err);
99            return Err(ErrorCode::NewProjectCantUnpackStub);
100        }
101    }
102
103    Ok(())
104}
105
106/// Find all Cargo.toml_ files, replace "my_app" with package_name and "my-app" with its
107/// kebab-case form (cargo wants binary names in kebab-case), and save as Cargo.toml
108fn process_cargo_toml_files(dir: &Path, package_name: &str) -> Result<(), ErrorCode> {
109    let kebab_name = package_name.replace('_', "-");
110
111    for entry in WalkDir::new(dir).into_iter().filter_map(|e| e.ok()) {
112        if entry.file_name() == "Cargo.toml_" {
113            let path = entry.path();
114            // Read the content
115            let content = match fs::read_to_string(path) {
116                Ok(content) => content,
117                Err(err) => {
118                    log::error!("Can't read {}: {}", path.display(), err);
119                    return Err(ErrorCode::NewProjectCantCreateCargoToml);
120                }
121            };
122
123            let new_content = content
124                .replace("my_app", package_name)
125                .replace("my-app", &kebab_name);
126
127            // Write to Cargo.toml in the same directory
128            if let Some(parent) = path.parent() {
129                let cargo_toml_path = parent.join("Cargo.toml");
130                if let Err(err) = fs::write(&cargo_toml_path, new_content) {
131                    log::error!("Can't write to {}: {}", cargo_toml_path.display(), err);
132                    return Err(ErrorCode::NewProjectCantWriteToCargoToml);
133                }
134            }
135
136            // Remove the original Cargo.toml_ file
137            if let Err(err) = fs::remove_file(path) {
138                log::error!("Can't remove {}: {}", path.display(), err);
139                return Err(ErrorCode::NewProjectCantCreateCargoToml);
140            }
141        }
142    }
143
144    Ok(())
145}
146
147#[cfg(test)]
148mod tests {
149    use super::{AGENT_FILES, Template};
150
151    #[test]
152    fn every_template_has_the_agent_files_at_its_root() {
153        for template in [Template::Frontend, Template::Fullstack] {
154            for name in AGENT_FILES {
155                assert!(
156                    template.get_dir().get_file(name).is_some(),
157                    "{template} template has no {name}, which --no-agent-files removes"
158                );
159            }
160        }
161    }
162}