oro_config/
lib.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
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
//! Configuration loader for Orogene config files.

use std::{collections::HashSet, ffi::OsString, path::PathBuf};

pub use clap::{ArgMatches, Command};
pub use config::Config as OroConfig;
use config::{builder::DefaultState, ConfigBuilder, Environment, File, ValueKind};
use kdl_source::KdlFormat;
use miette::Result;

use error::OroConfigError;

mod error;
mod kdl_source;

pub trait OroConfigLayerExt {
    fn with_negations(self) -> Self;
    fn layered_args(&self, args: &mut Vec<OsString>, config: &OroConfig) -> Result<()>;
}

impl OroConfigLayerExt for Command {
    fn with_negations(self) -> Self {
        let negated = self
            .get_arguments()
            .filter(|opt| opt.get_long().is_some())
            .map(|opt| format!("no-{}", opt.get_long().expect("long option")))
            .collect::<Vec<_>>();
        let negations = self
            .get_arguments()
            .filter(|opt| opt.get_long().is_some())
            .zip(negated)
            .map(|(opt, negated)| {
                // This is a bit tricky. For arguments that we want to have
                // `--no-foo` for, but we want `foo` to default to true, we
                // need to set the `long` flag _on the original_ to `no-foo`,
                // and then this one will "reverse" it.
                let long = if negated.starts_with("no-no-") {
                    negated.replace("no-no-", "")
                } else {
                    negated.clone()
                };
                clap::Arg::new(negated)
                    .long(long)
                    .global(opt.is_global_set())
                    .hide(true)
                    .action(clap::ArgAction::SetTrue)
                    .overrides_with(opt.get_id())
            })
            .collect::<Vec<_>>();
        // Add the negations
        self.args(negations)
    }

    fn layered_args(&self, args: &mut Vec<OsString>, config: &OroConfig) -> Result<()> {
        let mut long_opts = HashSet::new();
        for opt in self.get_arguments() {
            if opt.get_long().is_some() {
                long_opts.insert(opt.get_id().to_string());
            }
        }
        let matches = self
            .clone()
            .ignore_errors(true)
            .get_matches_from(&args.clone());
        for opt in long_opts {
            // TODO: _prepend_ args unconditionally if they're coming from
            // config, so multi-args get parsed right. Right now, if you have
            // something in your config, it'll get completely overridden by
            // the command line.
            if matches.value_source(&opt) != Some(clap::parser::ValueSource::CommandLine) {
                let opt = opt.replace('_', "-");
                if !args.contains(&OsString::from(format!("--no-{opt}"))) {
                    if let Ok(bool) = config.get_bool(&opt) {
                        if bool {
                            args.push(OsString::from(format!("--{}", opt)));
                        } else {
                            args.push(OsString::from(format!("--no-{}", opt)));
                        }
                    } else if let Ok(value) = config.get_string(&opt) {
                        args.push(OsString::from(format!("--{}", opt)));
                        args.push(OsString::from(value));
                    } else if let Ok(value) = config.get_table(&opt) {
                        for (key, val) in value {
                            match &val.kind {
                                ValueKind::Table(map) => {
                                    for (k, v) in map {
                                        args.push(OsString::from(format!("--{}", opt)));
                                        args.push(OsString::from(format!("{{{key}}}{k}={v}")));
                                    }
                                }
                                // TODO: error if val.kind is an Array
                                _ => {
                                    args.push(OsString::from(format!("--{}", opt)));
                                    args.push(OsString::from(format!("{key}={val}")));
                                }
                            }
                        }
                    } else if let Ok(value) = config.get_array(&opt) {
                        for val in value {
                            if let Ok(val) = val.into_string() {
                                args.push(OsString::from(format!("--{}", opt)));
                                args.push(OsString::from(val));
                            }
                        }
                    }
                }
            }
        }
        Ok(())
    }
}

#[derive(Debug, Clone)]
pub struct OroConfigOptions {
    builder: ConfigBuilder<DefaultState>,
    global: bool,
    env: bool,
    pkg_root: Option<PathBuf>,
    global_config_file: Option<PathBuf>,
}

impl Default for OroConfigOptions {
    fn default() -> Self {
        OroConfigOptions {
            builder: OroConfig::builder(),
            global: true,
            env: true,
            pkg_root: None,
            global_config_file: None,
        }
    }
}

impl OroConfigOptions {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn global(mut self, global: bool) -> Self {
        self.global = global;
        self
    }

    pub fn env(mut self, env: bool) -> Self {
        self.env = env;
        self
    }

    pub fn pkg_root(mut self, root: Option<PathBuf>) -> Self {
        self.pkg_root = root;
        self
    }

    pub fn global_config_file(mut self, file: Option<PathBuf>) -> Self {
        self.global_config_file = file;
        self
    }

    pub fn set_default(mut self, key: &str, value: &str) -> Result<Self, OroConfigError> {
        self.builder = self.builder.set_default(key, value)?;
        Ok(self)
    }

    pub fn load(self) -> Result<OroConfig> {
        let mut builder = self.builder;
        if self.global {
            if let Some(config_file) = self.global_config_file {
                let path = config_file.display().to_string();
                builder = builder.add_source(File::new(&path, KdlFormat).required(false));
            }
        }
        if self.env {
            builder = builder.add_source(Environment::with_prefix("oro_config"));
        }
        if let Some(root) = self.pkg_root {
            builder = builder.add_source(
                File::new(&root.join("oro.kdl").display().to_string(), KdlFormat).required(false),
            );
        }
        Ok(builder.build().map_err(OroConfigError::ConfigError)?)
    }
}

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

    use std::env;
    use std::fs;

    use miette::{IntoDiagnostic, Result};
    use pretty_assertions::assert_eq;
    use tempfile::tempdir;

    #[test]
    fn env_configs() -> Result<()> {
        let dir = tempdir().into_diagnostic()?;
        env::set_var("ORO_CONFIG_STORE", dir.path().display().to_string());
        let config = OroConfigOptions::new().global(false).load()?;
        env::remove_var("ORO_CONFIG_STORE");
        assert_eq!(
            config.get_string("store").into_diagnostic()?,
            dir.path().display().to_string()
        );
        Ok(())
    }

    #[test]
    fn global_config() -> Result<()> {
        let dir = tempdir().into_diagnostic()?;
        let file = dir.path().join("oro.kdl");
        fs::write(&file, "options{\nstore \"hello world\"\n}").into_diagnostic()?;
        let config = OroConfigOptions::new()
            .env(false)
            .global_config_file(Some(file))
            .load()?;
        assert_eq!(
            config.get_string("store").into_diagnostic()?,
            String::from("hello world")
        );
        Ok(())
    }

    #[test]
    fn missing_config() -> Result<()> {
        let config = OroConfigOptions::new().global(false).env(false).load()?;
        assert!(config.get_string("store").is_err());
        Ok(())
    }
}