codeberg_cli/actions/config/
generate.rs

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