Skip to main content

cornerstone/
parse.rs

1//! Zero-dependency argument parser.
2//!
3//! Given a [`Command`] spec and the raw arguments, produces [`Matches`]: the
4//! resolved positional values and flag values. Supports:
5//!
6//! * `--long value` and `--long=value`
7//! * `-s value` and `-svalue`
8//! * bundled boolean shorts: `-abc` == `-a -b -c`
9//! * `--` to stop flag parsing; everything after is positional
10//! * variadic trailing positionals
11//!
12//! Parse errors are [`crate::error::Error`] with the `USAGE` exit code.
13
14use crate::error::{Error, Result};
15use crate::spec::{Command, FlagKind};
16use std::collections::HashMap;
17
18/// The result of parsing: flag values and positional arguments by name.
19#[derive(Debug, Default, Clone)]
20pub struct Matches {
21    bools: HashMap<String, bool>,
22    values: HashMap<String, String>,
23    positionals: HashMap<String, Vec<String>>,
24}
25
26impl Matches {
27    /// Whether a boolean switch was present.
28    pub fn flag(&self, long: &str) -> bool {
29        self.bools.get(long).copied().unwrap_or(false)
30    }
31
32    /// The value of a value-flag, if present (or its default).
33    pub fn value(&self, long: &str) -> Option<&str> {
34        self.values.get(long).map(|s| s.as_str())
35    }
36
37    /// A required positional; errors if missing.
38    pub fn arg(&self, name: &str) -> Result<&str> {
39        self.positionals
40            .get(name)
41            .and_then(|v| v.first())
42            .map(|s| s.as_str())
43            .ok_or_else(|| Error::usage(format!("missing required argument <{}>", name)))
44    }
45
46    /// An optional positional.
47    pub fn arg_opt(&self, name: &str) -> Option<&str> {
48        self.positionals.get(name).and_then(|v| v.first()).map(|s| s.as_str())
49    }
50
51    /// All values of a variadic positional.
52    pub fn args(&self, name: &str) -> Vec<String> {
53        self.positionals.get(name).cloned().unwrap_or_default()
54    }
55}
56
57/// Parse `raw` against `cmd`. `raw` should exclude the program name and the
58/// subcommand token (i.e. just the arguments to this command).
59pub fn parse(cmd: &Command, raw: &[String]) -> Result<Matches> {
60    let mut m = Matches::default();
61
62    // Seed defaults for value-flags.
63    for f in &cmd.flags {
64        if let Some(d) = &f.default {
65            m.values.insert(f.long.clone(), d.clone());
66        }
67        if f.kind == FlagKind::Bool {
68            m.bools.insert(f.long.clone(), false);
69        }
70    }
71
72    let mut positional_values: Vec<String> = Vec::new();
73    let mut i = 0;
74    let mut no_more_flags = false;
75
76    while i < raw.len() {
77        let tok = &raw[i];
78
79        if no_more_flags {
80            positional_values.push(tok.clone());
81            i += 1;
82            continue;
83        }
84
85        if tok == "--" {
86            no_more_flags = true;
87            i += 1;
88            continue;
89        }
90
91        if let Some(rest) = tok.strip_prefix("--") {
92            // Long flag, possibly --key=value.
93            let (name, inline_val) = match rest.split_once('=') {
94                Some((k, v)) => (k, Some(v.to_string())),
95                None => (rest, None),
96            };
97            let flag = cmd
98                .flags
99                .iter()
100                .find(|f| f.long == name)
101                .ok_or_else(|| Error::usage(format!("unknown flag --{}", name)))?;
102            match flag.kind {
103                FlagKind::Bool => {
104                    if inline_val.is_some() {
105                        return Err(Error::usage(format!("flag --{} takes no value", name)));
106                    }
107                    m.bools.insert(flag.long.clone(), true);
108                }
109                FlagKind::Value => {
110                    let val = if let Some(v) = inline_val {
111                        v
112                    } else {
113                        i += 1;
114                        raw.get(i)
115                            .cloned()
116                            .ok_or_else(|| Error::usage(format!("flag --{} needs a value", name)))?
117                    };
118                    m.values.insert(flag.long.clone(), val);
119                }
120            }
121            i += 1;
122            continue;
123        }
124
125        if tok.len() > 1 && tok.starts_with('-') && tok != "-" {
126            // Short flag(s). Could be bundled bools, or -s value, or -svalue.
127            let chars: Vec<char> = tok[1..].chars().collect();
128            let mut consumed_value = false;
129            for (ci, c) in chars.iter().enumerate() {
130                let flag = cmd
131                    .flags
132                    .iter()
133                    .find(|f| f.short == Some(*c))
134                    .ok_or_else(|| Error::usage(format!("unknown flag -{}", c)))?;
135                match flag.kind {
136                    FlagKind::Bool => {
137                        m.bools.insert(flag.long.clone(), true);
138                    }
139                    FlagKind::Value => {
140                        // The rest of this token is the value, if any; otherwise
141                        // the next token.
142                        let remainder: String = chars[ci + 1..].iter().collect();
143                        let val = if !remainder.is_empty() {
144                            remainder
145                        } else {
146                            i += 1;
147                            raw.get(i).cloned().ok_or_else(|| {
148                                Error::usage(format!("flag -{} needs a value", c))
149                            })?
150                        };
151                        m.values.insert(flag.long.clone(), val);
152                        consumed_value = true;
153                        break;
154                    }
155                }
156            }
157            let _ = consumed_value;
158            i += 1;
159            continue;
160        }
161
162        // Bare positional.
163        positional_values.push(tok.clone());
164        i += 1;
165    }
166
167    // Bind positionals to their declared names.
168    let mut pv = positional_values.into_iter();
169    for (idx, arg) in cmd.args.iter().enumerate() {
170        if arg.variadic {
171            let rest: Vec<String> = pv.by_ref().collect();
172            if arg.required && rest.is_empty() {
173                return Err(Error::usage(format!(
174                    "missing required argument <{}>",
175                    arg.name
176                )));
177            }
178            m.positionals.insert(arg.name.clone(), rest);
179            break;
180        }
181        match pv.next() {
182            Some(v) => {
183                m.positionals.insert(arg.name.clone(), vec![v]);
184            }
185            None => {
186                if arg.required {
187                    return Err(Error::usage(format!(
188                        "missing required argument <{}>",
189                        arg.name
190                    )));
191                }
192            }
193        }
194        let _ = idx;
195    }
196
197    // Any leftover positionals are an error (unless the last arg was variadic,
198    // in which case we already consumed them).
199    let leftover: Vec<String> = pv.collect();
200    if !leftover.is_empty() {
201        return Err(Error::usage(format!(
202            "unexpected argument(s): {}",
203            leftover.join(" ")
204        )));
205    }
206
207    Ok(m)
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213    use crate::spec::{Arg, Command, Flag};
214
215    fn cmd() -> Command {
216        let mut c = Command::new("t");
217        c.args.push(Arg::new("name"));
218        c.args.push(Arg::new("extra").optional());
219        c.flags.push(Flag::switch("verbose").short('v'));
220        c.flags.push(Flag::value("output").short('o'));
221        c
222    }
223
224    fn parse_ok(raw: &[&str]) -> Matches {
225        let owned: Vec<String> = raw.iter().map(|s| s.to_string()).collect();
226        parse(&cmd(), &owned).expect("should parse")
227    }
228
229    #[test]
230    fn positional_required_and_optional() {
231        let m = parse_ok(&["alice"]);
232        assert_eq!(m.arg("name").unwrap(), "alice");
233        assert!(m.arg_opt("extra").is_none());
234        let m = parse_ok(&["alice", "bob"]);
235        assert_eq!(m.arg_opt("extra"), Some("bob"));
236    }
237
238    #[test]
239    fn missing_required_is_usage_error() {
240        let e = parse(&cmd(), &[]).unwrap_err();
241        assert_eq!(e.code, crate::error::codes::USAGE);
242    }
243
244    #[test]
245    fn long_flag_space_and_equals() {
246        assert_eq!(parse_ok(&["x", "--output", "f"]).value("output"), Some("f"));
247        assert_eq!(parse_ok(&["x", "--output=f"]).value("output"), Some("f"));
248    }
249
250    #[test]
251    fn short_flag_space_and_attached() {
252        assert_eq!(parse_ok(&["x", "-o", "f"]).value("output"), Some("f"));
253        assert_eq!(parse_ok(&["x", "-of"]).value("output"), Some("f"));
254    }
255
256    #[test]
257    fn bool_switch() {
258        assert!(parse_ok(&["x", "-v"]).flag("verbose"));
259        assert!(parse_ok(&["x", "--verbose"]).flag("verbose"));
260        assert!(!parse_ok(&["x"]).flag("verbose"));
261    }
262
263    #[test]
264    fn double_dash_stops_flags() {
265        let m = parse_ok(&["x", "--", "-v"]);
266        // -v after -- is positional, so it fills `extra`
267        assert_eq!(m.arg_opt("extra"), Some("-v"));
268        assert!(!m.flag("verbose"));
269    }
270
271    #[test]
272    fn unknown_flag_errors() {
273        let owned = vec!["x".to_string(), "--nope".to_string()];
274        assert_eq!(parse(&cmd(), &owned).unwrap_err().code, crate::error::codes::USAGE);
275    }
276
277    #[test]
278    fn value_flag_missing_value_errors() {
279        let owned = vec!["x".to_string(), "--output".to_string()];
280        assert!(parse(&cmd(), &owned).is_err());
281    }
282
283    #[test]
284    fn variadic_collects_rest() {
285        let mut c = Command::new("t");
286        c.args.push(Arg::new("items").variadic());
287        let owned: Vec<String> = ["a", "b", "c"].iter().map(|s| s.to_string()).collect();
288        let m = parse(&c, &owned).unwrap();
289        assert_eq!(m.args("items"), vec!["a", "b", "c"]);
290    }
291
292    #[test]
293    fn too_many_positionals_errors() {
294        let owned: Vec<String> = ["a", "b", "c"].iter().map(|s| s.to_string()).collect();
295        assert!(parse(&cmd(), &owned).is_err());
296    }
297
298    #[test]
299    fn default_value_applied() {
300        let mut c = Command::new("t");
301        c.flags.push(Flag::value("mode").default("fast"));
302        let m = parse(&c, &[]).unwrap();
303        assert_eq!(m.value("mode"), Some("fast"));
304    }
305}