Skip to main content

git_atomic/cli/commands/
init.rs

1use crate::cli::output::Printer;
2use crate::config::Config;
3use crate::core::Error;
4use crate::core::effect::{self, Effect};
5use std::path::Path;
6
7const HEADER: &str = "\
8# git-atomic configuration
9# See: https://github.com/aRustyDev/git-atomic
10#
11# Order matters: first matching component wins.
12
13";
14
15pub fn run(config_path: &Path, dry_run: bool, printer: &Printer) -> Result<(), Error> {
16    if config_path.exists() {
17        return Err(Error::General(format!(
18            "config already exists: {}",
19            config_path.display()
20        )));
21    }
22
23    let sample = Config::sample();
24    let toml_body = toml::to_string_pretty(&sample)
25        .map_err(|e| Error::General(format!("failed to serialize config: {e}")))?;
26
27    let content = format!("{HEADER}{toml_body}");
28    let structured = serde_json::to_value(&sample).ok();
29    let effects = vec![Effect::WriteFile {
30        path: config_path.to_path_buf(),
31        content,
32        structured,
33    }];
34
35    effect::execute(None, &effects, dry_run, printer)?;
36
37    if !dry_run {
38        printer.print_init(config_path);
39    }
40
41    Ok(())
42}