aboutsummaryrefslogtreecommitdiffstats
path: root/crates/config/src/arguments.rs
blob: 2cb26b345d6f7873bbbd448432a95785eae5f0ee (plain)
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
//! 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, anyhow, 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_in, overlay, unset_entry,
};
use crate::option::{Kind, OptionSpec, Schema, from_text};

pub const CONFIG: &str = "config";
/// Printing the report of the configuration and exiting (`with_print_config`).
pub const PRINT_CONFIG: &str = "print-config";
/// Naming an importer (`import::Importers`): `--meta-importer-NAME IMPORTER`, as
/// `[meta.importer] NAME = …` in a file (`take_importers`).
pub const META_IMPORTER: &str = "meta-importer";

/// `command` taking `--print-config`: a program given it prints its configuration's
/// report (`report::report`) and exits (`prints_config`).
pub fn with_print_config(command: Command) -> Command {
    command.arg(
        Arg::new(PRINT_CONFIG)
            .long(PRINT_CONFIG)
            .action(ArgAction::SetTrue)
            .help("Print the effective configuration as JSON (with each value's source) and exit."),
    )
}

/// Whether `--print-config` was given.
pub fn prints_config(matches: &ArgMatches) -> bool {
    matches.get_flag(PRINT_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(
            // For the help alone: the names are whatever follows `--meta-importer-`,
            // taken off the command line before it is read (`take_importers`).
            Arg::new(META_IMPORTER)
                .long("meta-importer-NAME")
                .value_name("IMPORTER")
                .help("Name an importer: NAME:REST is then IMPORTER (env:, file:, cmd:), with REST as its variable `name`, in every file and argument; as [meta.importer] NAME in a file."),
        )
        .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 arguments `arguments` without those naming importers (`--meta-importer-NAME
/// IMPORTER`, or with `=`), and the importers they name: taken off before the command
/// line is read, as their names are the configuration's, not the command's. Nothing
/// after `--` is one.
pub fn take_importers(
    arguments: impl IntoIterator<Item = String>,
) -> Result<(Vec<String>, import::Importers)> {
    let prefix = format!("--{META_IMPORTER}-");
    let mut named = import::Importers::new();
    let mut others = Vec::new();
    let mut arguments = arguments.into_iter();
    while let Some(argument) = arguments.next() {
        if argument == "--" {
            others.push(argument);
            others.extend(arguments);
            break;
        }
        let Some(rest) = argument.strip_prefix(&prefix) else {
            others.push(argument);
            continue;
        };
        let (name, importer) = match rest.split_once('=') {
            Some((name, importer)) => (name.to_owned(), importer.to_owned()),
            None => {
                let importer = arguments
                    .next()
                    .ok_or_else(|| anyhow!("{argument} takes an importer"))?;
                (rest.to_owned(), importer)
            }
        };
        let importer = import::named_by_argument(&name, &importer)
            .with_context(|| format!("{prefix}{name}"))?;
        named.insert(name, importer);
    }
    Ok((others, named))
}

/// The importers the configuration names: those of the files `files`, in order, then
/// `by_arguments`, those its arguments name (`take_importers`); of two of one name, the
/// later.
pub fn importers(files: &[PathBuf], by_arguments: &import::Importers) -> Result<import::Importers> {
    let mut named = import::Importers::new();
    for path in files {
        named.extend(file::importers(path)?);
    }
    named.extend(by_arguments.clone());
    Ok(named)
}

/// The values of `options` given as arguments, where no importers are named.
pub fn arguments(matches: &ArgMatches, schema: &Schema) -> Result<Layer> {
    arguments_in(matches, schema, &import::Importers::new())
}

/// The values of `options` given as arguments (unsets first, so a value given too wins);
/// `named` are the importers the configuration names.
pub fn arguments_in(
    matches: &ArgMatches,
    schema: &Schema,
    named: &import::Importers,
) -> 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_in(raw, named) {
                    Raw::Literal(text) => from_text(spec.kind, text).inspect(|value| {
                        sources.literal(value);
                    }),
                    Raw::Import(importer) => {
                        sources.import(&importer);
                        from_import_in(spec.kind, &importer, named)
                    }
                }
                .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>)> {
    merged_in(matches, schema, first, &import::Importers::new())
}

/// `merged`, with the importers the arguments name (`take_importers`).
pub fn merged_in(
    matches: &ArgMatches,
    schema: &Schema,
    first: &[PathBuf],
    by_arguments: &import::Importers,
) -> 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 named = importers(&files, by_arguments)?;
    let mut merged = Layer::new();
    for path in &files {
        for (name, entry) in file::load_in(path, schema, &named)? {
            overlay(&mut merged, name, entry, Overlay::FileOverFile, schema);
        }
    }
    for (name, entry) in arguments_in(matches, schema, &named)? {
        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 (arguments, named) =
            take_importers(arguments.iter().map(|argument| (*argument).to_owned()))?;
        let command = with_options(Command::new("program"), OPTIONS);
        let matches =
            command.try_get_matches_from(std::iter::once("program".to_owned()).chain(arguments))?;
        merged_in(&matches, &SCHEMA, &[], &named).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.json",
            r#"{"name": "base", "peers": ["a", "b"], "local": "here"}"#,
        );
        scratch.file(
            "main.json",
            r#"{"include": ["base.json"], "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"));
        // The report: each option's value and where it is from, a secret's left out.
        let settings: serde_json::Map<String, JsonValue> = layer
            .iter()
            .map(|(name, entry)| (name.clone(), entry.value.clone()))
            .collect();
        let origins = layer
            .iter()
            .map(|(name, entry)| (name.clone(), entry.origin.clone()))
            .collect();
        let files = [scratch.0.join("main.json")];
        let report = crate::report::report(
            &SCHEMA,
            &settings,
            &origins,
            &files,
            crate::report::Values::Interpolated,
        );
        assert_eq!(report["files"], json!([path("main.json")]));
        let options = &report["options"];
        assert_eq!(options["name"]["value"], json!("main"));
        assert_eq!(options["name"]["source"], json!("file"));
        assert!(
            options["name"]["file"]
                .as_str()
                .is_some_and(|file| file.ends_with("main.json"))
        );
        assert_eq!(
            options["remote"],
            json!({ "source": "default", "value": null })
        );
        assert_eq!(options["token"]["secret"], json!(true));
        assert!(options["token"].get("value").is_none());
        assert!(!report.to_string().contains("hush"));
        let command = with_print_config(with_options(Command::new("program"), OPTIONS));
        let matches = command
            .try_get_matches_from(["program", "--print-config"])
            .unwrap();
        assert!(prints_config(&matches));
        // 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.json", r#"{"nmae": "x"}"#);
        let said = format!(
            "{:#}",
            merged_of(&["--config", &path("unknown.json")]).unwrap_err()
        );
        assert!(said.contains("unknown option"), "{said}");
        scratch.file("gone.json", r#"{"legacy": "x"}"#);
        let said = format!(
            "{:#}",
            merged_of(&["--config", &path("gone.json")]).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());
    }

    /// Importers a configuration names (`[meta.importer]`, `--meta-importer-NAME`) count in
    /// every file and argument, wherever they are named; of two of one name, the later
    /// source's.
    #[test]
    fn importers_named_in_files_and_arguments() {
        let scratch = Scratch::new("arguments-importers");
        let path = |name: &str| scratch.0.join(name).display().to_string();
        scratch.file(
            "names.json",
            r#"{"meta": {"importer": {
                "show": {"command": ["printf", "<%s>", "$(var:name)"]},
                "kept": "file:$(var:name)"}}}"#,
        );
        scratch.file(
            "main.json",
            r#"{"include": ["names.json"], "name": {"show": "main"}, "token": {"kept": "secret"},
                "peers": ["a", "$(show:b)", {"show": "c"}]}"#,
        );
        scratch.file("secret", "hush\n");
        let layer = merged_of(&["--config", &path("main.json")]).unwrap();
        assert_eq!(layer["name"].value, json!("<main>"));
        assert_eq!(layer["token"].value, json!("hush"));
        assert_eq!(layer["peers"].value, json!(["a", "<b>", "<c>"]));
        // Shown as written, not as what it stands for.
        assert_eq!(layer["name"].origin.imports, ["show:main"]);

        // Named in a later file, or by an argument: in an earlier file too; and in
        // arguments.
        scratch.file(
            "first.json",
            r#"{"name": {"late": "x"}, "local": "$(late:y)"}"#,
        );
        scratch.file(
            "later.json",
            r#"{"meta": {"importer": {"late": "cmd:printf 'later-%s' $(var:name)"}}}"#,
        );
        let files = [
            "--config",
            &path("first.json"),
            "--config",
            &path("later.json"),
        ];
        let layer = merged_of(&files).unwrap();
        assert_eq!(layer["name"].value, json!("later-x"));
        assert_eq!(layer["local"].value, json!("later-y"));
        // Of two of one name, the argument's, over the files'.
        let mut by_argument = files.to_vec();
        by_argument.extend([
            "--meta-importer-late",
            "cmd:printf 'argument-%s' $(var:name)",
            "--remote",
            "late:z",
        ]);
        let layer = merged_of(&by_argument).unwrap();
        assert_eq!(layer["name"].value, json!("argument-x"));
        assert_eq!(layer["remote"].value, json!("argument-z"));
        // Unnamed, it is text on the command line, and no importer in a file.
        let layer = merged_of(&["--name", "late:z"]).unwrap();
        assert_eq!(layer["name"].value, json!("late:z"));
        assert!(merged_of(&["--config", &path("first.json")]).is_err());

        // What `meta` takes.
        for (file, refused) in [
            ("other.json", r#"{"meta": {"other": 1}}"#),
            ("list.json", r#"{"meta": {"importer": ["a"]}}"#),
            (
                "builtin.json",
                r#"{"meta": {"importer": {"env": "cmd:true"}}}"#,
            ),
            ("text.json", r#"{"meta": 1}"#),
        ] {
            scratch.file(file, refused);
            assert!(merged_of(&["--config", &path(file)]).is_err(), "{refused}");
        }
        // With `=`, too; and what it takes.
        let layer = merged_of(&[
            "--meta-importer-late=cmd:printf '=%s' $(var:name)",
            "--name",
            "late:z",
        ])
        .unwrap();
        assert_eq!(layer["name"].value, json!("=z"));
        assert!(merged_of(&["--meta-importer-late"]).is_err());
        assert!(merged_of(&["--meta-importer-late", "plain"]).is_err());
        assert!(merged_of(&["--meta-importer-file", "cmd:true"]).is_err());
        // After `--`, it is the command's.
        let (rest, named) =
            take_importers(["--", "--meta-importer-late", "cmd:true"].map(str::to_owned)).unwrap();
        assert_eq!((rest.len(), named.len()), (3, 0));
    }
}