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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
use std::path::PathBuf;
use std::{env::current_dir, path::Path};

use anyhow::Context;
use clap::ValueEnum;
use comfy_table::Table;
use config::Config;
use serde::{Deserialize, Serialize};
use url::Url;

use crate::paths::berg_data_dir;

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
pub enum ConfigLocation {
    Global,
    Local,
}

/// Parsed configuration of the `berg` client
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BergConfig {
    /// base url for the forgejo instance that were going to talk to
    pub base_url: String,
    /// protocol used, typically only a choice between http/https
    pub protocol: String,
    /// the output of some actions is displayed in a table format.
    /// This can optionally be disabled to make the output more machine readable
    pub fancy_tables: bool,
    /// the output of some actions is displayed with extra colors in the terminal.
    /// This can optionally be disabled in case of e.g. color blindness
    ///
    /// WIP this does nothing yet since we don't have colors anyways yet
    pub no_color: bool,
}

impl BergConfig {
    fn iter_default_field_value() -> impl Iterator<Item = (&'static str, config::Value)> {
        let BergConfig {
            base_url,
            protocol,
            fancy_tables,
            no_color,
        } = Default::default();
        [
            ("base_url", config::Value::from(base_url)),
            ("protocol", config::Value::from(protocol)),
            ("fancy_tables", config::Value::from(fancy_tables)),
            ("no_color", config::Value::from(no_color)),
        ]
        .into_iter()
    }
}

impl Default for BergConfig {
    fn default() -> Self {
        Self {
            base_url: String::from("codeberg.org/"),
            protocol: String::from("https"),
            fancy_tables: true,
            no_color: false,
        }
    }
}

impl BergConfig {
    /// tries to read berg config from a known set of locations:
    ///
    /// The following list is ordered with descending priority
    ///
    /// - environment variables of the form "BERG_<config field name in caps>"
    /// - current directory + "berg.toml"
    /// - data dir + ".berg-cli/berg.toml""
    ///
    /// Note that config options are overridden with these priorities. This implies that if both
    /// global and local configs exist, all existing options from the local config override the
    /// global configs options. On the other hand, if some options are not overridden, then the
    /// global ones are used in this scenario.
    pub fn new() -> anyhow::Result<Self> {
        let config = Self::raw()?.try_deserialize::<BergConfig>()?;
        Ok(config)
    }

    pub fn raw() -> anyhow::Result<Config> {
        let local_config_path = current_dir().map(add_berg_config_file)?;
        let global_config_path = berg_data_dir().map(add_berg_config_file)?;
        let mut config_builder = Config::builder();

        // adding sources starting with least significant location
        //
        // - global
        // - local path uppermost parent
        // - local path walking down to pwd
        // - pwd
        // - env variable with BERG_ prefix

        config_builder = config_builder.add_source(file_from_path(global_config_path.as_path()));
        tracing::debug!("config search in: {global_config_path:?}");

        let mut walk_up = local_config_path.clone();
        let walking_up = std::iter::from_fn(move || {
            walk_up
                .parent()
                .and_then(|parent| parent.parent())
                .map(add_berg_config_file)
                .map(|parent| {
                    walk_up = parent.clone();
                    parent
                })
        });

        let pwd = std::iter::once(local_config_path);
        let local_paths = pwd.chain(walking_up).collect::<Vec<_>>();

        for path in local_paths.iter().rev() {
            tracing::debug!("config search in: {path:?}");
            config_builder = config_builder.add_source(file_from_path(path));
        }

        config_builder = config_builder.add_source(config::Environment::with_prefix("BERG"));
        // add default values if no source has the value set

        for (field_name, default_value) in BergConfig::iter_default_field_value() {
            config_builder = config_builder.set_default(field_name, default_value)?;
        }

        config_builder.build().map_err(anyhow::Error::from)
    }
}

impl BergConfig {
    pub fn url(&self) -> anyhow::Result<Url> {
        let url = format!(
            "{protoc}://{url}",
            protoc = self.protocol,
            url = self.base_url
        );
        Url::parse(url.as_str())
            .context("The protocol + base url in the config don't add up to a valid url")
    }

    pub fn make_table(&self) -> Table {
        let mut table = Table::new();

        let preset = if self.fancy_tables {
            comfy_table::presets::UTF8_FULL
        } else {
            // print everything on one line for long lines
            table.set_width(u16::MAX);
            comfy_table::presets::NOTHING
        };

        table.load_preset(preset);

        table
    }
}

fn file_from_path(
    path: impl AsRef<Path>,
) -> config::File<config::FileSourceFile, config::FileFormat> {
    config::File::new(
        path.as_ref().to_str().unwrap_or_default(),
        config::FileFormat::Toml,
    )
    .required(false)
}

fn add_berg_config_file(dir: impl AsRef<Path>) -> PathBuf {
    dir.as_ref().join("berg.toml")
}

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

    fn make_config(path: PathBuf, config: BergConfig) -> anyhow::Result<()> {
        let config_path = add_berg_config_file(path);
        let toml = toml::to_string(&config)?;
        std::fs::write(config_path, toml)?;
        Ok(())
    }

    fn delete_config(path: PathBuf) -> anyhow::Result<()> {
        let config_path = add_berg_config_file(path);
        std::fs::remove_file(config_path)?;
        Ok(())
    }

    #[test]
    #[ignore = "doesn't work on nix in 'ci' because of no r/w permissions on the system"]
    fn berg_config_integration_test() -> anyhow::Result<()> {
        // ensure the directories are there while testing
        // (otherwise CI will fail)
        let local_dir = current_dir()?;
        std::fs::create_dir_all(local_dir)?;
        let global_dir = berg_data_dir()?;
        std::fs::create_dir_all(global_dir)?;

        // test local config
        let config = BergConfig {
            base_url: String::from("local"),
            ..Default::default()
        };
        make_config(current_dir()?, config)?;
        let config = BergConfig::new();
        assert!(config.is_ok(), "{config:?}");
        let config = config.unwrap();
        assert_eq!(config.base_url.as_str(), "local");
        delete_config(current_dir()?)?;

        // test global config
        let config = BergConfig {
            base_url: String::from("global"),
            ..Default::default()
        };
        make_config(berg_data_dir()?, config)?;
        let config = BergConfig::new();
        assert!(config.is_ok(), "{config:?}");
        let config = config.unwrap();
        assert_eq!(config.base_url.as_str(), "global");
        delete_config(berg_data_dir()?)?;

        // test creating template global config works
        let config = BergConfig::new();
        assert!(config.is_ok(), "{config:?}");
        let config = config.unwrap();
        assert_eq!(config.base_url.as_str(), "codeberg.org/");

        // testing behavior if both configs exist
        {
            // local
            let config = BergConfig {
                base_url: String::from("local"),
                ..Default::default()
            };
            make_config(current_dir()?, config)?;
        }
        {
            // global
            let config = BergConfig {
                base_url: String::from("global"),
                ..Default::default()
            };
            make_config(berg_data_dir()?, config)?;
        }
        let config = BergConfig::new();
        assert!(config.is_ok(), "{config:?}");
        let config = config.unwrap();
        assert_eq!(config.base_url.as_str(), "local");
        delete_config(current_dir()?)?;
        delete_config(berg_data_dir()?)?;

        Ok(())
    }
}