git_prole/
config.rs

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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
use camino::Utf8PathBuf;
use clap::Parser;
use fs_err as fs;
use miette::Context;
use miette::IntoDiagnostic;
use serde::Deserialize;
use xdg::BaseDirectories;

use crate::cli::Cli;
use crate::install_tracing::install_tracing;

/// Configuration, both from the command-line and a user configuration file.
#[derive(Debug)]
pub struct Config {
    /// User directories.
    #[expect(dead_code)]
    pub(crate) dirs: BaseDirectories,
    /// User configuration file.
    pub file: ConfigFile,
    /// User configuration file path.
    pub path: Utf8PathBuf,
    /// Command-line options.
    pub cli: Cli,
}

impl Config {
    /// The contents of the default configuration file.
    pub const DEFAULT: &str = include_str!("../config.toml");

    pub fn new() -> miette::Result<Self> {
        let cli = Cli::parse();
        // TODO: add tracing settings to the config file
        install_tracing(&cli.log)?;
        let dirs = BaseDirectories::with_prefix("git-prole").into_diagnostic()?;
        const CONFIG_FILE_NAME: &str = "config.toml";
        // TODO: Use `git config` for configuration?
        let path = cli
            .config
            .as_ref()
            .map(|path| Ok(path.join(CONFIG_FILE_NAME)))
            .unwrap_or_else(|| dirs.get_config_file(CONFIG_FILE_NAME).try_into())
            .into_diagnostic()?;
        let file = {
            if !path.exists() {
                ConfigFile::default()
            } else {
                toml::from_str(
                    &fs::read_to_string(&path)
                        .into_diagnostic()
                        .wrap_err("Failed to read configuration file")?,
                )
                .into_diagnostic()
                .wrap_err("Failed to deserialize configuration file")?
            }
        };
        Ok(Self {
            dirs,
            path,
            file,
            cli,
        })
    }
}

/// Configuration file format.
///
/// Each configuration key should have two test cases:
/// - `config_{key}` for setting the value.
/// - `config_{key}_default` for the default value.
#[derive(Debug, Default, Deserialize, PartialEq, Eq)]
pub struct ConfigFile {
    #[serde(default)]
    remotes: Vec<String>,

    #[serde(default)]
    default_branches: Vec<String>,

    #[serde(default)]
    copy_untracked: Option<bool>,

    #[serde(default)]
    enable_gh: Option<bool>,
}

impl ConfigFile {
    pub fn remotes(&self) -> Vec<String> {
        // Yeah this basically sucks. But how big could these lists really be?
        if self.remotes.is_empty() {
            vec!["upstream".to_owned(), "origin".to_owned()]
        } else {
            self.remotes.clone()
        }
    }

    pub fn default_branches(&self) -> Vec<String> {
        // Yeah this basically sucks. But how big could these lists really be?
        if self.default_branches.is_empty() {
            vec!["main".to_owned(), "master".to_owned(), "trunk".to_owned()]
        } else {
            self.default_branches.clone()
        }
    }

    pub fn copy_untracked(&self) -> bool {
        self.copy_untracked.unwrap_or(true)
    }

    pub fn enable_gh(&self) -> bool {
        self.enable_gh.unwrap_or(false)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;

    #[test]
    fn test_default_config_file_parse() {
        assert_eq!(
            toml::from_str::<ConfigFile>(Config::DEFAULT).unwrap(),
            ConfigFile {
                remotes: vec!["upstream".to_owned(), "origin".to_owned(),],
                default_branches: vec!["main".to_owned(), "master".to_owned(), "trunk".to_owned(),],
                copy_untracked: Some(true),
                enable_gh: Some(false),
            }
        );
    }
}