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
|
//! The command line: a program's options as arguments, the configuration files it
//! names (`--config`) and what it unsets of theirs (`--unset`), put together.
use std::path::PathBuf;
use anyhow::{Context, Result, bail};
use clap::parser::ValueSource;
use clap::{Arg, ArgAction, ArgMatches, Command};
use serde_json::Value as JsonValue;
use crate::file::{self, UNSET};
use crate::import::{self, Raw};
use crate::layer::{Entry, Layer, Overlay, Provenance, Sources, from_import, overlay, unset_entry};
use crate::option::{Kind, OptionSpec, Schema, from_text};
pub const CONFIG: &str = "config";
/// Stops on an argument naming an option that is gone, saying why, before the command
/// line is read: clap would call it unexpected.
pub fn refuse_gone(arguments: impl IntoIterator<Item = String>, schema: &Schema) -> Result<()> {
for argument in arguments {
let Some(name) = argument.strip_prefix("--") else {
continue;
};
let name = name.split('=').next().unwrap_or(name);
if let Some(why) = schema.gone(name) {
bail!("--{name} is gone: {why}");
}
}
Ok(())
}
/// `command` taking `options` as arguments, and configuration files for them
/// (`--config`) and unsets of what those set (`--unset`).
pub fn with_options(command: Command, options: &'static [OptionSpec]) -> Command {
let mut command = command
.after_help(
"Every option can also be set in a configuration file (--config); arguments win.\n\
A value can be imported instead of written out: env:NAME, file:PATH or cmd:COMMAND \
(as text), or env+json:, file+json:, cmd+json: (parsed as JSON). \
literal:VALUE passes a value that starts with one of these prefixes.",
)
.arg(
Arg::new(CONFIG)
.long(CONFIG)
.value_name("PATH")
.action(ArgAction::Append)
.help("Configuration file (.toml or .json); repeatable, later files win."),
)
.arg(
Arg::new(UNSET)
.long(UNSET)
.value_name("OPTION")
.action(ArgAction::Append)
.help("Unset an option set by a configuration file (back to its default); repeatable."),
);
for spec in options {
let help = match spec.default {
Some(default) => format!("{} [default: {default}]", spec.help),
None => spec.help.to_owned(),
};
let arg = Arg::new(spec.name)
.long(spec.name)
.help(help)
.hide(spec.hidden);
command = command.arg(match spec.kind {
Kind::Flag => arg.action(ArgAction::SetTrue),
Kind::List => arg.value_name(spec.value_name).action(ArgAction::Append),
Kind::Text | Kind::Integer | Kind::Duration | Kind::Size => {
arg.value_name(spec.value_name).action(ArgAction::Set)
}
});
}
command
}
/// The values of `options` given as arguments (unsets first, so a value given too wins).
pub fn arguments(matches: &ArgMatches, schema: &Schema) -> Result<Layer> {
let mut layer = Layer::new();
for name in matches.get_many::<String>(UNSET).into_iter().flatten() {
if schema.spec(name).is_none() {
bail!("--unset {name}: no such option");
}
layer.insert(name.clone(), unset_entry(Provenance::Argument));
}
for spec in schema.options {
if matches.value_source(spec.name) != Some(ValueSource::CommandLine) {
continue;
}
let mut sources = Sources::default();
let value = if spec.kind == Kind::Flag {
JsonValue::Bool(true)
} else {
let mut values = Vec::new();
for raw in matches.get_many::<String>(spec.name).into_iter().flatten() {
let value = match import::parse_argument(raw) {
Raw::Literal(text) => from_text(spec.kind, text).inspect(|value| {
sources.literal(value);
}),
Raw::Import(importer) => {
sources.import(&importer);
from_import(spec.kind, &importer)
}
}
.with_context(|| format!("--{}", spec.name))?;
values.push(value);
}
if spec.kind == Kind::List {
JsonValue::Array(
values
.into_iter()
.flat_map(|value| match value {
JsonValue::Array(items) => items,
other => vec![other],
})
.collect(),
)
} else {
values.pop().unwrap_or(JsonValue::Null)
}
};
layer.insert(
spec.name.to_owned(),
Entry {
value,
origin: sources.origin(Provenance::Argument, false, spec.kind),
},
);
}
Ok(layer)
}
/// The values of the options of `schema`: from the configuration files `first` and then
/// those `matches` names (`--config`), in order, later ones winning, then from its
/// arguments; and those files.
pub fn merged(
matches: &ArgMatches,
schema: &Schema,
first: &[PathBuf],
) -> Result<(Layer, Vec<PathBuf>)> {
let files: Vec<PathBuf> = first
.iter()
.cloned()
.chain(
matches
.get_many::<String>(CONFIG)
.into_iter()
.flatten()
.map(PathBuf::from),
)
.collect();
let mut merged = Layer::new();
for path in &files {
for (name, entry) in file::load(path, schema)? {
overlay(&mut merged, name, entry, Overlay::FileOverFile, schema);
}
}
for (name, entry) in arguments(matches, schema)? {
overlay(&mut merged, name, entry, Overlay::ArgumentOverFile, schema);
}
Ok((merged, files))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::option::{OptionSpec, option};
use crate::testing::Scratch;
use serde_json::json;
const OPTIONS: &[OptionSpec] = &[
option("name", Kind::Text, "NAME", None, "A name"),
option("peers", Kind::List, "PEER,[...]", None, "Peers"),
option("local", Kind::Text, "PATH", None, "A local one"),
option("remote", Kind::Text, "URL", None, "A remote one"),
option("token", Kind::Text, "TOKEN", None, "A token").secret(),
];
const SCHEMA: Schema = Schema {
options: OPTIONS,
conflicts: &[(&["remote"], &["local"])],
gone: &[("legacy", "use name instead")],
};
fn merged_of(arguments: &[&str]) -> Result<Layer> {
let command = with_options(Command::new("program"), OPTIONS);
let matches = command
.try_get_matches_from(std::iter::once("program").chain(arguments.iter().copied()))?;
merged(&matches, &SCHEMA, &[]).map(|(layer, _)| layer)
}
/// A program's own options, by its schema: files in order, a file over its
/// includes, arguments over files; unsets; a conflict dropping the earlier side; an
/// option that is gone said as such, in a file and as an argument.
#[test]
fn files_and_arguments_of_a_schema_of_ones_own() {
let scratch = Scratch::new("arguments");
let path = |name: &str| scratch.0.join(name).display().to_string();
scratch.file(
"base.toml",
"name = \"base\"\npeers = [\"a\", \"b\"]\nlocal = \"here\"\n",
);
scratch.file(
"main.json",
r#"{"include": ["base.toml"], "name": "main", "token": {"file": "secret"}}"#,
);
scratch.file("secret", "hush\n");
let layer = merged_of(&["--config", &path("main.json")]).unwrap();
assert_eq!(layer["name"].value, json!("main"));
assert_eq!(layer["peers"].value, json!(["a", "b"]));
assert_eq!(layer["token"].value, json!("hush"));
assert_eq!(layer["token"].shown(SCHEMA.secret("token")), "<secret>");
assert!(layer["name"].origin.to_string().ends_with("main.json"));
// Arguments over files, and an unset back to the default.
let layer = merged_of(&[
"--config",
&path("main.json"),
"--name",
"given",
"--unset",
"peers",
])
.unwrap();
assert_eq!(layer["name"].value, json!("given"));
assert_eq!(layer["name"].origin.provenance, Provenance::Argument);
assert!(layer["peers"].value.is_null() && layer["peers"].origin.unset);
// What can't be combined: the later source's side stays.
let layer = merged_of(&["--config", &path("main.json"), "--remote", "there"]).unwrap();
assert!(!layer.contains_key("local"));
assert_eq!(layer["remote"].value, json!("there"));
// Unknown, and gone.
scratch.file("unknown.toml", "nmae = \"x\"\n");
let said = format!(
"{:#}",
merged_of(&["--config", &path("unknown.toml")]).unwrap_err()
);
assert!(said.contains("unknown option"), "{said}");
scratch.file("gone.toml", "legacy = \"x\"\n");
let said = format!(
"{:#}",
merged_of(&["--config", &path("gone.toml")]).unwrap_err()
);
assert!(said.contains("use name instead"), "{said}");
let said = refuse_gone(["--legacy=x".to_owned()], &SCHEMA).unwrap_err();
assert!(said.to_string().contains("use name instead"));
assert!(refuse_gone(["--name".to_owned()], &SCHEMA).is_ok());
}
}
|