-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
lib.rs
212 lines (190 loc) · 6.47 KB
/
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
//! Configuration loader for Orogene config files.
use std::{
collections::{HashMap, HashSet},
path::PathBuf, ffi::OsString,
};
pub use clap::{ArgMatches, Command};
pub use config::Config as OroConfig;
use config::{builder::DefaultState, ConfigBuilder, ConfigError, Environment, File};
use miette::{Diagnostic, Result};
use thiserror::Error;
pub trait OroConfigLayerExt {
fn with_negations(self) -> Self;
fn layered_matches(self, config: &OroConfig) -> Result<ArgMatches>;
}
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)| {
clap::Arg::new(negated.clone())
.long(negated)
.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_matches(mut self, config: &OroConfig) -> Result<ArgMatches> {
// Add the negations
self = self.with_negations();
let mut short_opts = HashMap::new();
let mut long_opts = HashSet::new();
for opt in self.get_arguments() {
if let Some(short) = opt.get_short() {
short_opts.insert(short, (*opt).clone());
}
if let Some(long) = opt.get_long() {
long_opts.insert(long.to_string());
}
}
let mut args = std::env::args_os().collect::<Vec<_>>();
let matches = self.clone().get_matches_from(&args);
for opt in long_opts {
if matches.value_source(&opt) != Some(clap::parser::ValueSource::CommandLine) {
if let Ok(value) = config.get_string(&opt) {
if !args.contains(&OsString::from(format!("--no-{}", opt))) {
args.push(OsString::from(format!("--{}", opt)));
args.push(OsString::from(value));
}
}
}
}
// Check for missing flags and inject config options into
Ok(self.get_matches_from(args))
}
}
#[derive(Debug, Error, Diagnostic)]
pub enum OroConfigError {
#[error(transparent)]
#[diagnostic(code(config::error))]
ConfigError(#[from] ConfigError),
#[error(transparent)]
#[diagnostic(code(config::error))]
ConfigParseError(#[from] Box<dyn std::error::Error + Send + Sync>),
}
#[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::with_name(&path[..]).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::with_name(&root.join("ororc").display().to_string()).required(false),
)
.add_source(
File::with_name(&root.join(".ororc").display().to_string()).required(false),
)
.add_source(
File::with_name(&root.join("ororc.toml").display().to_string()).required(false),
)
.add_source(
File::with_name(&root.join(".ororc.toml").display().to_string())
.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("ororc.toml");
fs::write(&file, "store = \"hello world\"").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(())
}
}