codeberg-cli 0.5.5

CLI Tool for codeberg similar to gh and glab
Documentation
use crate::actions::GlobalArgs;
use crate::paths::config_path;
use crate::render::json::JsonToStdout;
use crate::types::config::{BergConfig, ConfigLocation};

use clap::Parser;
use miette::IntoDiagnostic;

/// 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
    ///
    /// - stdout : just print it on stdout
    #[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, global_args: GlobalArgs) -> miette::Result<()> {
        let _ = global_args;

        let config = BergConfig::new()?;

        match self.location {
            ConfigLocation::Local | ConfigLocation::Global => {
                let path_dir = self.location.path()?;
                let path_file = config_path()?;

                // remove if we want to replace the file
                if self.replace && path_file.exists() {
                    std::fs::remove_file(path_file.clone()).into_diagnostic()?;
                }

                // by now the file shouldn't exist or we have to throw an error (non-replace case)
                if path_file.exists() {
                    miette::bail!("berg config already exists at {path_file:?}!");
                }

                let config_text = toml::to_string(&config).into_diagnostic()?;
                std::fs::create_dir_all(path_dir.clone()).into_diagnostic()?;
                std::fs::write(path_file.clone(), config_text).into_diagnostic()?;
                println!("Successfully created berg config at {path_file:?}");
            }
            ConfigLocation::Stdout => match global_args.output_mode {
                crate::types::output::OutputMode::Pretty => {
                    let config_text = toml::to_string(&config).into_diagnostic()?;
                    println!("{config_text}");
                }
                crate::types::output::OutputMode::Json => config.print_json()?,
            },
        }
        Ok(())
    }
}