vertigo_cli/new/
mod.rs

1use clap::Args;
2use include_dir::{include_dir, Dir};
3use std::{fs, path::Path};
4
5static TEMPLATE: Dir = include_dir!("$CARGO_MANIFEST_DIR/src/new/template");
6
7#[derive(Args)]
8pub struct NewOpts {
9    pub package_name: String,
10    #[arg(long, default_value_t = {"./".to_string()})]
11    pub dest_dir: String,
12}
13
14pub fn run(opts: NewOpts) -> Result<(), i32> {
15    log::info!("Creating {}", opts.package_name);
16
17    let target_path = Path::new(&opts.dest_dir).join(&opts.package_name);
18
19    // Check if dir is empty or non-existent
20    if let Ok(mut dir) = target_path.read_dir() {
21        if dir.next().is_some() {
22            log::error!(
23                "Destination dir ({}) is not empty",
24                target_path.to_string_lossy()
25            );
26            return Err(-1);
27        }
28    }
29
30    // Create directory
31    if let Err(err) = fs::create_dir_all(&target_path) {
32        log::error!(
33            "Can't create directory {}: {}",
34            target_path.to_string_lossy(),
35            err
36        );
37        return Err(-2);
38    };
39
40    // Paste files into it
41    if let Err(err) = TEMPLATE.extract(Path::new(&opts.dest_dir).join(&opts.package_name)) {
42        log::error!(
43            "Can't unpack vertigo stub to {}: {}",
44            target_path.to_string_lossy(),
45            err
46        );
47        return Err(-3);
48    };
49
50    // Remove Cargo.toml_
51    // (cargo packaging does not permit adding second Cargo.toml file)
52    if let Err(err) = fs::remove_file(target_path.join("Cargo.toml_")) {
53        log::error!("Can't rename to Cargo.toml_ to Cargo.toml: {}", err);
54        return Err(-4);
55    };
56
57    // Save Cargo.toml with replaced package name
58    let cargo_toml = TEMPLATE.get_file("Cargo.toml_").unwrap();
59    let cargo_toml_content = cargo_toml.contents_utf8().unwrap();
60
61    if let Err(err) = fs::write(
62        target_path.join("Cargo.toml"),
63        cargo_toml_content.replace("my_app", &opts.package_name),
64    ) {
65        log::error!("Can't write to Cargo.toml: {}", err);
66        return Err(-4);
67    };
68
69    Ok(())
70}