Skip to main content

solar_core/subcommand/
init.rs

1use std::{
2    fs::{self, File},
3    path::PathBuf,
4};
5
6use rust_terminal::Terminal;
7
8use clap::Parser;
9
10use crate::{SolarError, Install};
11
12#[derive(Parser, Clone)]
13pub struct Init {
14    /// The destination to initialize the project.
15    #[arg(short, long, default_value = ".")]
16    destination: PathBuf,
17
18    /// Whether to force reinitialization of an already existing git repository.
19    /// WARNING: Setting this to true will delete commit history for existing git repositories.
20    #[arg(short, long, default_value = "false")]
21    force_init: bool,
22
23    /// Whether to force tool installation to an existing git repository.
24    #[arg(short, long, default_value = "false")]
25    install_existing: bool,
26}
27
28impl Init {
29    pub fn run(&self) -> Result<(), SolarError> {
30        // Initialize git repository if forcing initialization or repository is not initialized already
31        let no_existing_git_repo =
32            fs::exists(self.destination.join(PathBuf::from(".git"))).is_err();
33        if self.force_init || no_existing_git_repo {
34            Terminal::command().piped().run("git", vec!["init"])?;
35        }
36
37        // Create a README.md file
38        File::create(&self.destination.join(PathBuf::from("README.md")))?;
39
40        // Install all tools into the project
41        if self.install_existing || no_existing_git_repo {
42            let installer: Install = Install::parse_from(vec![
43                "",
44                self.destination
45                    .to_str()
46                    .ok_or("Failed to convert destination path to string.")?,
47            ]);
48            installer.run()?;
49        }
50        Ok(())
51    }
52}