codeberg_cli/actions/config/
generate.rs

1use crate::actions::GeneralArgs;
2use crate::paths::config_path;
3use crate::render::json::JsonToStdout;
4use crate::types::config::{BergConfig, ConfigLocation};
5
6use clap::Parser;
7
8/// Generate standard configuration at certain locations
9#[derive(Parser, Debug)]
10pub struct ConfigGenerateArgs {
11    /// Specify location at which default config should be dumped
12    ///
13    /// - global : data_dir + .berg-cli/berg.toml
14    ///
15    /// - local  : current directory
16    ///
17    /// - stdout : just print it on stdout
18    #[arg(short, long, value_enum, default_value_t = ConfigLocation::Local)]
19    pub location: ConfigLocation,
20
21    /// Specifies whether overwriting already existing configs is allowed
22    #[arg(short, long, default_value_t = false)]
23    pub replace: bool,
24}
25
26impl ConfigGenerateArgs {
27    pub fn run(self, general_args: GeneralArgs) -> anyhow::Result<()> {
28        let _ = general_args;
29
30        let config = BergConfig::new()?;
31
32        match self.location {
33            ConfigLocation::Local | ConfigLocation::Global => {
34                let path_dir = self.location.path()?;
35                let path_file = config_path()?;
36
37                // remove if we want to replace the file
38                if self.replace && path_file.exists() {
39                    std::fs::remove_file(path_file.clone())?;
40                }
41
42                // by now the file shouldn't exist or we have to throw an error (non-replace case)
43                if path_file.exists() {
44                    anyhow::bail!("berg config already exists at {path_file:?}!");
45                }
46
47                let config_text = toml::to_string(&config)?;
48                std::fs::create_dir_all(path_dir.clone())?;
49                std::fs::write(path_file.clone(), config_text)?;
50                println!("Successfully created berg config at {path_file:?}");
51            }
52            ConfigLocation::Stdout => match general_args.output_mode {
53                crate::types::output::OutputMode::Pretty => {
54                    let config_text = toml::to_string(&config)?;
55                    println!("{config_text}");
56                }
57                crate::types::output::OutputMode::Json => config.print_json()?,
58            },
59        }
60        Ok(())
61    }
62}