1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
use std::env::current_dir;

use crate::actions::GeneralArgs;
use crate::paths::config_path;
use crate::types::config::{BergConfig, ConfigLocation};

use anyhow::Context;
use clap::Parser;

/// Generate standard configuration at certain locations
#[derive(Parser, Debug)]
pub struct ConfigGenerateArgs {
    /// Specify location at which default config should be dumped
    ///
    /// - global = data_dir + .berg-cli/berg.toml
    ///
    /// - local  = current directory
    #[arg(short, long, value_enum, default_value_t = ConfigLocation::Local)]
    pub location: ConfigLocation,

    /// Specifies whether overwriting already existing configs is allowed
    #[arg(short, long, default_value_t = false)]
    pub replace: bool,
}

impl ConfigGenerateArgs {
    pub fn run(self, general_args: GeneralArgs) -> anyhow::Result<()> {
        let _ = general_args;
        let args = self;
        let path_dir = match args.location {
            ConfigLocation::Global => config_path()?
                .parent()
                .context("config path has parent directory")?
                .to_path_buf(),
            ConfigLocation::Local => current_dir()?,
        };
        let path_file = config_path()?;
        if !path_file.exists() || (path_file.exists() && args.replace) {
            if args.replace {
                std::fs::remove_file(path_file.clone())?;
            }
            std::fs::create_dir_all(path_dir.clone())?;
            let config = BergConfig::default();
            let config_text = toml::to_string(&config)?;
            std::fs::write(path_file.clone(), config_text)?;
            println!("Successfully created berg config at {path_file:?}");
        } else {
            println!("berg config already exists at {path_file:?}!");
        }
        Ok(())
    }
}