zarust 0.2.0

Rust implementation of the ZArchive format
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
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
//! A dependency-free argument parser for the `zarust` binary.
//!
//! Supports `--flag`, `--flag=value`, `--flag value`, clustered short flags
//! (`-fv`), attached short values (`-oout.zar`), and `--` to end option parsing.
//! Options may appear before or after the subcommand.

use std::{ffi::OsString, path::PathBuf};

use crate::cli::ui::{ColorChoice, display_path};

/// How much the command should print on success.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Verbosity {
    /// Errors only.
    Quiet,
    /// Progress and a summary.
    Normal,
    /// Progress, a summary, and one line per entry.
    Verbose,
}

/// A parsed command line.
#[derive(Debug)]
pub struct Invocation {
    pub command: Command,
    pub options: Options,
}

#[derive(Debug)]
pub enum Command {
    Pack {
        input: PathBuf,
        output: Option<PathBuf>,
    },
    Extract {
        archive: PathBuf,
        output: Option<PathBuf>,
    },
    List {
        archive: PathBuf,
        path: Option<OsString>,
    },
    Info {
        archive: PathBuf,
    },
    Verify {
        archive: PathBuf,
    },
    Help,
    Version,
}

#[derive(Debug)]
pub struct Options {
    /// `-o/--output`, an alternative to the trailing positional path.
    pub output: Option<PathBuf>,
    pub force: bool,
    pub verbosity: Verbosity,
    pub progress: bool,
    pub color: ColorChoice,
    pub tree: bool,
    pub check: bool,
}

impl Default for Options {
    fn default() -> Self {
        Self {
            output: None,
            force: false,
            verbosity: Verbosity::Normal,
            progress: true,
            color: ColorChoice::Auto,
            tree: false,
            check: false,
        }
    }
}

/// A malformed command line. Reported to stderr and exits with code 2.
#[derive(Debug)]
pub struct UsageError(pub String);

impl UsageError {
    fn new(message: impl Into<String>) -> Self {
        Self(message.into())
    }
}

type Parsed<T> = Result<T, UsageError>;

pub fn parse(raw: impl IntoIterator<Item = OsString>) -> Parsed<Invocation> {
    let raw = raw.into_iter().collect::<Vec<_>>();
    if raw.is_empty() {
        return Ok(Invocation {
            command: Command::Help,
            options: Options::default(),
        });
    }

    // Options are stripped first so they may appear anywhere, including before
    // the subcommand: `zarust --color never pack src` and `zarust pack src
    // --color never` are the same invocation.
    let (mut positionals, mut options, wants_help, wants_version) = split(&raw)?;

    if wants_help {
        return Ok(Invocation {
            command: Command::Help,
            options,
        });
    }
    if wants_version {
        return Ok(Invocation {
            command: Command::Version,
            options,
        });
    }

    // A leading subcommand selects the mode explicitly; anything else falls back
    // to inferring it from the path, matching the original ZArchive tool.
    let name = match positionals.first().and_then(|first| first.to_str()) {
        Some(text) if is_command_name(text) => {
            let name = text.to_owned();
            positionals.pop_front();
            name
        }
        _ => infer_command(positionals.first())?,
    };

    let mut take_output = |positionals: &mut Positionals| -> Parsed<Option<PathBuf>> {
        match (positionals.pop_front_path(), options.output.take()) {
            (Some(_), Some(_)) => Err(UsageError::new(
                "the output path was given both positionally and with --output",
            )),
            (positional, flag) => Ok(positional.or(flag)),
        }
    };

    let command = match name.as_str() {
        "help" => Command::Help,
        "version" => Command::Version,
        "pack" => {
            let input = take_path(&mut positionals, "pack", "a source directory")?;
            let output = take_output(&mut positionals)?;
            Command::Pack { input, output }
        }
        "extract" => {
            let archive = take_path(&mut positionals, "extract", "an archive")?;
            let output = take_output(&mut positionals)?;
            Command::Extract { archive, output }
        }
        "list" => {
            let archive = take_path(&mut positionals, "list", "an archive")?;
            let path = positionals.pop_front();
            Command::List { archive, path }
        }
        "info" => Command::Info {
            archive: take_path(&mut positionals, "info", "an archive")?,
        },
        "verify" => Command::Verify {
            archive: take_path(&mut positionals, "verify", "an archive")?,
        },
        other => return Err(UsageError::new(format!("unknown command `{other}`"))),
    };

    if let Some(extra) = positionals.pop_front() {
        return Err(UsageError::new(format!(
            "unexpected argument `{}`",
            extra.to_string_lossy()
        )));
    }

    // `--quiet` and `--no-progress` are equivalent as far as the bar goes;
    // collapse them here so commands only consult one field.
    if options.verbosity == Verbosity::Quiet {
        options.progress = false;
    }

    Ok(Invocation { command, options })
}

fn is_command_name(text: &str) -> bool {
    matches!(
        text,
        "pack" | "extract" | "list" | "info" | "verify" | "help" | "version"
    )
}

fn infer_command(first: Option<&OsString>) -> Parsed<String> {
    let Some(path) = first else {
        return Err(UsageError::new("no command or path given"));
    };
    let path = PathBuf::from(path);
    if path.is_dir() {
        Ok("pack".to_owned())
    } else if path.is_file() {
        Ok("extract".to_owned())
    } else {
        Err(UsageError::new(format!(
            "`{}` is not an existing file or directory",
            display_path(&path)
        )))
    }
}

fn take_path(positionals: &mut Positionals, command: &str, what: &str) -> Parsed<PathBuf> {
    positionals
        .pop_front_path()
        .ok_or_else(|| UsageError::new(format!("`{command}` needs {what}")))
}

/// Positional arguments in the order they appeared.
#[derive(Debug, Default)]
struct Positionals(std::collections::VecDeque<OsString>);

impl Positionals {
    fn push(&mut self, value: OsString) {
        self.0.push_back(value);
    }

    fn first(&self) -> Option<&OsString> {
        self.0.front()
    }

    fn pop_front(&mut self) -> Option<OsString> {
        self.0.pop_front()
    }

    fn pop_front_path(&mut self) -> Option<PathBuf> {
        self.0.pop_front().map(PathBuf::from)
    }
}

/// Splits `args` into positionals and options, reporting whether `--help` or
/// `--version` appeared anywhere.
fn split(args: &[OsString]) -> Parsed<(Positionals, Options, bool, bool)> {
    let mut positionals = Positionals::default();
    let mut options = Options::default();
    let mut help = false;
    let mut version = false;
    let mut literal = false;
    let mut index = 0;

    while index < args.len() {
        let arg = &args[index];
        index += 1;

        if literal {
            positionals.push(arg.clone());
            continue;
        }

        // Only options are required to be UTF-8; paths keep their original bytes.
        let Some(text) = arg.to_str() else {
            positionals.push(arg.clone());
            continue;
        };

        if text == "--" {
            literal = true;
        } else if let Some(long) = text.strip_prefix("--") {
            let (name, attached) = match long.split_once('=') {
                Some((name, value)) => (name, Some(value.to_owned())),
                None => (long, None),
            };
            match name {
                "help" => help = true,
                "version" => version = true,
                "force" => options.force = true,
                "verbose" => options.verbosity = Verbosity::Verbose,
                "quiet" => options.verbosity = Verbosity::Quiet,
                "tree" => options.tree = true,
                "check" => options.check = true,
                "no-progress" => options.progress = false,
                "color" => {
                    options.color = parse_color(&value(attached, args, &mut index, "--color")?)?;
                }
                "output" => {
                    let value = match attached {
                        Some(value) => OsString::from(value),
                        None => next(args, &mut index, "--output")?,
                    };
                    options.output = Some(PathBuf::from(value));
                }
                other => return Err(UsageError::new(format!("unknown option `--{other}`"))),
            }
        } else if text.len() > 1 && text.starts_with('-') {
            let chars = text[1..].char_indices();
            for (position, flag) in chars {
                // A short option that takes a value consumes the rest of the
                // cluster (`-l9`) or the next argument (`-l 9`).
                let attached = || {
                    let rest = &text[1 + position + flag.len_utf8()..];
                    (!rest.is_empty()).then(|| rest.to_owned())
                };
                match flag {
                    'h' => help = true,
                    'V' => version = true,
                    'f' => options.force = true,
                    'v' => options.verbosity = Verbosity::Verbose,
                    'q' => options.verbosity = Verbosity::Quiet,
                    'o' => {
                        let value = match attached() {
                            Some(value) => OsString::from(value),
                            None => next(args, &mut index, "-o")?,
                        };
                        options.output = Some(PathBuf::from(value));
                        break;
                    }
                    other => return Err(UsageError::new(format!("unknown option `-{other}`"))),
                }
            }
        } else {
            positionals.push(arg.clone());
        }
    }

    Ok((positionals, options, help, version))
}

fn value(
    attached: Option<String>,
    args: &[OsString],
    index: &mut usize,
    name: &str,
) -> Parsed<String> {
    match attached {
        Some(value) => Ok(value),
        None => next(args, index, name)?
            .into_string()
            .map_err(|_| UsageError::new(format!("`{name}` needs a valid UTF-8 value"))),
    }
}

fn next(args: &[OsString], index: &mut usize, name: &str) -> Parsed<OsString> {
    let value = args
        .get(*index)
        .ok_or_else(|| UsageError::new(format!("`{name}` needs a value")))?;
    *index += 1;
    Ok(value.clone())
}

fn parse_color(text: &str) -> Parsed<ColorChoice> {
    match text {
        "auto" => Ok(ColorChoice::Auto),
        "always" => Ok(ColorChoice::Always),
        "never" => Ok(ColorChoice::Never),
        other => Err(UsageError::new(format!(
            "`{other}` is not a color mode (use auto, always, or never)"
        ))),
    }
}

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

    fn parse_args(args: &[&str]) -> Parsed<Invocation> {
        parse(args.iter().map(OsString::from))
    }

    #[test]
    fn reads_subcommands_and_positionals() {
        let parsed = parse_args(&["pack", "src", "out.zar"]).unwrap();
        let Command::Pack { input, output } = parsed.command else {
            panic!("expected pack");
        };
        assert_eq!(input, PathBuf::from("src"));
        assert_eq!(output, Some(PathBuf::from("out.zar")));
    }

    #[test]
    fn accepts_every_option_spelling() {
        let parsed = parse_args(&["pack", "src", "--color=never", "-fv"]).unwrap();
        assert_eq!(parsed.options.color, ColorChoice::Never);
        assert!(parsed.options.force);
        assert_eq!(parsed.options.verbosity, Verbosity::Verbose);

        let parsed = parse_args(&["pack", "src", "-o", "out.zar"]).unwrap();
        let Command::Pack { output, .. } = parsed.command else {
            panic!("expected pack");
        };
        assert_eq!(output, Some(PathBuf::from("out.zar")));
    }

    #[test]
    fn accepts_options_on_either_side_of_the_subcommand() {
        for args in [
            &["--color", "never", "pack", "src", "out.zar"][..],
            &["pack", "--color", "never", "src", "out.zar"][..],
            &["pack", "src", "out.zar", "--color", "never"][..],
        ] {
            let parsed = parse_args(args).unwrap();
            assert_eq!(parsed.options.color, ColorChoice::Never, "{args:?}");
            let Command::Pack { input, output } = parsed.command else {
                panic!("expected pack for {args:?}");
            };
            assert_eq!(input, PathBuf::from("src"));
            assert_eq!(output, Some(PathBuf::from("out.zar")));
        }
    }

    #[test]
    fn rejects_an_output_given_twice() {
        assert!(parse_args(&["pack", "src", "out.zar", "-o", "other.zar"]).is_err());
    }

    #[test]
    fn quiet_disables_the_progress_bar() {
        let parsed = parse_args(&["pack", "src", "--quiet"]).unwrap();
        assert!(!parsed.options.progress);
    }

    #[test]
    fn treats_double_dash_as_a_literal_terminator() {
        let parsed = parse_args(&["list", "--", "--weird-name.zar"]).unwrap();
        let Command::List { archive, .. } = parsed.command else {
            panic!("expected list");
        };
        assert_eq!(archive, PathBuf::from("--weird-name.zar"));
    }

    #[test]
    fn rejects_bad_options_and_missing_arguments() {
        assert!(parse_args(&["pack"]).is_err());
        assert!(parse_args(&["pack", "src", "--nope"]).is_err());
        assert!(parse_args(&["pack", "src", "--color", "mauve"]).is_err());
        assert!(parse_args(&["pack", "src", "--color"]).is_err());
        assert!(parse_args(&["verify", "a.zar", "b.zar"]).is_err());
    }

    #[test]
    fn help_and_version_win_over_other_arguments() {
        assert!(matches!(
            parse_args(&["pack", "src", "--help"]).unwrap().command,
            Command::Help
        ));
        assert!(matches!(
            parse_args(&["--version"]).unwrap().command,
            Command::Version
        ));
        assert!(matches!(parse_args(&[]).unwrap().command, Command::Help));
    }
}