monerochan_cli/commands/
new.rs

1use anyhow::Result;
2use clap::{Args, Parser};
3use std::{
4    fs,
5    path::Path,
6    process::{Command, Stdio},
7};
8use yansi::Paint;
9
10#[derive(Args)]
11#[group(required = true, multiple = false)]
12struct TemplateType {
13    /// Use the `bare` template which includes just a program and script.
14    #[arg(long)]
15    bare: bool,
16}
17
18#[derive(Parser)]
19#[command(name = "new", about = "Setup a new project that runs inside the MONEROCHAN.")]
20pub struct NewCmd {
21    /// The name of the project.
22    name: String,
23
24    /// The template to use for the project.
25    #[command(flatten)]
26    template: TemplateType,
27
28    /// Version of monerochan-project-template to use (branch or tag).
29    #[arg(long, default_value = "main")]
30    version: String,
31}
32
33const TEMPLATE_REPOSITORY_URL: &str =
34    "https://github.com/Monero-Chan-Foundation/monerochan-project-template";
35
36impl NewCmd {
37    pub fn run(&self) -> Result<()> {
38        let root = Path::new(&self.name);
39
40        // Create the root directory if it doesn't exist.
41        if !root.exists() {
42            fs::create_dir(&self.name)?;
43        }
44
45        // Clone the repository with the specified version.
46        let mut command = Command::new("git");
47
48        command
49            .arg("clone")
50            .arg("--branch")
51            .arg(&self.version)
52            .arg("--quiet")
53            .arg(TEMPLATE_REPOSITORY_URL)
54            .arg(root.as_os_str())
55            .arg("--depth=1");
56
57        // Suppress git output.
58        command.stdout(Stdio::null()).stderr(Stdio::piped());
59
60        let output = command.output().expect("failed to execute command");
61        if !output.status.success() {
62            let stderr = String::from_utf8_lossy(&output.stderr);
63            return Err(anyhow::anyhow!("Failed to clone repository: {}", stderr));
64        }
65
66        // Remove the .git directory.
67        fs::remove_dir_all(root.join(".git"))?;
68
69        println!(
70            " \x1b[1m{}\x1b[0m {}",
71            Paint::green("Initialized"),
72            self.name
73        );
74
75        Ok(())
76    }
77}