mkit-cli 0.4.1

The mkit command-line tool: a content-addressed VCS with native attestation support
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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
//! `mkit diff` — show changes as a unified patch.
//!
//! Modes:
//!
//! - no args — HEAD tree vs a fresh worktree snapshot;
//! - `--staged` / `--cached` — HEAD tree vs the staged index tree
//!   (what `mkit commit` would record);
//! - one revision (`<rev>`) — that revision's tree vs the worktree (or
//!   vs the staged index with `--staged`);
//! - two revisions (`<a> <b>`) or a range (`<a>..<b>`) — diff the two
//!   resolved trees against each other.
//!
//! A leading positional that is not a resolvable revision is treated as
//! the start of the pathspec list; a leading positional that *looks*
//! like a revision (ref / commit / range) but fails to resolve is a
//! hard error rather than a silent empty diff (#207).
//!
//! Trailing positional paths (pathspecs) filter the output to entries
//! at or below those paths. The default output is a Git-compatible
//! unified diff: a git-shaped `diff --git a/<p> b/<p>` header per changed
//! path (with `new file mode`/`deleted file mode`/`index`/`--- a/p`/`+++ b/p`
//! lines, `/dev/null` for adds/deletes) followed by Myers-diff hunks (or a
//! `Binary files … differ` line). The `index` ids are abbreviated BLAKE3
//! prefixes — the one inherent divergence from `git diff`.
//!
//! `--name-only` / `--name-status` switch to summary output: one record
//! per changed path — just the path, or an `A`/`D`/`M` status letter
//! (`T` for an mkit mode change) plus the path. Special-byte paths are
//! C-style quoted (git `core.quotePath`); `-z` instead NUL-terminates
//! records and emits raw paths (and, for `--name-status`, NUL-terminates
//! the status letter and path as separate fields).
//!
//! `-w`/`--ignore-all-space` and `-b`/`--ignore-space-change` change
//! which lines the hunk generator treats as equal (`-w` wins if both are
//! given); `-U<n>`/`--unified=<n>` sets the number of unchanged context
//! lines around each hunk (default 3). Neither affects the bytes of a
//! line that does render — only which lines end up part of a hunk.

use std::io::Write;

use clap::Parser;
use mkit_core::hash::Hash;
use mkit_core::layout::RepoLayout;
use mkit_core::object::{EntryMode, Object};
use mkit_core::ops::merge::find_merge_base;
use mkit_core::ops::{
    DEFAULT_CONTEXT_LINES, DiffEntry, DiffKind, WhitespaceMode, detect_exact_renames, diff_trees,
    unified_hunks_opts,
};
use mkit_core::refs;
use mkit_core::store::{DisplaySource, EphemeralSink, ObjectSource, ObjectStore};
use mkit_core::worktree;

use super::revspec;
use crate::clap_shim;
use crate::exit;
use crate::format;

mod stat;
pub(super) use stat::render_stat;

#[derive(Debug, Parser)]
#[command(
    name = "mkit diff",
    about = "Show changes as a unified patch (HEAD vs worktree, --staged, or two trees)."
)]
#[allow(clippy::struct_excessive_bools)] // clap option flags, not a state machine
struct DiffOpts {
    /// Diff the staged index tree against HEAD (the change `mkit commit`
    /// would record) instead of HEAD vs worktree.
    #[arg(long, visible_alias = "cached")]
    staged: bool,

    /// Show only the names of changed files, one per line, instead of a
    /// patch (like `git diff --name-only`).
    #[arg(long, conflicts_with = "name_status")]
    name_only: bool,

    /// Show a status letter (`A`/`D`/`M`; `T` for an mkit mode change)
    /// and the name of each changed file (like `git diff --name-status`).
    #[arg(long)]
    name_status: bool,

    /// Show a diffstat: per-file changed-line counts and a `+`/`-` graph,
    /// plus a summary line (like `git diff --stat`). Honors `COLUMNS`
    /// (default 80) for the graph width.
    #[arg(long, conflicts_with_all = ["name_only", "name_status"])]
    stat: bool,

    /// Diff against the merge base of the revisions, like `git diff
    /// --merge-base`. With one revision: `merge-base(<rev>, HEAD)` vs the
    /// worktree. With two: `merge-base(<a>, <b>)` vs `<b>`. (Equivalent to
    /// the `<a>...<b>` symmetric range, but spelled as a flag.)
    #[arg(long = "merge-base", conflicts_with = "staged")]
    merge_base: bool,

    /// NUL-terminate `--name-only` / `--name-status` records and emit raw
    /// (unquoted) paths — like `git diff -z`. In `--name-status`, the
    /// status letter and path are each NUL-terminated. Only valid with
    /// `--name-only` / `--name-status`.
    #[arg(short = 'z')]
    z: bool,

    /// Exit with 1 when there are differences, 0 when there are none (the
    /// patch is still printed) — like `git diff --exit-code`. The CI
    /// idiom for "fail if the tree changed".
    #[arg(long = "exit-code")]
    exit_code: bool,

    /// Like `--exit-code` but print nothing (`git diff --quiet`).
    #[arg(long)]
    quiet: bool,

    /// Turn off rename detection (on by default, like git). A move then
    /// shows as a separate deletion and addition.
    #[arg(long = "no-renames")]
    no_renames: bool,

    /// Detect renames, optionally with a similarity threshold (`-M`,
    /// `--find-renames[=N]`). mkit pairs by identical content (exact,
    /// 100%), so any threshold ≤ 100 selects the same matches.
    #[arg(short = 'M', long = "find-renames", value_name = "N", num_args = 0..=1, default_missing_value = "100")]
    find_renames: Option<String>,

    /// Colorize the patch: `always`, `auto` (default, tty-only), or
    /// `never` (like `git diff --color[=<when>]`). Honors `NO_COLOR` /
    /// `CLICOLOR_FORCE` under `auto`.
    #[arg(long = "color", value_name = "WHEN", num_args = 0..=1, require_equals = true, default_missing_value = "always", conflicts_with = "no_color")]
    color: Option<String>,

    /// Disable colorized output (`git diff --no-color`).
    #[arg(long = "no-color")]
    no_color: bool,

    /// Ignore whitespace when comparing lines — like git's `-w` /
    /// `--ignore-all-space`. A line that differs from its counterpart only
    /// in whitespace is treated as unchanged context; the printed line
    /// still shows its own real (unmodified) bytes. Takes precedence over
    /// `-b` when both are given.
    #[arg(short = 'w', long = "ignore-all-space")]
    ignore_all_space: bool,

    /// Ignore changes in the *amount* of whitespace — like git's `-b` /
    /// `--ignore-space-change`. Runs of whitespace compare equal
    /// regardless of length, but a line with whitespace where the other
    /// side has none still differs (unlike `-w`).
    #[arg(short = 'b', long = "ignore-space-change")]
    ignore_space_change: bool,

    /// Number of unchanged context lines shown around each hunk (default
    /// 3) — like git's `-U<n>` / `--unified=<n>`.
    #[arg(short = 'U', long = "unified", value_name = "N")]
    unified: Option<usize>,

    /// Optional revisions (refs, full/short hashes, `HEAD~n`, or an
    /// `A..B` range) followed by optional pathspecs to limit the
    /// output. With no revisions, diffs HEAD vs worktree (or HEAD vs
    /// index with --staged). A leading argument that is not a resolvable
    /// revision starts the pathspec list.
    args: Vec<String>,
}

impl DiffOpts {
    /// Resolve `-w`/`-b` into the single [`WhitespaceMode`] the hunk
    /// renderer consumes. `-w` wins when both are given, matching git
    /// (the more aggressive mode takes precedence rather than erroring).
    fn whitespace_mode(&self) -> WhitespaceMode {
        if self.ignore_all_space {
            WhitespaceMode::IgnoreAllSpace
        } else if self.ignore_space_change {
            WhitespaceMode::IgnoreSpaceChange
        } else {
            WhitespaceMode::Exact
        }
    }
}

#[must_use]
pub fn run(args: &[String]) -> u8 {
    let opts = match clap_shim::parse::<DiffOpts>("mkit diff", args) {
        Ok(o) => o,
        Err(code) => return code,
    };
    // `-z` only governs the `--name-only` / `--name-status` record
    // framing (per the parity matrix); it has no defined meaning for the
    // unified-patch output yet, so reject it rather than silently ignore.
    if opts.z && !(opts.name_only || opts.name_status) {
        return emit_err(
            "`-z` is only valid with `--name-only` or `--name-status`",
            exit::USAGE,
        );
    }
    let Some(color_choice) = crate::term::ColorChoice::parse(opts.color.as_deref()) else {
        return emit_err("--color expects always, auto, or never", exit::USAGE);
    };
    let use_color = !opts.no_color
        && color_choice.resolve(std::io::IsTerminal::is_terminal(&std::io::stdout()));
    let ws_mode = opts.whitespace_mode();
    let context = opts.unified.unwrap_or(DEFAULT_CONTEXT_LINES);
    let cwd = match std::env::current_dir() {
        Ok(p) => p,
        Err(e) => return emit_err(&format!("cwd: {e}"), exit::NOINPUT),
    };
    let layout = match super::resolve_layout(&cwd) {
        Ok(layout) => layout,
        Err(code) => return code,
    };
    let store = match ObjectStore::open(&layout) {
        Ok(s) => s,
        Err(e) => return emit_err(&format!("not a mkit repo: {e}"), exit::GENERAL_ERROR),
    };

    // Worktree/index snapshot trees are ephemeral: they live in this
    // in-memory overlay, never in the durable store — no flush cost,
    // no garbage objects. Reads fall through to the store.
    let snapshot = EphemeralSink::new(&store);

    let (old_tree, new_tree, pathspecs) = match resolve_diff_endpoints(
        &store,
        &snapshot,
        &layout,
        opts.staged,
        opts.merge_base,
        &opts.args,
    ) {
        Ok(v) => v,
        Err((msg, code)) => return emit_err(&msg, code),
    };

    let mut result = match diff_trees(&snapshot, old_tree, new_tree) {
        Ok(r) => r,
        Err(e) => return emit_err(&format!("diff: {e}"), exit::GENERAL_ERROR),
    };

    // Rename detection (on by default, like git's `diff.renames`): collapse
    // identical-content delete/add pairs into `R` entries before filtering
    // and rendering. A provided threshold must parse, but the exact matcher
    // ignores its magnitude.
    if let Some(t) = &opts.find_renames {
        let n = t.trim_end_matches('%');
        if !n.is_empty() && n.parse::<u8>().is_err() {
            return emit_err(&format!("invalid --find-renames value: {t}"), exit::USAGE);
        }
    }
    if !opts.no_renames {
        detect_exact_renames(&mut result.entries);
    }

    let normalized: Vec<String> = pathspecs.iter().map(|p| normalize_pathspec(p)).collect();
    let selected: Vec<&mkit_core::ops::DiffEntry> = result
        .entries
        .iter()
        .filter(|e| normalized.is_empty() || path_matches_any(&e.path, &normalized))
        .collect();

    // `--exit-code`/`--quiet` report difference via the exit status (1 =
    // changed, 0 = clean). `--quiet` additionally suppresses output.
    let report_exit = opts.exit_code || opts.quiet;
    let diff_status = if report_exit && !selected.is_empty() {
        exit::GENERAL_ERROR
    } else {
        exit::OK
    };
    if opts.quiet {
        return diff_status;
    }

    let mut stdout = std::io::stdout().lock();
    if opts.stat {
        // `render_stat` hoists its own `DisplaySource` wrapping (#625).
        return match render_stat(&mut stdout, &snapshot, selected.into_iter()) {
            Ok(()) => diff_status,
            Err(msg) => emit_err(&msg, exit::GENERAL_ERROR),
        };
    }
    // The patch paths below print what they render here — nothing durable
    // is published from this path — so skip the BLAKE3 re-verify on every
    // changed blob (#625).
    let display = DisplaySource::new(&snapshot);
    for e in selected {
        let res = if opts.name_only || opts.name_status {
            emit_entry_name(&mut stdout, e, opts.name_status, opts.z);
            Ok(())
        } else if use_color {
            // Render the entry to a buffer, then colorize line-by-line so
            // the byte-exact patch machinery stays color-agnostic.
            let mut buf: Vec<u8> = Vec::new();
            match emit_entry_patch(&mut buf, &display, e, context, ws_mode) {
                // Colorize on RAW BYTES (not via from_utf8_lossy) so a
                // non-UTF-8 patch body round-trips byte-for-byte, matching
                // the uncolored path.
                Ok(()) => stdout
                    .write_all(&colorize_patch(&buf))
                    .map_err(|err| format!("write: {err}")),
                Err(msg) => Err(msg),
            }
        } else {
            emit_entry_patch(&mut stdout, &display, e, context, ws_mode)
        };
        if let Err(msg) = res {
            return emit_err(&msg, exit::GENERAL_ERROR);
        }
    }
    diff_status
}

/// ANSI-colorize a unified-diff patch line-by-line, matching git's default
/// palette: metadata bold, hunk headers cyan, additions green, deletions
/// red. Context lines are left uncolored. Operates on raw bytes so a
/// non-UTF-8 patch body round-trips unchanged (only ASCII line prefixes
/// drive the coloring).
fn colorize_patch(text: &[u8]) -> Vec<u8> {
    const RESET: &[u8] = b"\x1b[0m";
    let mut out: Vec<u8> = Vec::with_capacity(text.len() + 64);
    for line in text.split_inclusive(|&b| b == b'\n') {
        let (body, nl): (&[u8], &[u8]) = if line.last() == Some(&b'\n') {
            (&line[..line.len() - 1], b"\n")
        } else {
            (line, b"")
        };
        let code: Option<&[u8]> = if body.starts_with(b"@@") {
            Some(b"\x1b[36m") // hunk header: cyan
        } else if body.starts_with(b"diff ")
            || body.starts_with(b"index ")
            || body.starts_with(b"new file")
            || body.starts_with(b"deleted file")
            || body.starts_with(b"old mode")
            || body.starts_with(b"new mode")
            || body.starts_with(b"rename ")
            || body.starts_with(b"similarity ")
            || body.starts_with(b"--- ")
            || body.starts_with(b"+++ ")
        {
            Some(b"\x1b[1m") // metadata: bold
        } else if body.first() == Some(&b'+') {
            Some(b"\x1b[32m") // addition: green
        } else if body.first() == Some(&b'-') {
            Some(b"\x1b[31m") // deletion: red
        } else {
            None
        };
        match code {
            Some(c) => {
                out.extend_from_slice(c);
                out.extend_from_slice(body);
                out.extend_from_slice(RESET);
                out.extend_from_slice(nl);
            }
            None => out.extend_from_slice(line),
        }
    }
    out
}

/// Display name for stat/summary rows: C-style quoted like git's default
/// `core.quotePath` when the path has special bytes, else the raw path.
fn c_quote_name(path: &str) -> String {
    super::c_quote_path(path).unwrap_or_else(|| path.to_string())
}

/// Status letter for `--name-status`. mkit's `ModeChanged` maps to `T`
/// (git's type-change letter) — a documented mkit extension, since mkit
/// tracks a pure mode flip as its own diff kind.
fn name_status_letter(kind: DiffKind) -> char {
    match kind {
        DiffKind::Added => 'A',
        DiffKind::Removed => 'D',
        DiffKind::Modified => 'M',
        DiffKind::ModeChanged => 'T',
        // Renames carry a similarity score (`R100`) and two paths, so
        // `--name-status` formats them specially in `emit_entry_name`;
        // this bare letter is the fallback / name-only case.
        DiffKind::Renamed => 'R',
    }
}

/// Emit one `--name-only` / `--name-status` record for a changed entry.
///
/// Newline mode: `<path>\n` (name-only) or `<letter>\t<path>\n`
/// (name-status); a path with special bytes is C-style quoted like git's
/// default `core.quotePath`. `-z` mode: paths are raw (unquoted) and
/// records are NUL-terminated — `<path>\0`, or `<letter>\0<path>\0` where
/// the status letter and path are each their own NUL-terminated field
/// (matching `git diff --name-status -z`).
fn emit_entry_name(out: &mut impl Write, e: &DiffEntry, name_status: bool, z: bool) {
    // `--name-status` rename: git emits `R100<sep><src><sep><dst>` (source
    // first, unlike status's porcelain `-z`), TAB-separated by default and
    // NUL-separated under `-z`. Verified against git.
    if name_status && e.kind == DiffKind::Renamed {
        let src = e.old_path.as_deref().unwrap_or(&e.path);
        if z {
            let _ = write!(out, "R100\0{src}\0{}\0", e.path);
        } else {
            let sq = super::c_quote_path(src).unwrap_or_else(|| src.to_string());
            let dq = super::c_quote_path(&e.path).unwrap_or_else(|| e.path.clone());
            let _ = writeln!(out, "R100\t{sq}\t{dq}");
        }
        return;
    }
    if z {
        if name_status {
            let _ = write!(out, "{}\0", name_status_letter(e.kind));
        }
        let _ = write!(out, "{}\0", e.path);
        return;
    }
    let path = super::c_quote_path(&e.path);
    let shown = path.as_deref().unwrap_or(&e.path);
    if name_status {
        let _ = writeln!(out, "{}\t{shown}", name_status_letter(e.kind));
    } else {
        let _ = writeln!(out, "{shown}");
    }
}

/// `(old_tree, new_tree, pathspecs)` triple computed from the args.
type DiffEndpoints = (Option<Hash>, Option<Hash>, Vec<String>);

/// Decide the `old_tree` / `new_tree` / pathspecs triple from the
/// `staged` flag and the positional args. Returns `(message, exit_code)`
/// on error so the caller can route it through `emit_err`.
///
/// Cases:
/// - `--staged <rev>...` (any positionals) — usage contradiction
///   (#223): `--staged` already fixes both endpoints (HEAD vs index).
/// - `<a>..<b> [paths…]` — range form; both ends resolved to trees.
/// - `<a> <b> [paths…]` — two revisions, when both resolve.
/// - `<a> [paths…]` — one revision vs worktree (or vs index w/--staged
///   only in the no-positional case, handled above).
/// - no leading revision — default HEAD-vs-worktree / HEAD-vs-index,
///   all positionals are pathspecs.
/// `--merge-base` endpoint resolution. One revision: `merge-base(rev,
/// HEAD)` vs the worktree; two revisions: `merge-base(a, b)` vs `b`.
/// Trailing positionals are pathspecs. Annotated tags are peeled to their
/// commit before the merge-base walk, like git.
fn resolve_merge_base_endpoints(
    store: &ObjectStore,
    snapshot: &EphemeralSink<'_>,
    layout: &RepoLayout,
    args: &[String],
) -> Result<DiffEndpoints, (String, u8)> {
    let first = args.first().ok_or_else(|| {
        (
            "`--merge-base` requires at least one revision".to_string(),
            exit::USAGE,
        )
    })?;
    let a = peel_tags(
        store,
        revspec::resolve_revision(store, layout, first)
            .map_err(|e| (format!("bad revision '{first}': {e}"), exit::DATAERR))?,
    );

    // A second positional that resolves to a revision selects the
    // two-revision form. One that only *looks* like a revision but fails to
    // resolve is a hard error (#207); anything else is a pathspec, leaving
    // the single-revision (vs worktree) form.
    if let Some(second) = args.get(1) {
        match revspec::resolve_revision(store, layout, second) {
            Ok(h) => {
                let b = peel_tags(store, h);
                let base = merge_base_of(store, a, b)?;
                let old = object_to_tree(store, &base).map_err(|e| (e, exit::GENERAL_ERROR))?;
                let new = object_to_tree(store, &b).map_err(|e| (e, exit::GENERAL_ERROR))?;
                return Ok((Some(old), Some(new), args[2..].to_vec()));
            }
            // A 2nd positional that fails to resolve is treated as a pathspec
            // ONLY when it is clearly path-shaped (names an existing worktree
            // path, a tracked path, or contains `/`). Otherwise it is an
            // ambiguous bad revision — a typo'd `<b>` — which we surface,
            // rather than silently falling back to the single-rev form and
            // emitting an empty diff (matching git's "ambiguous argument").
            Err(e)
                if matches!(e, revspec::RevError::Unknown(_))
                    && looks_like_pathspec(layout, second) => {}
            Err(e) => return Err((format!("bad revision '{second}': {e}"), exit::DATAERR)),
        }
    }

    // Single revision: merge-base(rev, HEAD) vs the worktree.
    let head = refs::resolve_head(layout)
        .map_err(|e| (format!("resolve HEAD: {e}"), exit::GENERAL_ERROR))?
        .ok_or_else(|| {
            (
                "HEAD has no commit to take a merge base with".to_string(),
                exit::GENERAL_ERROR,
            )
        })?;
    let head = peel_tags(store, head);
    let base = merge_base_of(store, a, head)?;
    let old = object_to_tree(store, &base).map_err(|e| (e, exit::GENERAL_ERROR))?;
    let new = worktree_tree_filtered(store, snapshot, layout)?;
    Ok((Some(old), Some(new), args[1..].to_vec()))
}

/// Resolve the single merge base of `a` and `b`, mapping "no base" to a
/// clear error (matches git's `--merge-base` failure on unrelated histories).
fn merge_base_of(store: &ObjectStore, a: Hash, b: Hash) -> Result<Hash, (String, u8)> {
    find_merge_base(store, a, b)
        .map_err(|e| (format!("merge base: {e}"), exit::GENERAL_ERROR))?
        .ok_or_else(|| {
            (
                "no merge base between the given revisions".to_string(),
                exit::DATAERR,
            )
        })
}

#[allow(clippy::too_many_arguments)]
fn resolve_diff_endpoints(
    store: &ObjectStore,
    snapshot: &EphemeralSink<'_>,
    layout: &RepoLayout,
    staged: bool,
    merge_base: bool,
    args: &[String],
) -> Result<DiffEndpoints, (String, u8)> {
    // `--merge-base <a> [<b>] [paths…]` — diff the merge base of the given
    // revision(s) rather than the revisions themselves. Resolved before
    // any other form (clap already rejects `--merge-base --staged`).
    if merge_base {
        return resolve_merge_base_endpoints(store, snapshot, layout, args);
    }

    // #223: `--staged` with explicit revisions is contradictory —
    // `--staged` already pins HEAD vs the index. Pathspecs are fine, but
    // a leading argument that *looks* like a revision is not, and must
    // fail closed: if it resolves it is the contradiction (#223), and if
    // it does not it is a bad revision (#207). Either way we error rather
    // than silently treating a typo'd hash as a no-match pathspec (which
    // would empty-succeed and diverge from `git diff --cached <bad-rev>`).
    // A non-rev-looking leading arg (e.g. `path/`, `file.txt`) still falls
    // through as a pathspec filter.
    if staged {
        if let Some(first) = args.first()
            && looks_like_rev_request(first)
        {
            if revspec::resolve_revision(store, layout, strip_range_end(first).0).is_ok() {
                return Err((
                    "`--staged` diffs HEAD vs the index; it cannot take an explicit revision"
                        .to_string(),
                    exit::USAGE,
                ));
            }
            return Err((
                format!("bad revision '{first}': not a known ref, commit, or short hash"),
                exit::DATAERR,
            ));
        }
        // No leading revision: HEAD vs index, all positionals = pathspecs.
        let head = head_tree(store, layout).map_err(|e| (e, exit::GENERAL_ERROR))?;
        let idx = index_tree(layout, store, snapshot).map_err(|e| (e, exit::GENERAL_ERROR))?;
        return Ok((head, idx, args.to_vec()));
    }

    // Symmetric range `A...B` = diff the merge base of A and B against B
    // (git semantics). Must be checked before `A..B` (which it contains).
    if let Some(first) = args.first()
        && let Some((a, b)) = split_symmetric(first)
    {
        // Peel annotated/signed tags to their commit before merge-base
        // resolution, like git (and like `log` does for its range bases).
        let commit_a = peel_tags(
            store,
            revspec::resolve_revision(store, layout, a)
                .map_err(|e| (format!("bad revision '{a}': {e}"), exit::DATAERR))?,
        );
        let commit_b = peel_tags(
            store,
            revspec::resolve_revision(store, layout, b)
                .map_err(|e| (format!("bad revision '{b}': {e}"), exit::DATAERR))?,
        );
        let mb = find_merge_base(store, commit_a, commit_b)
            .map_err(|e| (format!("merge base: {e}"), exit::GENERAL_ERROR))?
            .ok_or_else(|| {
                (
                    format!("no merge base between '{a}' and '{b}'"),
                    exit::DATAERR,
                )
            })?;
        let old = object_to_tree(store, &mb).map_err(|e| (e, exit::GENERAL_ERROR))?;
        let new = object_to_tree(store, &commit_b).map_err(|e| (e, exit::GENERAL_ERROR))?;
        return Ok((Some(old), Some(new), args[1..].to_vec()));
    }

    // Range form `A..B` as the first positional.
    if let Some(first) = args.first()
        && let Some((a, b)) = split_range(first)
    {
        let old = rev_to_tree(store, layout, a)?;
        let new = rev_to_tree(store, layout, b)?;
        return Ok((Some(old), Some(new), args[1..].to_vec()));
    }

    // Try to peel one or two leading revisions.
    let first_rev = args.first().and_then(|a| try_rev_to_tree(store, layout, a));
    match first_rev {
        None => {
            // No leading revision → default HEAD vs worktree; all
            // positionals are pathspecs. If the first arg *looked* like
            // a revision but failed to resolve, error loudly (#207)
            // rather than silently treating it as a pathspec.
            if let Some(first) = args.first()
                && looks_like_rev_request(first)
            {
                return Err((
                    format!("bad revision '{first}': not a known ref, commit, or short hash"),
                    exit::DATAERR,
                ));
            }
            let head = head_tree(store, layout).map_err(|e| (e, exit::GENERAL_ERROR))?;
            let new = Some(worktree_tree_filtered(store, snapshot, layout)?);
            Ok((head, new, args.to_vec()))
        }
        Some(Err(e)) => Err(e),
        Some(Ok(old)) => {
            // One revision resolved. Is the second positional also a
            // revision? If so, two-rev mode; otherwise rev-vs-worktree.
            let second_rev = args.get(1).and_then(|a| try_rev_to_tree(store, layout, a));
            match second_rev {
                Some(Ok(new)) => Ok((Some(old), Some(new), args[2..].to_vec())),
                Some(Err(e)) => Err(e),
                None => {
                    let new = Some(worktree_tree_filtered(store, snapshot, layout)?);
                    Ok((Some(old), new, args[1..].to_vec()))
                }
            }
        }
    }
}

/// Resolve a revision spec to a tree hash, mapping a commit/remix to its
/// tree and accepting a bare tree hash as itself. `(message, code)` on
/// failure.
/// Snapshot the worktree, seeding the tracked set from the index (or HEAD
/// when no index file exists) so a tracked file matching an ignore rule is
/// not dropped from the snapshot and misreported as a deletion.
fn worktree_tree_filtered(
    store: &ObjectStore,
    snapshot: &EphemeralSink<'_>,
    layout: &RepoLayout,
) -> Result<Hash, (String, u8)> {
    let idx =
        super::read_or_seed_index_from_head(layout, store).map_err(|e| (e, exit::GENERAL_ERROR))?;
    worktree::build_tree_filtered(snapshot, layout.worktree_root(), Some(&idx))
        .map_err(|e| (format!("build tree: {e}"), exit::GENERAL_ERROR))
}

fn rev_to_tree(store: &ObjectStore, layout: &RepoLayout, spec: &str) -> Result<Hash, (String, u8)> {
    let h = revspec::resolve_revision(store, layout, spec)
        .map_err(|e| (format!("bad revision '{spec}': {e}"), exit::DATAERR))?;
    object_to_tree(store, &h).map_err(|e| (e, exit::GENERAL_ERROR))
}

/// Like [`rev_to_tree`] but distinguishes "not a revision at all" (None)
/// from "looks like a revision but is broken" (`Some(Err(..))`).
fn try_rev_to_tree(
    store: &ObjectStore,
    layout: &RepoLayout,
    spec: &str,
) -> Option<Result<Hash, (String, u8)>> {
    match revspec::resolve_revision(store, layout, spec) {
        Ok(h) => Some(object_to_tree(store, &h).map_err(|e| (e, exit::GENERAL_ERROR))),
        Err(revspec::RevError::Unknown(_)) => {
            // Not a known ref/object. If it still *looks* like a
            // revision request (ref-shaped or hash-shaped), surface the
            // failure; otherwise it is a pathspec.
            if looks_like_rev_request(spec) {
                Some(Err((
                    format!("bad revision '{spec}': not a known ref, commit, or short hash"),
                    exit::DATAERR,
                )))
            } else {
                None
            }
        }
        Err(e) => Some(Err((format!("bad revision '{spec}': {e}"), exit::DATAERR))),
    }
}

/// Follow `Object::Tag` targets to the first non-tag object, so an
/// annotated/signed tag resolves to the commit it points at. Delegates to
/// the shared `log::peel_tags` (kept as a local alias for the call sites).
fn peel_tags(store: &ObjectStore, h: Hash) -> Hash {
    super::log::peel_tags(store, h)
}

/// Map a resolved object hash to a tree hash: commit/remix → its tree,
/// a tree → itself.
pub(super) fn object_to_tree(store: &ObjectStore, h: &Hash) -> Result<Hash, String> {
    match store.read_object(h) {
        Ok(Object::Commit(c)) => Ok(c.tree_hash),
        Ok(Object::Remix(r)) => Ok(r.tree_hash),
        Ok(Object::Tree(_)) => Ok(*h),
        Ok(_) => Err(format!(
            "{} is not a commit, remix, or tree",
            mkit_core::hash::to_hex(h)
        )),
        Err(e) => Err(read_err(e)),
    }
}

/// Split an `A..B` range. Returns `None` if there is no `..`.
fn split_range(s: &str) -> Option<(&str, &str)> {
    let (a, b) = s.split_once("..")?;
    if a.is_empty() || b.is_empty() {
        return None;
    }
    Some((a, b))
}

/// Split a symmetric `A...B` range. An empty side defaults to `HEAD`
/// (`A...` = `A...HEAD`, `...B` = `HEAD...B`).
fn split_symmetric(s: &str) -> Option<(&str, &str)> {
    let (a, b) = s.split_once("...")?;
    Some((
        if a.is_empty() { "HEAD" } else { a },
        if b.is_empty() { "HEAD" } else { b },
    ))
}

/// The left-hand end of a possible range, used for the `--staged`
/// contradiction probe. Returns `(rev, is_range)`.
fn strip_range_end(s: &str) -> (&str, bool) {
    match s.split_once("..") {
        Some((a, _)) if !a.is_empty() => (a, true),
        _ => (s, false),
    }
}

/// Heuristic for #207: does this argument look like the user *intended*
/// a revision (so a resolve failure should be a hard error) rather than
/// a pathspec? True for hash-shaped tokens, `A..B` ranges, and the
/// literal `HEAD` (possibly with `~`/`^` navigation). A plain
/// filesystem-y token (`src/`, `./x`, `*.rs`) is treated as a pathspec.
fn looks_like_rev_request(s: &str) -> bool {
    if s.contains("..") {
        return true;
    }
    // A `~` or `^` navigation suffix is revision syntax, not a path.
    let base = s.split(['~', '^']).next().unwrap_or(s);
    if base == "HEAD" {
        return true;
    }
    // Hash-shaped: ≥ MIN_SHORT_HASH hex chars with no path separators.
    base.len() >= revspec::MIN_SHORT_HASH
        && !base.contains('/')
        && !base.contains('.')
        && base.bytes().all(|b| b.is_ascii_hexdigit())
}

/// Is `arg` clearly a pathspec rather than a (typo'd) revision? True when it
/// names an existing worktree path OR matches a tracked index path (a file/dir
/// tracked but deleted from the worktree is still a valid pathspec, as in
/// git). A bare `/` is NOT enough — branch names routinely contain `/` (e.g.
/// `feature/x`), so a typo'd branch like `feature/typo` must surface as a bad
/// revision rather than silently degrade into an empty-output pathspec filter.
fn looks_like_pathspec(layout: &RepoLayout, arg: &str) -> bool {
    if layout.worktree_root().join(arg).symlink_metadata().is_ok() {
        return true;
    }
    // Normalize the spec the same way the path filter will (e.g. `./a.txt` ->
    // `a.txt`) before matching the index, so a tracked-but-deleted file passed
    // as `./a.txt` isn't misread as a bad revision.
    let spec = normalize_pathspec(arg);
    let Ok(idx) = mkit_core::index::read_index(layout) else {
        return false;
    };
    let prefix = format!("{spec}/");
    idx.entries
        .iter()
        .any(|e| e.path == spec || e.path.starts_with(&prefix))
}

fn head_tree(store: &ObjectStore, layout: &RepoLayout) -> Result<Option<Hash>, String> {
    let head = refs::resolve_head(layout).map_err(|e| format!("resolve HEAD: {e}"))?;
    match head {
        None => Ok(None),
        Some(h) => match store.read_object(&h) {
            Ok(Object::Commit(c)) => Ok(Some(c.tree_hash)),
            Ok(Object::Remix(r)) => Ok(Some(r.tree_hash)),
            Ok(_) => Ok(None),
            Err(e) => Err(format!("read HEAD: {e}")),
        },
    }
}

fn index_tree(
    layout: &RepoLayout,
    store: &ObjectStore,
    snapshot: &EphemeralSink<'_>,
) -> Result<Option<Hash>, String> {
    let idx = super::read_or_seed_index_from_head(layout, store)?;
    // Ephemeral diff snapshot — nothing durable is published, so skip the
    // re-hash; the read path verifies any object actually touched.
    let tree = worktree::build_tree_from_index_with(store, snapshot, &idx, false)
        .map_err(|e| format!("build index tree: {e}"))?;
    Ok(Some(tree))
}

/// Normalize a pathspec to the index/diff path form: strip a leading
/// `./`, collapse `\\` to `/`, drop a trailing `/`. The repo root in any
/// spelling (`.`, `./`, `/`, or empty) normalizes to the empty string, which
/// [`path_matches_any`] treats as "match everything" (matching git, where
/// `diff -- .` is the whole-tree diff).
fn normalize_pathspec(spec: &str) -> String {
    let s = spec.replace('\\', "/");
    let s = s.strip_prefix("./").unwrap_or(&s);
    let s = s.strip_suffix('/').unwrap_or(s);
    if s == "." {
        String::new()
    } else {
        s.to_string()
    }
}

fn path_matches_any(path: &str, specs: &[String]) -> bool {
    specs
        .iter()
        // An empty spec is the repo root (`.`/`./`) → matches every path.
        .any(|spec| spec.is_empty() || super::index_path_matches_or_descends(path, spec))
}

/// Abbreviated all-zero blob id git prints for an absent side of `index`.
const ZERO_ABBREV: &str = "0000000";

/// git octal mode string for a [`DiffEntry`] side (`None` → regular file).
fn git_octal(mode: Option<EntryMode>) -> &'static str {
    match mode {
        Some(EntryMode::Executable) => "100755",
        Some(EntryMode::Symlink) => "120000",
        Some(EntryMode::Tree) => "040000",
        _ => "100644",
    }
}

/// Abbreviated blob id for an `index` line side (`None` → all-zero).
fn abbrev(h: Option<Hash>) -> String {
    h.map_or_else(|| ZERO_ABBREV.to_string(), |h| format::short_hash(&h, 7))
}

/// Emit a git-shaped `diff --git` header plus unified-diff hunks for one
/// changed entry. The `index <old>..<new>` ids are abbreviated BLAKE3
/// prefixes (longer than git's SHA-1 prefixes for the same `core.abbrev`),
/// the one inherent divergence; everything else matches `git diff`.
///
/// Shared with `mkit show`, so a commit's diff body is byte-identical to
/// `mkit diff <parent> <commit>` when both use the default `context`/`ws`
/// (git's `-U3`, exact comparison).
///
/// `context` is the `-U<n>` unchanged-context-line count and `ws` is the
/// `-w`/`-b` whitespace-comparison mode; pass
/// [`mkit_core::ops::DEFAULT_CONTEXT_LINES`] / [`WhitespaceMode::Exact`]
/// for git's defaults.
pub(super) fn emit_entry_patch<S: ObjectSource + ?Sized>(
    out: &mut impl Write,
    store: &S,
    e: &DiffEntry,
    context: usize,
    ws: WhitespaceMode,
) -> Result<(), String> {
    // git C-style quotes special-byte paths in the header (core.quotePath),
    // quoting the whole `a/<path>` / `b/<path>` token as a unit. For a
    // rename the `a/` side is the source path, the `b/` side the dest.
    let a_src = if e.kind == DiffKind::Renamed {
        e.old_path.as_deref().unwrap_or(&e.path)
    } else {
        e.path.as_str()
    };
    let a_path = quoted_side('a', a_src);
    let b_path = quoted_side('b', &e.path);
    let _ = writeln!(out, "diff --git {a_path} {b_path}");

    match e.kind {
        DiffKind::Renamed => {
            // Exact rename: identical content, so 100% similar and no hunk.
            let from = super::c_quote_path(a_src).unwrap_or_else(|| a_src.to_string());
            let to = super::c_quote_path(&e.path).unwrap_or_else(|| e.path.clone());
            let _ = writeln!(out, "similarity index 100%");
            let _ = writeln!(out, "rename from {from}");
            let _ = writeln!(out, "rename to {to}");
            return Ok(());
        }
        DiffKind::ModeChanged => {
            // Identical content, mode flip — only the mode lines, no hunks.
            let _ = writeln!(out, "old mode {}", git_octal(e.old_mode));
            let _ = writeln!(out, "new mode {}", git_octal(e.new_mode));
            return Ok(());
        }
        DiffKind::Added => {
            let _ = writeln!(out, "new file mode {}", git_octal(e.new_mode));
            let _ = writeln!(out, "index {}..{}", ZERO_ABBREV, abbrev(e.new_hash));
        }
        DiffKind::Removed => {
            let _ = writeln!(out, "deleted file mode {}", git_octal(e.old_mode));
            let _ = writeln!(out, "index {}..{}", abbrev(e.old_hash), ZERO_ABBREV);
        }
        DiffKind::Modified if e.old_mode != e.new_mode => {
            // Content and mode both changed: mode lines, index without mode.
            let _ = writeln!(out, "old mode {}", git_octal(e.old_mode));
            let _ = writeln!(out, "new mode {}", git_octal(e.new_mode));
            let _ = writeln!(out, "index {}..{}", abbrev(e.old_hash), abbrev(e.new_hash));
        }
        DiffKind::Modified => {
            let _ = writeln!(
                out,
                "index {}..{} {}",
                abbrev(e.old_hash),
                abbrev(e.new_hash),
                git_octal(e.new_mode)
            );
        }
    }

    let old_bytes = match e.old_hash {
        Some(h) => read_blob(store, &h)?,
        None => Vec::new(),
    };
    let new_bytes = match e.new_hash {
        Some(h) => read_blob(store, &h)?,
        None => Vec::new(),
    };
    // `--- a/p` / `+++ b/p` (quoted), with `/dev/null` for the absent side.
    let (minus, plus) = match e.kind {
        DiffKind::Added => ("/dev/null".to_string(), b_path.clone()),
        DiffKind::Removed => (a_path.clone(), "/dev/null".to_string()),
        _ => (a_path.clone(), b_path.clone()),
    };
    match unified_hunks_opts(&old_bytes, &new_bytes, context, ws) {
        None => {
            let _ = writeln!(out, "Binary files {minus} and {plus} differ");
        }
        Some(hunks) if hunks.is_empty() => {}
        Some(hunks) => {
            let _ = writeln!(out, "--- {minus}");
            let _ = writeln!(out, "+++ {plus}");
            let _ = out.write_all(&hunks);
        }
    }
    Ok(())
}

/// The git-quoted `a/<path>` / `b/<path>` token for a patch header: C-style
/// quoted (with surrounding quotes) when the path has special bytes, else the
/// plain `<side>/<path>`.
fn quoted_side(side: char, path: &str) -> String {
    let s = format!("{side}/{path}");
    super::c_quote_path(&s).unwrap_or(s)
}

/// Read a blob's bytes from the store, reassembling chunked blobs via
/// the shared core helper so diff/cat/checkout agree (#203).
fn read_blob<S: ObjectSource + ?Sized>(store: &S, h: &Hash) -> Result<Vec<u8>, String> {
    worktree::read_blob(store, h).map_err(read_err)
}

/// The one place the CLI's "read object: …" error wording is defined.
fn read_err<E: std::fmt::Display>(e: E) -> String {
    format!("read object: {e}")
}

use super::error as emit_err;

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

    fn de(path: &str, kind: DiffKind) -> DiffEntry {
        DiffEntry {
            path: path.to_string(),
            kind,
            old_hash: None,
            new_hash: None,
            old_mode: None,
            new_mode: None,
            old_path: None,
        }
    }

    fn render(e: &DiffEntry, name_status: bool, z: bool) -> String {
        let mut buf = Vec::new();
        emit_entry_name(&mut buf, e, name_status, z);
        String::from_utf8(buf).unwrap()
    }

    #[test]
    fn name_status_letters_cover_every_kind() {
        assert_eq!(name_status_letter(DiffKind::Added), 'A');
        assert_eq!(name_status_letter(DiffKind::Removed), 'D');
        assert_eq!(name_status_letter(DiffKind::Modified), 'M');
        assert_eq!(name_status_letter(DiffKind::ModeChanged), 'T');
    }
    #[test]
    fn name_only_newline_plain_path() {
        assert_eq!(
            render(&de("a.txt", DiffKind::Modified), false, false),
            "a.txt\n"
        );
    }

    #[test]
    fn name_status_newline_is_letter_tab_path() {
        assert_eq!(
            render(&de("a.txt", DiffKind::Added), true, false),
            "A\ta.txt\n"
        );
    }

    #[test]
    fn name_only_quotes_special_path_in_newline_mode() {
        // A tab is C-style quoted like git core.quotePath.
        assert_eq!(
            render(&de("a\tb.txt", DiffKind::Modified), false, false),
            "\"a\\tb.txt\"\n"
        );
    }

    #[test]
    fn z_mode_is_raw_and_nul_terminated() {
        // name-only -z: `<path>\0`, path emitted raw (unquoted).
        assert_eq!(
            render(&de("a\tb.txt", DiffKind::Modified), false, true),
            "a\tb.txt\0"
        );
        // name-status -z: `<letter>\0<path>\0` — two NUL-terminated fields.
        assert_eq!(
            render(&de("del.txt", DiffKind::Removed), true, true),
            "D\0del.txt\0"
        );
    }
}