shift 0.3.0

A command-line argument parser
Documentation
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
#![deny(missing_docs)]
//! Parsing command line arguments
//!
//! Call [`parse`] to get a [`Bag`] from which options, flags and operands may be extracted.
//!
//! ## Supported syntax
//!
//! GNU-style command line invocations like the following are supported:
//!
//! ```text
//! exe commit --verbose --level=info --message message
//! exe -v -l=info -m message
//! ```
//!
//! Anything prefixed with a `-` or `--` is treated as an option or flag.
//! The following command lines are equivalent:
//! ```text
//! exe -one -two -3
//! exe --one --two --3
//! ```
//!
//! After parsing this, you'll be able to extract three flags: `one`, `two` and `3`.
//!
//! The end of options marker `--` is respected.
//! Any arguments that come after it are treated as operands (i.e. positional arguments)
//!
//! While the order the command line arguments appear in is irrelevant, the order in which you extract them is.
//! In particular, when a switch is followed by a value, it is ambiguous whether it should be treated as an option or a flag.
//! The order in which methods are called resolves this ambiguity:
//!
//! ```
//! // Treated as a flag followed by a positional argument
//! let mut bag = shift::parse(vec![
//!     String::from("program"),
//!     String::from("--option"),
//!     String::from("value")
//! ]).unwrap();
//! assert_eq!(bag.shift_flag("option"), true);
//! assert_eq!(bag.shift_operand().as_deref(), Some("value"));
//! assert!(bag.is_empty());
//!
//! // Treated as an option
//! let mut bag = shift::parse(vec![
//!     String::from("program"),
//!     String::from("--option"),
//!     String::from("value")
//! ]).unwrap();
//! assert_eq!(bag.shift_option("option").as_deref(), Some("value"));
//! assert!(bag.is_empty());
//! ```

use std::fmt::Display;

/// Parsed command line arguments
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bag {
    program_name: String,
    entries: Vec<Entry>,
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
enum Entry {
    #[default]
    Empty,
    LongSwitch(String, Option<String>),
    ShortSwitch(String, Option<String>),
    Operand(String),
}
/// A command line parsing error
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParseError {
    /// The list of command line arguments was not at lest 1 element long
    MissingProgramName,
    /// Encountered an option withuot a name (e.g. `--=value`)
    InvalidSwitch(String),
}

/// Parses the given command line arguments into a [bag](crate::Bag)
pub fn parse(args: Vec<String>) -> Result<Bag, ParseError> {
    let mut saw_end_of_options = false;
    let mut entries: Vec<Entry> = Vec::new();

    let mut iter = args.into_iter();

    let Some(program_name) = iter.next() else {
        return Err(ParseError::MissingProgramName);
    };

    for arg in iter {
        if saw_end_of_options || arg == "-" {
            entries.push(Entry::Operand(arg));
            continue;
        }

        if arg == "--" {
            entries.push(Entry::Operand(arg));
            saw_end_of_options = true;
            continue;
        }

        if let Some(value) = arg.strip_prefix("--") {
            if let Some((name, value)) = value.split_once('=') {
                if name.is_empty() {
                    return Err(ParseError::InvalidSwitch(arg));
                }
                entries.push(Entry::LongSwitch(
                    String::from(name),
                    Some(String::from(value)),
                ));
            } else {
                entries.push(Entry::LongSwitch(String::from(value), None));
            }
            continue;
        }

        if let Some(value) = arg.strip_prefix("-") {
            if let Some((name, value)) = value.split_once('=') {
                if name.is_empty() {
                    return Err(ParseError::InvalidSwitch(arg));
                }

                entries.push(Entry::ShortSwitch(
                    String::from(name),
                    Some(String::from(value)),
                ));
            } else {
                entries.push(Entry::ShortSwitch(String::from(value), None));
            }
            continue;
        }

        entries.push(Entry::Operand(arg));
    }

    Ok(Bag {
        program_name,
        entries,
    })
}

impl Bag {
    /// Returns `true` when there are no more flags, options or positional arguments left.
    pub fn is_empty(&self) -> bool {
        self.entries.iter().all(|e| *e == Entry::Empty)
    }

    /// Removes the first flag with the given name from the bag if it exists.
    pub fn shift_flag(&mut self, name: &str) -> bool {
        for entry in self.entries.iter_mut() {
            if let Entry::LongSwitch(n, None) | Entry::ShortSwitch(n, None) = entry {
                if n != name {
                    continue;
                }

                *entry = Entry::Empty;
                return true;
            };
        }
        false
    }

    /// Removes the next positional argument that has the given value
    ///
    /// This is useful for extracting cli commands
    pub fn shift_operand_with_value(&mut self, expected_value: &str) -> bool {
        for entry in self.entries.iter_mut() {
            if let Entry::Operand(val) = entry {
                if val != expected_value {
                    continue;
                }

                *entry = Entry::Empty;
                return true;
            }
        }

        false
    }

    /// Removes the next positional argument from the argument bag, if any.
    ///
    /// Positional arguments are removed in the order they were supplied.
    /// Anything after the end-of-options marker counts as a positional argument.
    /// Note that the end-of-options marker itself will be returned by this method.
    pub fn shift_operand(&mut self) -> Option<String> {
        for entry in self.entries.iter_mut() {
            if let Entry::Operand(val) = entry {
                let value = std::mem::take(val);
                *entry = Entry::Empty;
                return Some(value);
            }
        }
        None
    }

    /// Removes the first option with the given `name` and returns its value.
    pub fn shift_option(&mut self, name: &str) -> Option<String> {
        for i in 0..self.entries.len() {
            match &mut self.entries[i] {
                // --n=val or -n=val
                Entry::LongSwitch(n, Some(val)) | Entry::ShortSwitch(n, Some(val)) => {
                    if n != name {
                        continue;
                    }

                    let value = std::mem::take(val);
                    self.entries[i] = Entry::Empty;

                    return Some(value);
                }
                // --n val or // -n val
                Entry::LongSwitch(n, None) | Entry::ShortSwitch(n, None) => {
                    if n != name {
                        continue;
                    }

                    let Some(Entry::Operand(val)) = self.entries.get_mut(i + 1) else {
                        continue;
                    };

                    let value = std::mem::take(val);

                    self.entries[i] = Entry::Empty;
                    self.entries[i + 1] = Entry::Empty;

                    return Some(value);
                }
                _ => continue,
            }
        }

        None
    }

    /// Returns the name of the executing program
    pub fn program_name(&self) -> &str {
        self.program_name.as_str()
    }

    /// Removes any leftover flags, options and operands that have not been `shift*`-ed.
    ///
    /// Subsequent calls will return an empty slice
    pub fn shift_remaining(&mut self) -> Vec<String> {
        let mut result = Vec::new();
        for entry in self.entries.iter_mut() {
            if *entry == Entry::Empty {
                continue;
            }

            result.push(entry.to_string());
            *entry = Entry::Empty;
        }
        result
    }
}

impl Display for Entry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Entry::Empty => Ok(()),
            Entry::LongSwitch(name, Some(value)) => write!(f, "--{name}={value}"),
            Entry::ShortSwitch(name, Some(value)) => write!(f, "-{name}={value}"),
            Entry::LongSwitch(name, None) => write!(f, "--{name}"),
            Entry::ShortSwitch(name, None) => write!(f, "-{name}"),
            Entry::Operand(value) => write!(f, "{value}"),
        }
    }
}

impl Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::MissingProgramName => write!(
                f,
                "empty list of command line arguments; must have at least one element that corresponds to the executable name"
            ),
            Self::InvalidSwitch(invalid) => write!(f, "option without a name: `{invalid}`"),
        }
    }
}

impl std::error::Error for ParseError {}

#[cfg(test)]
mod tests {
    use super::*;

    #[track_caller]
    fn args<const N: usize>(arr: [&str; N]) -> Vec<String> {
        arr.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn missing_exe_name() {
        let result = parse(args([]));
        assert_eq!(result, Err(ParseError::MissingProgramName));
    }

    #[test]
    fn malformed_option() {
        let result = parse(args(["program", "--=value"]));
        assert_eq!(
            result,
            Err(ParseError::InvalidSwitch(String::from("--=value")))
        );

        let result = parse(args(["program", "-=value"]));
        assert_eq!(
            result,
            Err(ParseError::InvalidSwitch(String::from("-=value")))
        );
    }

    #[test]
    fn shift_eql_separated_options() {
        let mut bag = parse(args(["program", "--opt1=val1", "-opt2=val2"])).unwrap();
        assert!(!bag.is_empty());
        assert_eq!(bag.shift_option("opt1").as_deref(), Some("val1"));
        assert_eq!(bag.shift_option("opt2").as_deref(), Some("val2"));
        assert_eq!(bag.shift_option("opt2"), None);
        assert!(bag.is_empty());
    }

    #[test]
    fn shift_space_separated_options() {
        let mut bag = parse(args(["program", "--opt1", "val1", "-opt2", "val2"])).unwrap();
        assert_eq!(bag.shift_option("opt1").as_deref(), Some("val1"));
        assert_eq!(bag.shift_option("opt2").as_deref(), Some("val2"));
        assert_eq!(bag.shift_option("opt2"), None);
        assert!(bag.is_empty());
    }

    #[test]
    fn shift_option_does_not_remove_flags() {
        let mut bag = parse(args(["program", "--switch", "--switch", "value"])).unwrap();
        assert_eq!(bag.shift_option("switch").as_deref(), Some("value"));
        assert!(bag.shift_flag("switch"));
        assert!(bag.is_empty());
    }

    #[test]
    fn shift_option_returns_multiple_values() {
        let mut bag = parse(args(["program", "--opt", "value", "--opt=value2"])).unwrap();
        assert_eq!(bag.shift_option("opt").as_deref(), Some("value"));
        assert_eq!(bag.shift_option("opt").as_deref(), Some("value2"));
        assert_eq!(bag.shift_option("opt"), None);
    }

    #[test]
    fn shifting_the_same_flag_multiple_times() {
        let mut bag = parse(args(["prgoram", "--flag", "--flag"])).unwrap();
        assert!(bag.shift_flag("flag"));
        assert!(bag.shift_flag("flag"));
        assert!(!bag.shift_flag("flag"));
        assert!(bag.is_empty());
    }

    #[test]
    fn shift_operand() {
        let mut bag = parse(args(["program", "-", "a", "b", "--", "c", "--", "-foo"])).unwrap();
        assert!(!bag.is_empty());
        assert_eq!(bag.shift_operand().as_deref(), Some("-"));
        assert_eq!(bag.shift_operand().as_deref(), Some("a"));
        assert_eq!(bag.shift_operand().as_deref(), Some("b"));
        assert_eq!(bag.shift_operand().as_deref(), Some("--"));
        assert_eq!(bag.shift_operand().as_deref(), Some("c"));
        assert_eq!(bag.shift_operand().as_deref(), Some("--"));
        assert_eq!(bag.shift_operand().as_deref(), Some("-foo"));
        assert_eq!(bag.shift_operand(), None);
        assert!(bag.is_empty());
    }

    #[test]
    fn resolving_operand_ambiguity() {
        let mut bag = parse(args(["program", "--flag", "operand"])).unwrap();
        assert_eq!(bag.shift_operand().as_deref(), Some("operand"));
        assert_eq!(bag.shift_option("flag"), None);
        assert!(bag.shift_flag("flag"));
        assert!(bag.is_empty());

        let mut bag = parse(args(["program", "--flag", "operand"])).unwrap();
        assert_eq!(bag.shift_option("flag").as_deref(), Some("operand"));
        assert_eq!(bag.shift_operand(), None);
        assert!(bag.is_empty());
    }

    #[test]
    fn shifting_remaining_arguments() {
        let mut bag = parse(args(["program", "-", "a", "b", "--", "c"])).unwrap();

        assert_eq!(bag.shift_operand().as_deref(), Some("-"));
        assert_eq!(
            bag.shift_remaining(),
            vec![
                String::from("a"),
                String::from("b"),
                String::from("--"),
                String::from("c")
            ]
        );
        assert!(bag.is_empty());
    }

    #[test]
    fn shift_operand_with_value() {
        let mut bag = parse(args(["program", "a", "b"])).unwrap();
        assert!(bag.shift_operand_with_value("b"));
        assert!(bag.shift_operand_with_value("a"));
        assert!(bag.is_empty());
    }
}

#[cfg(doctest)]
#[doc = include_str!("README.md")]
struct ReadmeDocTest;