jubarte-redlines 0.9.0

Lossless DOCX redline engine — compare two Word documents into a tracked-changes document that opens cleanly in Microsoft Word; list, accept, or reject revisions
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
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
//
// SPDX-License-Identifier: AGPL-3.0-only

//! `jubarte` — generate a tracked-changes (redline) `.docx` from two documents.
//!
//! ```text
//! jubarte original.docx modified.docx
//!   → writes original_v_modified.docx
//! jubarte -b a.docx -m b.docx -o out.docx --author "Jane" --date 2024-01-02T00:00:00Z
//! ```
//!
//! Positional args are `<ORIGINAL> <MODIFIED>`; the `--original`/`--modified`
//! flags override them. Argument parsing, `--help`, `--version`, short/long
//! flags, and validation are handled by clap (gated behind the default `cli`
//! feature).

use std::path::{Path, PathBuf};
use std::process::ExitCode;

use clap::Parser;

/// CLI-only global allocator. The redline pipeline spends ~41% of CPU self-time
/// in allocation/copy/free/drop of xmllinq nodes (measured with samply on the
/// RFP17 fixtures — `produce::coalesce_recurse`/`reconstruct_element` churn).
/// mimalloc lowers that per-allocation cost; it changes performance only, never
/// program semantics. Library consumers are unaffected (this lives in the
/// binary). Toggle off with `--no-default-features --features cli` for A/B.
#[cfg(feature = "fast-alloc")]
#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;

/// Generate a tracked-changes (redline) .docx from two documents.
///
/// The redline is the ORIGINAL document with every difference against MODIFIED
/// expressed as Word tracked changes (insertions, deletions, moves, and format
/// changes), so it opens cleanly in Microsoft Word.
#[derive(Parser, Debug)]
#[command(
    name = "jubarte",
    version,
    about = "Generate a tracked-changes (redline) .docx from two documents",
    long_about = None,
    after_help = "EXAMPLES:\n  \
        jubarte contract.docx contract-rev2.docx\n      \
        → writes contract_v_contract-rev2.docx next to the original\n\n  \
        jubarte -b old.docx -m new.docx -o redline.docx --author \"Legal\"\n  \
        jubarte a.docx b.docx --force --quiet",
)]
struct Cli {
    /// Subcommand (e.g. `revisions`); plain compare when omitted.
    #[command(subcommand)]
    command: Option<Command>,

    /// The original / base document (.docx).
    #[arg(value_name = "ORIGINAL")]
    original_pos: Option<PathBuf>,

    /// The modified document (.docx).
    #[arg(value_name = "MODIFIED")]
    modified_pos: Option<PathBuf>,

    /// Original/base document (overrides the positional ORIGINAL).
    #[arg(short = 'b', long = "original", value_name = "FILE")]
    original: Option<PathBuf>,

    /// Modified document (overrides the positional MODIFIED).
    #[arg(short = 'm', long = "modified", value_name = "FILE")]
    modified: Option<PathBuf>,

    /// Output path [default: <original-dir>/<original>_v_<modified>.docx].
    #[arg(short = 'o', long, value_name = "FILE")]
    output: Option<PathBuf>,

    /// Author name recorded on the revisions.
    #[arg(short = 'a', long, value_name = "NAME", default_value = "Redline")]
    author: String,

    /// Revision timestamp (ISO 8601); pinned for reproducible output.
    #[arg(
        short = 'd',
        long,
        value_name = "ISO8601",
        default_value = "1970-01-01T00:00:00Z"
    )]
    date: String,

    /// Overwrite the output file if it already exists.
    #[arg(long)]
    force: bool,

    /// Do not print the success message.
    #[arg(short = 'q', long)]
    quiet: bool,

    /// LCS detail threshold [default: 0.02, or 0.15 under
    /// --powertools-faithful]. 0.02 = Word-style within-paragraph word diffs
    /// with weak-match voiding; 0.15 = the PowerTools-faithful coarse
    /// fallback; 0 = confetti with no voiding. An explicit value always wins
    /// over either preset (Option distinguishes unset from explicitly-set —
    /// no sentinel ambiguity).
    #[arg(long, value_name = "RATIO")]
    detail_threshold: Option<f64>,

    /// PowerTools-faithful mode: coarse paragraph fallback (threshold 0.15)
    /// and no Word-visual alignment passes. Default is Word-visual mode.
    #[arg(long)]
    powertools_faithful: bool,

    /// DEBUG: zero WmlComparerSettings::merge_replaced_paragraphs — the
    /// word-visual UMBRELLA gate — which disables the WHOLE word-visual pass
    /// family (merge, flatten, reorder, margins, …), not just the paragraph
    /// merge (pagination experiments; hidden). Redundant with
    /// --powertools-faithful, which sets the same preset.
    #[arg(long, hide = true)]
    no_paragraph_merge: bool,
}

/// D.6 — `redline revisions <file> [--json]`: list the tracked revisions in
/// a redline .docx (the `WmlComparer.GetRevisions` facade).
#[derive(clap::Subcommand, Debug)]
enum Command {
    /// List the tracked revisions in a redline .docx.
    Revisions {
        /// The redline document (.docx).
        #[arg(value_name = "FILE")]
        file: PathBuf,
        /// Emit the list as JSON lines instead of a human summary.
        #[arg(long)]
        json: bool,
    },
    /// Accept every tracked revision (package-wide) and write the result.
    Accept {
        /// The document (.docx) whose revisions to accept.
        #[arg(value_name = "FILE")]
        file: PathBuf,
        /// Output path.
        #[arg(short = 'o', long, value_name = "FILE")]
        output: PathBuf,
        /// Overwrite the output file if it already exists.
        #[arg(long)]
        force: bool,
    },
    /// Reject every tracked revision (package-wide) and write the result.
    Reject {
        /// The document (.docx) whose revisions to reject.
        #[arg(value_name = "FILE")]
        file: PathBuf,
        /// Output path.
        #[arg(short = 'o', long, value_name = "FILE")]
        output: PathBuf,
        /// Overwrite the output file if it already exists.
        #[arg(long)]
        force: bool,
    },
    /// Convert a .docx to PDF (independent of LibreOffice).
    Convert {
        /// The document (.docx) to convert.
        #[arg(value_name = "FILE")]
        file: PathBuf,
        /// Output path [default: <stem>.pdf next to the input].
        #[arg(short = 'o', long, value_name = "FILE")]
        output: Option<PathBuf>,
        /// Overwrite the output file if it already exists.
        #[arg(long)]
        force: bool,
        /// Deflate the PDF's streams (`/FlateDecode`). Much smaller output;
        /// the trade is that the page content is no longer plain text, so it
        /// cannot be read with `strings` or `grep`.
        #[arg(long)]
        compress: bool,
    },
}

/// No-clobber contract shared by every writing subcommand.
fn ensure_writable(output: &Path, force: bool) -> Result<(), String> {
    if output.exists() && !force {
        return Err(format!(
            "output '{}' already exists (use --force to overwrite)",
            output.display()
        ));
    }
    Ok(())
}

/// Shared body for `accept` / `reject`: read the redline, apply the package-wide
/// resolution, and write the result under the compare path's no-clobber
/// contract. Generic over the resolver's error so neither `OpcError`'s path nor
/// the two arms' bodies are duplicated.
fn run_resolution<E: std::fmt::Debug>(
    file: &Path,
    output: &Path,
    force: bool,
    apply: fn(&[u8]) -> Result<Vec<u8>, E>,
    what: &str,
) -> Result<(), String> {
    ensure_writable(output, force)?;
    let bytes = std::fs::read(file).map_err(|e| format!("reading {}: {e}", file.display()))?;
    let out = apply(&bytes).map_err(|e| format!("{what} failed: {e:?}"))?;
    std::fs::write(output, &out).map_err(|e| format!("writing {}: {e}", output.display()))
}

fn run_convert(
    file: &Path,
    output: Option<&Path>,
    force: bool,
    compress: bool,
) -> Result<(), String> {
    let output = output
        .map(Path::to_path_buf)
        .unwrap_or_else(|| file.with_extension("pdf"));
    ensure_writable(&output, force)?;
    let bytes = std::fs::read(file).map_err(|e| format!("reading {}: {e}", file.display()))?;
    let options = jubarte::convert::PdfOptions { compress };
    let pdf = jubarte::convert::docx_to_pdf_with(&bytes, options)
        .map_err(|e| format!("convert failed: {e}"))?;
    std::fs::write(&output, &pdf).map_err(|e| format!("writing {}: {e}", output.display()))?;
    let pages = jubarte::convert::pdf_page_count(&pdf);
    println!(
        "wrote {} ({} bytes, {pages} page{})",
        output.display(),
        pdf.len(),
        if pages == 1 { "" } else { "s" }
    );
    Ok(())
}

fn run_revisions(file: &Path, json: bool) -> Result<(), String> {
    let bytes = std::fs::read(file).map_err(|e| format!("reading {}: {e}", file.display()))?;
    let settings = jubarte::comparer::WmlComparerSettings::default();
    let revs = jubarte::document_comparer::get_revisions(&bytes, &settings)
        .map_err(|e| format!("get_revisions failed: {e:?}"))?;
    if json {
        // Shared serialization (also the wasm `getRevisions` shape): full JSON
        // string escaping — backslash, quote, and ALL control chars < 0x20.
        for r in &revs {
            println!("{}", jubarte::document_comparer::revision_to_json(r));
        }
    } else {
        for r in &revs {
            let text = r.text.as_deref().unwrap_or("");
            let preview: String = text.chars().take(60).collect();
            println!(
                "{:?}\t{}\t{}\t{:?}",
                r.revision_type,
                r.author.as_deref().unwrap_or("-"),
                r.part_name,
                preview
            );
        }
        println!("{} revision(s)", revs.len());
    }
    Ok(())
}

/// A fully-resolved comparison job (positional/named merged, output computed).
#[derive(Debug, PartialEq)]
struct Job {
    original: PathBuf,
    modified: PathBuf,
    output: PathBuf,
    author: String,
    date: String,
    force: bool,
    quiet: bool,
    detail_threshold: Option<f64>,
    powertools_faithful: bool,
    no_paragraph_merge: bool,
}

impl Cli {
    /// Merge positional and named inputs (named flags win), compute the default
    /// output path, and validate that both documents are supplied.
    fn resolve(self) -> Result<Job, String> {
        let original = self
            .original
            .or(self.original_pos)
            .ok_or("missing ORIGINAL document (a positional arg or --original/-b)")?;
        let modified = self
            .modified
            .or(self.modified_pos)
            .ok_or("missing MODIFIED document (a positional arg or --modified/-m)")?;
        let output = self
            .output
            .unwrap_or_else(|| default_output(&original, &modified));
        Ok(Job {
            original,
            modified,
            output,
            author: self.author,
            date: self.date,
            force: self.force,
            quiet: self.quiet,
            detail_threshold: self.detail_threshold,
            powertools_faithful: self.powertools_faithful,
            no_paragraph_merge: self.no_paragraph_merge,
        })
    }
}

/// Build the default output path: `<original-dir>/<orig-stem>_v_<mod-stem>.docx`.
fn default_output(original: &Path, modified: &Path) -> PathBuf {
    let stem = |p: &Path| {
        p.file_stem()
            .map(|s| s.to_string_lossy().into_owned())
            .unwrap_or_else(|| "doc".to_string())
    };
    let name = format!("{}_v_{}.docx", stem(original), stem(modified));
    match original.parent().filter(|p| !p.as_os_str().is_empty()) {
        Some(dir) => dir.join(name),
        None => PathBuf::from(name),
    }
}

fn run(job: &Job) -> Result<(), String> {
    ensure_writable(&job.output, job.force)?;
    let original = std::fs::read(&job.original)
        .map_err(|e| format!("reading {}: {e}", job.original.display()))?;
    let modified = std::fs::read(&job.modified)
        .map_err(|e| format!("reading {}: {e}", job.modified.display()))?;

    let base = if job.powertools_faithful {
        jubarte::comparer::WmlComparerSettings::powertools_faithful()
    } else {
        jubarte::comparer::WmlComparerSettings::default()
    };
    let settings = jubarte::comparer::WmlComparerSettings {
        author_for_revisions: job.author.clone(),
        date_time_for_revisions: job.date.clone(),
        detail_threshold: job.detail_threshold.unwrap_or(base.detail_threshold),
        merge_replaced_paragraphs: if job.no_paragraph_merge {
            false
        } else {
            base.merge_replaced_paragraphs
        },
        ..base
    };
    let out = jubarte::document_comparer::compare_documents_with_settings(
        &original, &modified, &settings,
    )
    .map_err(|e| format!("compare failed: {e:?}"))?;

    std::fs::write(&job.output, &out)
        .map_err(|e| format!("writing {}: {e}", job.output.display()))?;

    if !job.quiet {
        println!("wrote {} ({} bytes)", job.output.display(), out.len());
    }
    Ok(())
}

/// Shared `Result → ExitCode` mapping for every command arm.
fn exit_code(r: Result<(), String>) -> ExitCode {
    match r {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("error: {e}");
            ExitCode::FAILURE
        }
    }
}

fn main() -> ExitCode {
    let cli = Cli::parse();
    match cli.command {
        Some(Command::Revisions { file, json }) => {
            return exit_code(run_revisions(&file, json));
        }
        Some(Command::Accept {
            file,
            output,
            force,
        }) => {
            return exit_code(run_resolution(
                &file,
                &output,
                force,
                jubarte::document_comparer::accept_revisions,
                "accept",
            ));
        }
        Some(Command::Reject {
            file,
            output,
            force,
        }) => {
            return exit_code(run_resolution(
                &file,
                &output,
                force,
                jubarte::document_comparer::reject_revisions,
                "reject",
            ));
        }
        Some(Command::Convert {
            file,
            output,
            force,
            compress,
        }) => {
            return exit_code(run_convert(&file, output.as_deref(), force, compress));
        }
        None => {}
    }
    let job = match cli.resolve() {
        Ok(job) => job,
        Err(e) => {
            eprintln!("error: {e}");
            eprintln!("try 'jubarte --help'");
            return ExitCode::from(2);
        }
    };
    exit_code(run(&job))
}

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

    fn job_of(args: &[&str]) -> Job {
        Cli::try_parse_from(args)
            .expect("parse")
            .resolve()
            .expect("resolve")
    }

    /// clap's own invariants (catches derive-config mistakes like duplicate shorts).
    #[test]
    fn cli_definition_is_valid() {
        Cli::command().debug_assert();
    }

    #[test]
    fn positional_args_and_default_output() {
        let j = job_of(&["jubarte", "a.docx", "b.docx"]);
        assert_eq!(j.original, PathBuf::from("a.docx"));
        assert_eq!(j.modified, PathBuf::from("b.docx"));
        assert_eq!(j.output, PathBuf::from("a_v_b.docx"));
        assert_eq!(j.author, "Redline");
        assert_eq!(j.date, "1970-01-01T00:00:00Z");
        assert!(!j.force && !j.quiet);
    }

    #[test]
    fn default_output_uses_original_directory_and_stems() {
        let o = default_output(
            Path::new("docs/contract.docx"),
            Path::new("rev/contract-2.docx"),
        );
        assert_eq!(o, PathBuf::from("docs/contract_v_contract-2.docx"));
        // no directory → bare name
        let o2 = default_output(Path::new("contract.docx"), Path::new("contract-2.docx"));
        assert_eq!(o2, PathBuf::from("contract_v_contract-2.docx"));
    }

    #[test]
    fn named_flags_override_positionals() {
        let j = job_of(&[
            "jubarte",
            "a.docx",
            "b.docx",
            "-b",
            "real-orig.docx",
            "--modified",
            "real-mod.docx",
        ]);
        assert_eq!(j.original, PathBuf::from("real-orig.docx"));
        assert_eq!(j.modified, PathBuf::from("real-mod.docx"));
    }

    #[test]
    fn all_options_long_and_short() {
        let j = job_of(&[
            "jubarte",
            "-b",
            "o.docx",
            "-m",
            "n.docx",
            "-o",
            "out.docx",
            "-a",
            "Jane Doe",
            "-d",
            "2024-01-02T00:00:00Z",
            "--force",
            "--quiet",
        ]);
        assert_eq!(j.output, PathBuf::from("out.docx"));
        assert_eq!(j.author, "Jane Doe");
        assert_eq!(j.date, "2024-01-02T00:00:00Z");
        assert!(j.force && j.quiet);
    }

    #[test]
    fn flags_can_supply_both_inputs_without_positionals() {
        let j = job_of(&["jubarte", "--original", "x.docx", "--modified", "y.docx"]);
        assert_eq!(j.original, PathBuf::from("x.docx"));
        assert_eq!(j.modified, PathBuf::from("y.docx"));
        assert_eq!(j.output, PathBuf::from("x_v_y.docx"));
    }

    #[test]
    fn double_dash_treats_rest_as_positionals() {
        let j = job_of(&["jubarte", "--", "-weird-name.docx", "b.docx"]);
        assert_eq!(j.original, PathBuf::from("-weird-name.docx"));
        assert_eq!(j.modified, PathBuf::from("b.docx"));
    }

    #[test]
    fn help_and_version_are_handled_by_clap() {
        use clap::error::ErrorKind;
        let help = Cli::try_parse_from(["jubarte", "--help"]).unwrap_err();
        assert_eq!(help.kind(), ErrorKind::DisplayHelp);
        let ver = Cli::try_parse_from(["jubarte", "-V"]).unwrap_err();
        assert_eq!(ver.kind(), ErrorKind::DisplayVersion);
    }

    #[test]
    fn missing_inputs_error_at_resolve() {
        let only_one = Cli::try_parse_from(["jubarte", "one.docx"])
            .unwrap()
            .resolve();
        assert!(only_one.unwrap_err().contains("missing MODIFIED"));
        let none = Cli::try_parse_from(["jubarte"]).unwrap().resolve();
        assert!(none.unwrap_err().contains("missing ORIGINAL"));
    }

    #[test]
    fn extra_positional_and_unknown_flag_rejected_by_clap() {
        use clap::error::ErrorKind;
        let extra = Cli::try_parse_from(["jubarte", "a.docx", "b.docx", "c.docx"]).unwrap_err();
        assert_eq!(extra.kind(), ErrorKind::UnknownArgument);
        let bogus = Cli::try_parse_from(["jubarte", "--bogus"]).unwrap_err();
        assert_eq!(bogus.kind(), ErrorKind::UnknownArgument);
        let missing_val = Cli::try_parse_from(["jubarte", "--author"]).unwrap_err();
        assert_eq!(missing_val.kind(), ErrorKind::InvalidValue);
    }

    /// D.6 — `redline revisions <file>` parses into `Command::Revisions` with
    /// `json` defaulting to `false`; the legacy positional/named compare
    /// fields are left at their defaults (`command` is a plain addition, not
    /// a replacement of the existing surface).
    #[test]
    fn revisions_subcommand_parses_with_default_json_false() {
        let cli = Cli::try_parse_from(["jubarte", "revisions", "file.docx"]).unwrap();
        match cli.command {
            Some(Command::Revisions { file, json }) => {
                assert_eq!(file, PathBuf::from("file.docx"));
                assert!(!json);
            }
            other => panic!("expected revisions subcommand, got {other:?}"),
        }
    }

    /// D.6 — `--json` sets the JSON-lines output flag.
    #[test]
    fn revisions_subcommand_json_flag_parses() {
        let cli = Cli::try_parse_from(["jubarte", "revisions", "file.docx", "--json"]).unwrap();
        match cli.command {
            Some(Command::Revisions { json, .. }) => assert!(json),
            other => panic!("expected revisions subcommand, got {other:?}"),
        }
    }

    /// D.6 — `revisions` without a FILE argument is a clap usage error.
    #[test]
    fn revisions_subcommand_missing_file_is_clap_error() {
        use clap::error::ErrorKind;
        let err = Cli::try_parse_from(["jubarte", "revisions"]).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument);
    }

    /// Prior behavior path: a two-positional invocation whose filenames do
    /// NOT collide with the subcommand name is unaffected by adding
    /// `command` to `Cli` — `cli.command` stays `None` and `resolve()`
    /// merges the positionals exactly as before this PR.
    #[test]
    fn plain_compare_positionals_leave_command_none() {
        let cli = Cli::try_parse_from(["jubarte", "a.docx", "b.docx"]).unwrap();
        assert!(cli.command.is_none());
        let job = cli.resolve().unwrap();
        assert_eq!(job.original, PathBuf::from("a.docx"));
        assert_eq!(job.modified, PathBuf::from("b.docx"));
    }

    /// `accept <file> -o <out> --force` parses into `Command::Accept` with the
    /// output and force flag captured.
    #[test]
    fn accept_subcommand_parses_file_output_and_force() {
        let cli =
            Cli::try_parse_from(["jubarte", "accept", "rl.docx", "-o", "out.docx", "--force"])
                .unwrap();
        match cli.command {
            Some(Command::Accept {
                file,
                output,
                force,
            }) => {
                assert_eq!(file, PathBuf::from("rl.docx"));
                assert_eq!(output, PathBuf::from("out.docx"));
                assert!(force);
            }
            other => panic!("expected accept subcommand, got {other:?}"),
        }
    }

    /// `reject <file> -o <out>` parses into `Command::Reject`; `force` defaults
    /// to false (the same no-clobber contract as `accept` / compare).
    #[test]
    fn reject_subcommand_parses_file_output_and_defaults_force_false() {
        let cli = Cli::try_parse_from(["jubarte", "reject", "rl.docx", "-o", "out.docx"]).unwrap();
        match cli.command {
            Some(Command::Reject {
                file,
                output,
                force,
            }) => {
                assert_eq!(file, PathBuf::from("rl.docx"));
                assert_eq!(output, PathBuf::from("out.docx"));
                assert!(!force);
            }
            other => panic!("expected reject subcommand, got {other:?}"),
        }
    }

    /// `reject` requires `-o/--output` (clap usage error when omitted), matching
    /// `accept`.
    #[test]
    fn reject_subcommand_requires_output() {
        use clap::error::ErrorKind;
        let err = Cli::try_parse_from(["jubarte", "reject", "rl.docx"]).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument);
    }

    /// Documents the one real interaction between the legacy compare surface
    /// and the new subcommand: a document literally named `revisions` as the
    /// first positional is parsed as the `revisions` subcommand (clap
    /// subcommand matching takes priority over positional args), not as the
    /// legacy ORIGINAL. This is the tradeoff for adding `revisions` as a
    /// subcommand rather than a flag.
    #[test]
    fn positional_named_revisions_is_parsed_as_subcommand() {
        let cli = Cli::try_parse_from(["jubarte", "revisions", "b.docx"]).unwrap();
        match cli.command {
            Some(Command::Revisions { file, .. }) => assert_eq!(file, PathBuf::from("b.docx")),
            other => panic!("expected revisions subcommand, got {other:?}"),
        }
    }
}