Skip to main content

argenv_resolve/
invocation.rs

1//! Resolving an invocation: what the program was actually given, and from where.
2use crate::{EnvSource, Finding, Record};
3use std::collections::BTreeMap;
4
5/// Which door a resolved value arrived through.
6///
7/// Carried on every resolved value because *"why is this value what it is?"* is
8/// the question a precedence chain otherwise makes unanswerable.
9#[derive(Clone, Copy, PartialEq, Eq, Debug)]
10pub enum Source {
11    /// An explicit command-line argument.
12    Arg,
13    /// An environment variable.
14    Env,
15    /// The declared default; nothing supplied a value.
16    Default,
17}
18
19impl std::fmt::Display for Source {
20    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21        f.write_str(match self {
22            Source::Arg => "argument",
23            Source::Env => "environment",
24            Source::Default => "default",
25        })
26    }
27}
28
29/// One resolved value and its provenance.
30#[derive(Clone, Debug, PartialEq)]
31pub struct Resolved {
32    /// The raw, unparsed text.
33    pub raw: String,
34    /// Where it came from.
35    pub source: Source,
36}
37
38/// What a program was invoked with: an argument vector and an environment.
39pub struct Invocation<'a> {
40    /// The arguments, **excluding** the program name.
41    pub args: &'a [String],
42    /// The environment.
43    pub env: &'a dyn EnvSource,
44}
45
46impl<'a> Invocation<'a> {
47    /// An invocation with no arguments, reading the given environment.
48    pub fn from_env(env: &'a dyn EnvSource) -> Invocation<'a> {
49        Invocation { args: &[], env }
50    }
51
52    /// Resolve every declared input against this invocation.
53    pub fn resolve(&self, model: &[Record]) -> Resolution {
54        let mut values: BTreeMap<String, Resolved> = BTreeMap::new();
55        let mut findings = Vec::new();
56
57        let parsed = parse_args(model, self.args, &mut findings);
58
59        resolve_positionals(model, &parsed.positionals, &mut values);
60
61        for (key, raw) in parsed.values {
62            values.insert(
63                key,
64                Resolved {
65                    raw,
66                    source: Source::Arg,
67                },
68            );
69        }
70
71        // The raw token in the invocation's first positional, if any — the
72        // subcommand actually given, compared as a plain string against each
73        // scoped record's own `subcommands` list. No step here identifies
74        // "the one true dispatcher": a record with an empty `subcommands`
75        // list is simply always in scope, and one with a non-empty list is
76        // in scope exactly when this token is in it — the same rule
77        // `resolve_positionals` already applies to argv, applied here to env.
78        let active_subcommand = parsed.positionals.first();
79
80        for r in model {
81            if values.contains_key(&r.key) {
82                continue;
83            }
84            if !r.subcommands.is_empty()
85                && active_subcommand.map(|s| r.subcommands.contains(s)) != Some(true)
86            {
87                continue; // scoped to subcommands that were not given — correctly unresolved
88            }
89            if let Some(raw) = r.env_names().iter().find_map(|n| self.env.get(n)) {
90                values.insert(
91                    r.key.clone(),
92                    Resolved {
93                        raw,
94                        source: Source::Env,
95                    },
96                );
97                continue;
98            }
99            if let Some(d) = &r.default {
100                values.insert(
101                    r.key.clone(),
102                    Resolved {
103                        raw: render_default(d),
104                        source: Source::Default,
105                    },
106                );
107            }
108        }
109
110        Resolution {
111            values,
112            positionals: parsed.positionals,
113            findings,
114            env_names: self.env.names(),
115        }
116    }
117}
118
119/// Everything an invocation resolved to, with provenance and any problems found.
120#[derive(Clone, Debug, Default)]
121pub struct Resolution {
122    values: BTreeMap<String, Resolved>,
123    positionals: Vec<String>,
124    findings: Vec<Finding>,
125    /// Every environment variable name present at resolution time, for
126    /// near-miss detection in the lint pass. Snapshotted here so that
127    /// `lint` can operate on `&Resolution` alone, with no `Invocation` needed.
128    pub(crate) env_names: Vec<String>,
129}
130
131impl Resolution {
132    /// The raw text resolved for `key`, if anything supplied one.
133    pub fn raw(&self, key: &str) -> Option<&str> {
134        self.values.get(key).map(|r| r.raw.as_str())
135    }
136
137    /// Where the value for `key` came from.
138    pub fn source(&self, key: &str) -> Option<Source> {
139        self.values.get(key).map(|r| r.source)
140    }
141
142    /// Every resolved value, by key.
143    pub fn values(&self) -> &BTreeMap<String, Resolved> {
144        &self.values
145    }
146
147    /// Arguments that were not flags, in order, plus anything after `--`.
148    pub fn positionals(&self) -> &[String] {
149        &self.positionals
150    }
151
152    /// Problems found while parsing the argument vector.
153    pub fn findings(&self) -> &[Finding] {
154        &self.findings
155    }
156}
157
158struct Parsed {
159    values: BTreeMap<String, String>,
160    positionals: Vec<String>,
161}
162
163/// Fill `values` from `positionals` for every record with `arg.position` set.
164///
165/// An unscoped record (`subcommands` empty) reads `positionals[position]`
166/// directly — `position` `0` is commonly a subcommand dispatch token, but
167/// nothing here requires that; a purely positional program with no dispatch
168/// at all (`cp <src> <dst>`) works the same way, one absolute slot each.
169///
170/// A record scoped to one or more subcommands reads `positionals[1 +
171/// position]` — one slot past the dispatch token — and only when the raw
172/// token at `positionals[0]` is one of its declared `subcommands`.
173/// Otherwise it is left unresolved, which is correct: for this invocation,
174/// that subcommand's input genuinely was not given.
175fn resolve_positionals(
176    model: &[Record],
177    positionals: &[String],
178    values: &mut BTreeMap<String, Resolved>,
179) {
180    let active_subcommand = positionals.first();
181
182    for r in model {
183        let Some(position) = r.arg.as_ref().and_then(|a| a.position) else {
184            continue;
185        };
186        let index = if r.subcommands.is_empty() {
187            position as usize
188        } else {
189            match active_subcommand {
190                Some(s) if r.subcommands.contains(s) => 1 + position as usize,
191                _ => continue, // wrong (or no) subcommand given — correctly unresolved
192            }
193        };
194        if let Some(raw) = positionals.get(index) {
195            values.insert(
196                r.key.clone(),
197                Resolved {
198                    raw: raw.clone(),
199                    source: Source::Arg,
200                },
201            );
202        }
203    }
204}
205
206/// Parse an argument vector against a model.
207///
208/// Recognised forms — chosen to match long-standing convention rather than to
209/// invent one:
210///
211/// * `--flag`, `--no-flag` (when negatable)
212/// * `--opt value`, `--opt=value`
213/// * `-f`, `-o value`, `-ovalue`
214/// * `-abc`, bundling several no-value short flags
215/// * `--`, after which everything is positional
216///
217/// A repeated flag accumulates when the input is a list, and otherwise the last
218/// occurrence wins. Anything unrecognised becomes a [`Finding`] rather than
219/// being dropped in silence.
220fn parse_args(model: &[Record], args: &[String], findings: &mut Vec<Finding>) -> Parsed {
221    let mut values: BTreeMap<String, String> = BTreeMap::new();
222    let mut positionals = Vec::new();
223    let mut i = 0usize;
224
225    while i < args.len() {
226        let a = &args[i];
227
228        if a == "--" {
229            positionals.extend(args[i + 1..].iter().cloned());
230            break;
231        }
232
233        if let Some(body) = a.strip_prefix("--") {
234            let (name, inline) = match body.split_once('=') {
235                Some((n, v)) => (n, Some(v.to_string())),
236                None => (body, None),
237            };
238
239            // Negation: --no-colour sets the boolean off.
240            if let Some(base) = name.strip_prefix("no-") {
241                if let Some(r) = find_long(model, base)
242                    .filter(|r| r.arg.as_ref().map(|a| a.negatable).unwrap_or(false))
243                {
244                    values.insert(r.key.clone(), "false".to_string());
245                    i += 1;
246                    continue;
247                }
248            }
249
250            match find_long(model, name) {
251                Some(r) => {
252                    let arity = r.arg.as_ref().map(|a| a.arity).unwrap_or(1);
253                    if arity == 0 {
254                        if inline.is_some() {
255                            findings.push(Finding::UnexpectedValue {
256                                arg: format!("--{name}"),
257                            });
258                        }
259                        values.insert(r.key.clone(), "true".to_string());
260                        i += 1;
261                    } else {
262                        match inline.or_else(|| args.get(i + 1).cloned()) {
263                            Some(v) => {
264                                accumulate(&mut values, r, v);
265                                i += if a.contains('=') { 1 } else { 2 };
266                            }
267                            None => {
268                                findings.push(Finding::MissingValue {
269                                    arg: format!("--{name}"),
270                                });
271                                i += 1;
272                            }
273                        }
274                    }
275                }
276                None => {
277                    findings.push(unknown_arg(model, &format!("--{name}")));
278                    i += 1;
279                }
280            }
281            continue;
282        }
283
284        if a.len() > 1 && a.starts_with('-') {
285            let body = &a[1..];
286            let first = body.chars().next().expect("non-empty");
287            match find_short(model, first) {
288                Some(r) => {
289                    let arity = r.arg.as_ref().map(|a| a.arity).unwrap_or(1);
290                    let rest: String = body.chars().skip(1).collect();
291                    if arity == 0 {
292                        values.insert(r.key.clone(), "true".to_string());
293                        if rest.is_empty() {
294                            i += 1;
295                        } else {
296                            // Bundled shorts: -abc. Re-enter with the remainder.
297                            let mut rebuilt = vec![format!("-{rest}")];
298                            rebuilt.extend(args[i + 1..].iter().cloned());
299                            let sub = parse_args(model, &rebuilt, findings);
300                            values.extend(sub.values);
301                            positionals.extend(sub.positionals);
302                            break;
303                        }
304                    } else {
305                        let value = if !rest.is_empty() {
306                            Some(rest.trim_start_matches('=').to_string())
307                        } else {
308                            args.get(i + 1).cloned()
309                        };
310                        match value {
311                            Some(v) => {
312                                accumulate(&mut values, r, v);
313                                i += if rest.is_empty() { 2 } else { 1 };
314                            }
315                            None => {
316                                findings.push(Finding::MissingValue {
317                                    arg: format!("-{first}"),
318                                });
319                                i += 1;
320                            }
321                        }
322                    }
323                }
324                None => {
325                    findings.push(unknown_arg(model, &format!("-{first}")));
326                    i += 1;
327                }
328            }
329            continue;
330        }
331
332        positionals.push(a.clone());
333        i += 1;
334    }
335
336    Parsed {
337        values,
338        positionals,
339    }
340}
341
342/// A repeated flag accumulates for a list input, and otherwise the last wins.
343fn accumulate(values: &mut BTreeMap<String, String>, r: &Record, v: String) {
344    let repeatable = r.arg.as_ref().map(|a| a.repeatable).unwrap_or(false);
345    match values.get(&r.key) {
346        Some(prev) if repeatable => {
347            let sep = r
348                .separators
349                .first()
350                .map(String::as_str)
351                .unwrap_or(",")
352                .to_string();
353            let joined = format!("{prev}{sep}{v}");
354            values.insert(r.key.clone(), joined);
355        }
356        _ => {
357            values.insert(r.key.clone(), v);
358        }
359    }
360}
361
362fn find_long<'a>(model: &'a [Record], name: &str) -> Option<&'a Record> {
363    model
364        .iter()
365        .find(|r| r.arg.as_ref().and_then(|a| a.long.as_deref()) == Some(name))
366}
367
368fn find_short(model: &[Record], c: char) -> Option<&Record> {
369    model.iter().find(|r| {
370        r.arg
371            .as_ref()
372            .and_then(|a| a.short.as_deref())
373            .and_then(|s| s.chars().next())
374            == Some(c)
375    })
376}
377
378fn unknown_arg(model: &[Record], label: &str) -> Finding {
379    let known: Vec<String> = model.iter().flat_map(Record::arg_labels).collect();
380    Finding::UnknownArg {
381        arg: label.to_string(),
382        did_you_mean: crate::lint::nearest(label, &known),
383    }
384}
385
386/// Render a declared default as the text an equivalent invocation would carry.
387fn render_default(v: &serde_json::Value) -> String {
388    match v {
389        serde_json::Value::String(s) => s.clone(),
390        other => other.to_string(),
391    }
392}