git-custom-cli 2.4.0

Fast, keyboard-driven terminal UI for dated Git commits
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
//! Stage mode: the working tree as a file list with stage / unstage / discard per file, a diff
//! viewer, and hunk-level stage / unstage / discard. Hunks are applied with `git apply` on a
//! patch built from git's own bytes (never an emulated `add -p`).

use crate::{
    diff::{self, FileDiff},
    git::{self, Opts},
    input,
    model::Config,
    modes,
    policy::{self, Op},
    repo_state::{self, Entry, EntryKind},
    screen, ui,
};
use anyhow::Result;

/// Longest diff shown; the rest is cut with a "(truncated)" footer.
const MAX_DIFF_LINES: usize = 5000;
/// Paths are literal file names, never globs or pathspec magic.
const LITERAL: &[(&str, &str)] = &[("GIT_LITERAL_PATHSPECS", "1")];
#[cfg(windows)]
const NULL_FILE: &str = "NUL";
#[cfg(not(windows))]
const NULL_FILE: &str = "/dev/null";

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Section {
    Staged,
    Unstaged,
    Untracked,
    Conflicted,
}

impl Section {
    fn tag(self) -> &'static str {
        match self {
            Section::Staged => "[S] staged   ",
            Section::Unstaged => "[M] unstaged ",
            Section::Untracked => "[?] untracked",
            Section::Conflicted => "[!] conflict ",
        }
    }
}

/// One selectable list row: an entry seen in one section (a file with both staged and
/// unstaged changes has two rows).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct Row {
    entry: usize,
    section: Section,
}

/// Rows in display order: Staged, Unstaged, Untracked, Conflicted (ignored files are skipped).
fn build_rows(entries: &[Entry]) -> Vec<Row> {
    let mut rows = Vec::new();
    for section in [
        Section::Staged,
        Section::Unstaged,
        Section::Untracked,
        Section::Conflicted,
    ] {
        for (entry, e) in entries.iter().enumerate() {
            let hit = match section {
                Section::Staged => e.staged(),
                Section::Unstaged => e.unstaged(),
                Section::Untracked => e.kind == EntryKind::Untracked,
                Section::Conflicted => e.conflicted(),
            };
            if hit {
                rows.push(Row { entry, section });
            }
        }
    }
    rows
}

fn row_text(e: &Entry, section: Section) -> String {
    let letter = match section {
        Section::Staged => e.x,
        Section::Unstaged => e.y,
        Section::Untracked => '?',
        Section::Conflicted => '!',
    };
    let name = match (&e.orig_path, section) {
        (Some(old), Section::Staged) => format!("{old} -> {}", e.path),
        _ => e.path.clone(),
    };
    format!("{} {letter}  {name}", section.tag())
}

fn header_lines(rows: &[Row]) -> Vec<String> {
    let count = |s: Section| rows.iter().filter(|r| r.section == s).count();
    let mut lines = vec![format!(
        "Staged {}  |  Unstaged {}  |  Untracked {}  |  Conflicted {}",
        count(Section::Staged),
        count(Section::Unstaged),
        count(Section::Untracked),
        count(Section::Conflicted)
    )];
    if rows.is_empty() {
        lines.push(screen::muted(
            "Nothing to stage: the working tree is clean. Edit a file, then press R.",
        ));
    }
    lines
}

/// The paths a staged entry covers: both sides of a rename.
fn entry_paths(e: &Entry) -> Vec<String> {
    let mut paths: Vec<String> = e.orig_path.iter().cloned().collect();
    paths.push(e.path.clone());
    paths
}

/// Arguments of the `git diff` that shows `e` in `section` (None for conflicts).
fn diff_args(section: Section, e: &Entry) -> Option<Vec<String>> {
    // Fixed `a/` `b/` prefixes: user settings (noprefix, mnemonicPrefix) would make `git apply`
    // reject the generated hunk patches.
    let base = [
        "diff",
        "--no-color",
        "--no-ext-diff",
        "--no-textconv",
        "--src-prefix=a/",
        "--dst-prefix=b/",
    ]
    .map(String::from);
    let mut args: Vec<String> = base.to_vec();
    match section {
        Section::Staged => {
            args.extend(["--cached", "-M", "--"].map(String::from));
            args.extend(entry_paths(e));
        }
        Section::Unstaged => {
            args.extend(["--", &e.path].map(String::from));
        }
        Section::Untracked => {
            args.extend(["--no-index", "--", NULL_FILE, &e.path].map(String::from));
        }
        Section::Conflicted => return None,
    }
    Some(args)
}

// ---------------------------------------------------------------------------------------------
// Executors (git side effects; testable with TempRepo)
// ---------------------------------------------------------------------------------------------

/// `git -C <dir> <args>`: `repo_state` paths are relative to the repo root, so path-taking
/// commands run there whatever folder the process happens to be in.
fn at<'a>(dir: &'a str, args: &[&'a str]) -> Vec<&'a str> {
    let mut full = vec!["-C", dir];
    full.extend_from_slice(args);
    full
}

fn head_exists(dir: &str) -> bool {
    git::git_raw(
        &at(dir, &["rev-parse", "--verify", "-q", "HEAD"]),
        &Opts::default(),
    )
    .map(|o| o.ok())
    .unwrap_or(false)
}

/// Runs `git <args> --pathspec-from-file=- --pathspec-file-nul` with the paths on stdin, which
/// avoids the Windows 32K command-line limit.
fn run_paths(dir: &str, args: &[&str], paths: &[String]) -> Result<()> {
    if paths.is_empty() {
        return Ok(());
    }
    let mut stdin = Vec::new();
    for path in paths {
        stdin.extend_from_slice(path.as_bytes());
        stdin.push(0);
    }
    let mut full = at(dir, args);
    full.extend(["--pathspec-from-file=-", "--pathspec-file-nul"]);
    git::git_ok(
        &full,
        &Opts {
            stdin: Some(&stdin),
            env: LITERAL,
            ..Opts::default()
        },
    )?;
    Ok(())
}

fn stage_paths(dir: &str, paths: &[String]) -> Result<()> {
    run_paths(dir, &["add"], paths)
}

fn unstage_paths(dir: &str, paths: &[String]) -> Result<()> {
    if head_exists(dir) {
        run_paths(dir, &["restore", "--staged"], paths)
    } else {
        run_paths(
            dir,
            &["rm", "--cached", "-r", "-q", "--ignore-unmatch"],
            paths,
        )
    }
}

fn discard_tracked_exec(dir: &str, path: &str) -> Result<()> {
    let args = at(dir, &["restore", "--worktree", "--", path]);
    git::git_ok(
        &args,
        &Opts {
            env: LITERAL,
            ..Opts::default()
        },
    )?;
    Ok(())
}

fn clean_args(path: &str) -> Vec<&str> {
    let mut args = vec!["clean", "-f"];
    if path.ends_with('/') {
        args.push("-d");
    }
    args.extend(["--", path]);
    args
}

fn discard_untracked_exec(dir: &str, path: &str) -> Result<()> {
    git::git_ok(
        &at(dir, &clean_args(path)),
        &Opts {
            env: LITERAL,
            ..Opts::default()
        },
    )?;
    Ok(())
}

/// Asks policy + the user, then discards. Returns whether anything was discarded.
fn discard_row(cfg: &Config, dir: &str, section: Section, e: &Entry) -> Result<bool> {
    let (op, what, command) = match section {
        Section::Unstaged => (
            Op::DiscardUnstaged,
            format!(
                "Throw away your unstaged changes to {}? This cannot be undone.",
                e.path
            ),
            format!("git restore --worktree -- {}", e.path),
        ),
        Section::Untracked => (
            Op::DiscardUntracked,
            format!(
                "Delete the untracked {} from disk? This cannot be undone.",
                e.path
            ),
            format!("git {}", clean_args(&e.path).join(" ")),
        ),
        _ => return Ok(false),
    };
    if !ui::gate(cfg, &policy::check(cfg, &op), &what, &command)? {
        return Ok(false);
    }
    if section == Section::Unstaged {
        discard_tracked_exec(dir, &e.path)?;
    } else {
        discard_untracked_exec(dir, &e.path)?;
    }
    let mut lines = vec![format!("Ran: {command}")];
    lines.extend(ui::explain(
        cfg,
        &["Discarding puts the file back to how it was at the last commit or staging."],
    ));
    ui::notice("Discarded", &lines)?;
    Ok(true)
}

/// Applies `patch` (bytes, via stdin) with `git apply <flags> -`.
fn apply_patch(dir: &str, flags: &[&str], patch: &[u8]) -> Result<()> {
    let mut args = vec!["apply"];
    args.extend_from_slice(flags);
    args.extend(["--whitespace=nowarn", "-"]);
    git::git_ok(
        &at(dir, &args),
        &Opts {
            stdin: Some(patch),
            ..Opts::default()
        },
    )?;
    Ok(())
}

fn stage_hunk(dir: &str, fd: &FileDiff, idx: usize) -> Result<()> {
    apply_patch(dir, &["--cached"], &diff::hunk_patch(fd, idx))
}

/// `fd` must come from the `--cached` diff.
fn unstage_hunk(dir: &str, fd: &FileDiff, idx: usize) -> Result<()> {
    apply_patch(dir, &["-R", "--cached"], &diff::hunk_patch(fd, idx))
}

/// `fd` must come from the unstaged diff.
fn discard_hunk_exec(dir: &str, fd: &FileDiff, idx: usize) -> Result<()> {
    apply_patch(dir, &["-R"], &diff::hunk_patch(fd, idx))
}

/// Loads and parses the diff of `e` in `section`.
fn load_files(dir: &str, section: Section, e: &Entry) -> Result<Vec<FileDiff>> {
    let Some(args) = diff_args(section, e) else {
        return Ok(Vec::new());
    };
    if section == Section::Untracked && e.path.ends_with('/') {
        let out = git::git_ok(
            &at(
                dir,
                &["ls-files", "--others", "--exclude-standard", "--", &e.path],
            ),
            &Opts {
                env: LITERAL,
                ..Opts::default()
            },
        )?;
        let mut header = format!("Untracked directory {}\nFiles:\n", e.path);
        out.lines()
            .for_each(|l| header.push_str(&format!("  {l}\n")));
        return Ok(vec![FileDiff {
            header: header.into_bytes(),
            hunks: Vec::new(),
        }]);
    }
    let mut refs: Vec<&str> = vec!["-C", dir];
    refs.extend([
        "-c",
        "diff.relative=false",
        "-c",
        "diff.noprefix=false",
        "-c",
        "diff.mnemonicPrefix=false",
    ]);
    refs.extend(args.iter().map(String::as_str));
    let out = git::git_raw(
        &refs,
        &Opts {
            env: LITERAL,
            ..Opts::default()
        },
    )?;
    // `--no-index` exits 1 when the files differ, which is the normal case.
    let good = out.ok() || (section == Section::Untracked && out.code == Some(1));
    if !good {
        anyhow::bail!("{}", out.stderr.trim());
    }
    Ok(diff::parse_diff(&out.stdout))
}

// ---------------------------------------------------------------------------------------------
// UI glue
// ---------------------------------------------------------------------------------------------

const LIST_KEYS: [ui::Key; 10] = [
    ui::Key {
        key: 'a',
        label: "stage",
    },
    ui::Key {
        key: 'u',
        label: "unstage",
    },
    ui::Key {
        key: 'x',
        label: "discard",
    },
    ui::Key {
        key: 'A',
        label: "stage ALL (Shift)",
    },
    ui::Key {
        key: 'U',
        label: "unstage ALL (Shift)",
    },
    ui::Key {
        key: 'i',
        label: "ignore",
    },
    ui::Key {
        key: 'c',
        label: "commit staged",
    },
    ui::Key {
        key: 'r',
        label: "refresh",
    },
    ui::Key {
        key: 'm',
        label: "menu",
    },
    ui::Key {
        key: 'd',
        label: "diff",
    },
];

/// A failed git call is shown, not fatal; Ctrl+C still propagates.
fn report(result: Result<()>) -> Result<()> {
    match result {
        Err(error) if !input::is_cancel(&error) => ui::notice("Git said no", &[error.to_string()]),
        other => other,
    }
}

fn say(title: &str, line: &str) -> Result<()> {
    ui::notice(title, &[line.to_string()])
}

fn conflict_menu(cfg: &mut Config, e: &Entry) -> Result<()> {
    let context = [
        format!("{} has merge conflicts.", e.path),
        "Conflicted files are read-only here: resolve in Conflicts mode.".into(),
    ];
    if ui::choose(
        "Conflicted file",
        &context,
        &["Open Conflicts mode", "Back"],
    )? == Some(0)
    {
        modes::open("conflicts", cfg)?;
    }
    Ok(())
}

fn stage_all(dir: &str, entries: &[Entry]) -> Result<()> {
    let paths: Vec<String> = entries
        .iter()
        .filter(|e| e.unstaged() || e.kind == EntryKind::Untracked)
        .map(|e| e.path.clone())
        .collect();
    stage_paths(dir, &paths)
}

fn unstage_all(dir: &str, entries: &[Entry]) -> Result<()> {
    let paths: Vec<String> = entries
        .iter()
        .filter(|e| e.staged())
        .flat_map(entry_paths)
        .collect();
    unstage_paths(dir, &paths)
}

/// Opens Commit mode for what is staged right now. The commit flow must not run `git add .`
/// (that would undo partial hunk staging), so it is told to commit the index as it is.
fn commit_staged(cfg: &mut Config) -> Result<()> {
    let state = repo_state::load()?;
    if !state.entries.iter().any(|e| e.staged()) {
        return say(
            "Nothing staged",
            "Stage a file or hunk first (a), then commit it here.",
        );
    }
    modes::STAGED_ONLY.store(true, std::sync::atomic::Ordering::Relaxed);
    let result = modes::open("commit", cfg);
    modes::STAGED_ONLY.store(false, std::sync::atomic::Ordering::Relaxed);
    result
}

/// One action on one row. Returns after the action; the caller reloads the list.
fn row_action(cfg: &mut Config, dir: &str, key: char, e: &Entry, section: Section) -> Result<()> {
    if section == Section::Conflicted {
        return match key {
            'i' | 'c' | 'a' | 'u' | 'x' => conflict_menu(cfg, e),
            _ => Ok(()),
        };
    }
    match (key, section) {
        ('a', Section::Staged) => say("Already staged", "Use U-shift or u to unstage it."),
        ('a', _) => report(stage_paths(dir, std::slice::from_ref(&e.path))),
        ('u', Section::Staged) => report(unstage_paths(dir, &entry_paths(e))),
        ('u', _) => say(
            "Not staged",
            "This row is not in the index; nothing to unstage.",
        ),
        ('x', Section::Staged) => say(
            "Unstage first",
            "Press u to unstage it, then discard the working copy.",
        ),
        ('x', _) => report(discard_row(cfg, dir, section, e).map(|_| ())),
        ('i', _) => modes::ignore::ignore_path(cfg, &e.path),
        _ => Ok(()),
    }
}

fn row_menu(cfg: &mut Config, dir: &str, e: &Entry, section: Section) -> Result<()> {
    let mut options: Vec<(&str, char)> = vec![("View diff", 'd')];
    match section {
        Section::Staged => options.push(("Unstage", 'u')),
        Section::Unstaged | Section::Untracked => {
            options.push(("Stage", 'a'));
            options.push(("Discard changes", 'x'));
            options.push(("Ignore this path", 'i'));
        }
        Section::Conflicted => options.push(("Resolve in Conflicts mode", 'a')),
    }
    options.push(("Commit staged changes", 'c'));
    let labels: Vec<&str> = options.iter().map(|o| o.0).collect();
    let context = [row_text(e, section)];
    let Some(pick) = ui::choose("File actions", &context, &labels)? else {
        return Ok(());
    };
    match options[pick].1 {
        'd' => open_row(cfg, dir, e, section),
        'c' => commit_staged(cfg),
        key => row_action(cfg, dir, key, e, section),
    }
}

fn open_row(cfg: &mut Config, dir: &str, e: &Entry, section: Section) -> Result<()> {
    if section == Section::Conflicted {
        return conflict_menu(cfg, e);
    }
    view_diff(cfg, dir, e, section)
}

fn diff_keys(section: Section) -> &'static [ui::Key] {
    const STAGE: [ui::Key; 2] = [
        ui::Key {
            key: 'a',
            label: "stage hunk",
        },
        ui::Key {
            key: 'x',
            label: "discard hunk",
        },
    ];
    const UNSTAGE: [ui::Key; 1] = [ui::Key {
        key: 'a',
        label: "unstage hunk",
    }];
    const UNTRACKED: [ui::Key; 1] = [ui::Key {
        key: 'a',
        label: "stage file",
    }];
    match section {
        Section::Unstaged => &STAGE,
        Section::Staged => &UNSTAGE,
        _ => &UNTRACKED,
    }
}

/// Does one hunk action; returns whether the repo changed.
fn hunk_action(
    cfg: &Config,
    dir: &str,
    section: Section,
    key: char,
    fd: &FileDiff,
    idx: usize,
) -> Result<bool> {
    match (section, key) {
        (Section::Unstaged, 'a') => stage_hunk(dir, fd, idx)?,
        (Section::Staged, 'a') => unstage_hunk(dir, fd, idx)?,
        (Section::Unstaged, 'x') => {
            let verdict = policy::check(cfg, &Op::DiscardUnstaged);
            let what = "Throw away this hunk from your working copy? This cannot be undone.";
            if !ui::gate(cfg, &verdict, what, "git apply -R -")? {
                return Ok(false);
            }
            discard_hunk_exec(dir, fd, idx)?;
        }
        _ => return Ok(false),
    }
    Ok(true)
}

fn view_diff(cfg: &mut Config, dir: &str, e: &Entry, section: Section) -> Result<()> {
    let mut acted = false;
    loop {
        let files = match load_files(dir, section, e) {
            Ok(files) => files,
            Err(error) => return ui::notice("Cannot show diff", &[error.to_string()]),
        };
        if acted && diff::hunk_count(&files) == 0 {
            return Ok(());
        }
        let lines = diff::display_lines(&files, MAX_DIFF_LINES);
        if lines.is_empty() {
            return say(
                "No differences",
                "Nothing to show (an empty file or no textual change).",
            );
        }
        let kind = if section == Section::Staged {
            "Staged"
        } else {
            "Unstaged"
        };
        let title = format!("{kind} diff: {}", row_text(e, section).trim());
        match ui::diff_view(&title, &lines, diff_keys(section))? {
            ui::DiffChoice::Back => return Ok(()),
            ui::DiffChoice::Action(key, hunk) => {
                if section == Section::Untracked {
                    report(stage_paths(dir, std::slice::from_ref(&e.path)))?;
                    return Ok(());
                }
                if let Some((fi, hi)) = diff::locate_hunk(&files, hunk) {
                    match hunk_action(cfg, dir, section, key, &files[fi], hi) {
                        Ok(changed) => acted |= changed,
                        Err(error) if !input::is_cancel(&error) => {
                            ui::notice("Git said no", &[error.to_string()])?;
                        }
                        Err(error) => return Err(error),
                    }
                }
            }
        }
    }
}

/// Entry point called by the mode router (`modes::run_mode`) inside an active terminal UI.
pub fn run(config: &mut Config) -> Result<()> {
    let mut index = 0usize;
    loop {
        let state = repo_state::load()?;
        let dir = state.workdir.to_string_lossy().into_owned();
        let dir = dir.as_str();
        let rows = build_rows(&state.entries);
        let header = header_lines(&rows);
        let texts: Vec<String> = rows
            .iter()
            .map(|r| row_text(&state.entries[r.entry], r.section))
            .collect();
        let choice = ui::action_list(
            "Stage: files and hunks",
            &header,
            &texts,
            &LIST_KEYS,
            &mut index,
        )?;
        let (key, at) = match choice {
            ui::Choice::Back => return Ok(()),
            ui::Choice::Open(i) => ('d', i),
            ui::Choice::Action(key, i) => (key, i),
        };
        let row = rows.get(at).copied();
        match (key, row) {
            ('r', _) => {}
            ('A', _) => report(stage_all(dir, &state.entries))?,
            ('U', _) => report(unstage_all(dir, &state.entries))?,
            ('c', _) => commit_staged(config)?,
            (_, None) => {}
            ('d', Some(r)) => open_row(config, dir, &state.entries[r.entry], r.section)?,
            ('m', Some(r)) => row_menu(config, dir, &state.entries[r.entry], r.section)?,
            (k, Some(r)) => row_action(config, dir, k, &state.entries[r.entry], r.section)?,
        }
    }
}

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

    fn entry(path: &str, x: char, y: char, kind: EntryKind) -> Entry {
        Entry {
            path: path.into(),
            orig_path: None,
            x,
            y,
            kind,
        }
    }

    fn d(repo: &TempRepo) -> String {
        repo.path().to_string_lossy().into_owned()
    }

    fn numbered(change_a: bool, change_b: bool) -> String {
        (1..=40)
            .map(|i| match (i, change_a, change_b) {
                (3, true, _) => "THREE\n".to_string(),
                (38, _, true) => "THIRTY-EIGHT\n".to_string(),
                _ => format!("line {i}\n"),
            })
            .collect()
    }

    fn base_repo() -> TempRepo {
        let repo = TempRepo::new(1);
        repo.write("big.txt", &numbered(false, false));
        repo.git(&["add", "big.txt"]);
        repo.git(&["commit", "-qm", "big"]);
        repo.write("big.txt", &numbered(true, true));
        repo
    }

    #[test]
    fn rows_are_grouped_by_section() {
        let entries = vec![
            entry("u.txt", '?', '?', EntryKind::Untracked),
            entry("both.txt", 'M', 'M', EntryKind::Ordinary),
            entry("c.txt", 'U', 'U', EntryKind::Unmerged),
            entry("i.txt", '!', '!', EntryKind::Ignored),
            entry("s.txt", 'A', '.', EntryKind::Ordinary),
        ];
        let rows = build_rows(&entries);
        let got: Vec<(usize, Section)> = rows.iter().map(|r| (r.entry, r.section)).collect();
        assert_eq!(
            got,
            vec![
                (1, Section::Staged),
                (4, Section::Staged),
                (1, Section::Unstaged),
                (0, Section::Untracked),
                (2, Section::Conflicted)
            ]
        );
        assert!(header_lines(&rows)[0].contains("Staged 2"));
        assert!(header_lines(&[]).len() == 2);
    }

    #[test]
    fn rename_row_shows_both_names() {
        let mut e = entry("new.txt", 'R', '.', EntryKind::Renamed);
        e.orig_path = Some("old.txt".into());
        assert!(row_text(&e, Section::Staged).ends_with("old.txt -> new.txt"));
        assert_eq!(
            entry_paths(&e),
            vec!["old.txt".to_string(), "new.txt".to_string()]
        );
    }

    #[test]
    fn diff_args_per_section() {
        let e = entry("a b.txt", 'M', 'M', EntryKind::Ordinary);
        assert!(diff_args(Section::Staged, &e)
            .unwrap()
            .contains(&"--cached".to_string()));
        let un = diff_args(Section::Unstaged, &e).unwrap();
        assert!(!un.contains(&"--cached".to_string()));
        assert_eq!(un.last().unwrap(), "a b.txt");
        let nu = diff_args(Section::Untracked, &e).unwrap();
        assert!(nu.contains(&"--no-index".to_string()) && nu.contains(&NULL_FILE.to_string()));
        assert!(diff_args(Section::Conflicted, &e).is_none());
    }

    #[test]
    fn clean_uses_d_only_for_directories() {
        assert_eq!(clean_args("f.txt"), vec!["clean", "-f", "--", "f.txt"]);
        assert_eq!(clean_args("dir/"), vec!["clean", "-f", "-d", "--", "dir/"]);
    }

    #[test]
    fn discard_untracked_is_danger_even_when_confirmations_off() {
        let cfg = Config {
            confirm_destructive: false,
            ..Config::default()
        };
        assert_eq!(
            policy::check(&cfg, &Op::DiscardUntracked),
            policy::Verdict::Danger
        );
        assert_eq!(
            policy::check(&cfg, &Op::DiscardUnstaged),
            policy::Verdict::Danger
        );
    }

    #[test]
    fn stage_only_first_hunk_round_trip() {
        let repo = base_repo();
        repo.run(|| {
            let e = entry("big.txt", '.', 'M', EntryKind::Ordinary);
            let files = load_files(&d(&repo), Section::Unstaged, &e).unwrap();
            assert_eq!(files[0].hunks.len(), 2);
            stage_hunk(&d(&repo), &files[0], 0).unwrap();
        });
        let cached = repo.git(&["diff", "--cached"]);
        assert!(cached.contains("+THREE") && !cached.contains("THIRTY-EIGHT"));
        let work = repo.git(&["diff"]);
        assert!(work.contains("+THIRTY-EIGHT") && !work.contains("THREE"));
    }

    #[test]
    fn unstage_one_hunk_round_trip() {
        let repo = base_repo();
        repo.git(&["add", "big.txt"]);
        repo.run(|| {
            let e = entry("big.txt", 'M', '.', EntryKind::Ordinary);
            let files = load_files(&d(&repo), Section::Staged, &e).unwrap();
            assert_eq!(files[0].hunks.len(), 2);
            unstage_hunk(&d(&repo), &files[0], 0).unwrap();
        });
        let cached = repo.git(&["diff", "--cached"]);
        assert!(cached.contains("+THIRTY-EIGHT") && !cached.contains("THREE"));
        assert!(repo.git(&["diff"]).contains("+THREE"));
    }

    #[test]
    fn discard_one_hunk_keeps_the_other() {
        let repo = base_repo();
        repo.run(|| {
            let e = entry("big.txt", '.', 'M', EntryKind::Ordinary);
            let files = load_files(&d(&repo), Section::Unstaged, &e).unwrap();
            discard_hunk_exec(&d(&repo), &files[0], 1).unwrap();
        });
        let work = repo.git(&["diff"]);
        assert!(work.contains("+THREE") && !work.contains("THIRTY-EIGHT"));
    }

    #[test]
    fn crlf_hunk_stages_cleanly() {
        let repo = TempRepo::new(1);
        let crlf = |a: &str| -> String {
            (1..=30)
                .map(|i| {
                    if i == 2 {
                        format!("{a}\r\n")
                    } else {
                        format!("l{i}\r\n")
                    }
                })
                .collect()
        };
        repo.write("w.txt", &crlf("old"));
        repo.git(&["add", "w.txt"]);
        repo.git(&["commit", "-qm", "w"]);
        repo.write("w.txt", &crlf("new"));
        repo.run(|| {
            let e = entry("w.txt", '.', 'M', EntryKind::Ordinary);
            let files = load_files(&d(&repo), Section::Unstaged, &e).unwrap();
            stage_hunk(&d(&repo), &files[0], 0).unwrap();
        });
        assert!(repo.git(&["diff"]).is_empty());
    }

    #[test]
    fn discard_tracked_restores_content() {
        let repo = TempRepo::new(1);
        repo.write("f1.txt", "scribble");
        repo.run(|| discard_tracked_exec(&d(&repo), "f1.txt").unwrap());
        assert!(repo.git(&["status", "--porcelain"]).is_empty());
    }

    #[test]
    fn discard_untracked_removes_file_and_dir() {
        let repo = TempRepo::new(1);
        repo.write("new.txt", "x");
        repo.write("d/inner.txt", "y");
        repo.run(|| {
            discard_untracked_exec(&d(&repo), "new.txt").unwrap();
            discard_untracked_exec(&d(&repo), "d/").unwrap();
        });
        assert!(repo.git(&["status", "--porcelain"]).is_empty());
    }

    #[test]
    fn untracked_diff_shows_added_lines() {
        let repo = TempRepo::new(1);
        repo.write("fresh.txt", "one\ntwo\n");
        repo.run(|| {
            let e = entry("fresh.txt", '?', '?', EntryKind::Untracked);
            let files = load_files(&d(&repo), Section::Untracked, &e).unwrap();
            assert_eq!(files[0].hunks.len(), 1);
            let shown = diff::display_lines(&files, 100);
            assert!(shown.contains(&"+one".to_string()));
        });
    }

    #[test]
    fn bulk_stage_and_unstage_via_stdin() {
        let repo = TempRepo::new(1);
        let names: Vec<String> = (0..5).map(|i| format!("n{i}.txt")).collect();
        for n in &names {
            repo.write(n, "x");
        }
        repo.write("odd [x].txt", "x");
        let mut all = names.clone();
        all.push("odd [x].txt".into());
        repo.run(|| stage_paths(&d(&repo), &all).unwrap());
        assert_eq!(
            repo.git(&["diff", "--cached", "--name-only"])
                .lines()
                .count(),
            6
        );
        repo.run(|| unstage_paths(&d(&repo), &all).unwrap());
        assert!(repo.git(&["diff", "--cached", "--name-only"]).is_empty());
    }

    #[test]
    fn unstage_on_unborn_head() {
        let repo = TempRepo::new(0);
        repo.write("a.txt", "x");
        repo.git(&["add", "a.txt"]);
        repo.run(|| unstage_paths(&d(&repo), &["a.txt".to_string()]).unwrap());
        assert!(repo.git(&["ls-files"]).is_empty());
    }

    #[test]
    fn unstaging_a_rename_restores_both_paths() {
        let repo = TempRepo::new(1);
        repo.git(&["mv", "f1.txt", "moved.txt"]);
        repo.run(|| {
            let state = repo_state::load().unwrap();
            let e = state
                .entries
                .iter()
                .find(|e| e.path == "moved.txt")
                .unwrap();
            assert_eq!(e.orig_path.as_deref(), Some("f1.txt"));
            unstage_paths(&d(&repo), &entry_paths(e)).unwrap();
        });
        assert!(repo.git(&["diff", "--cached", "--name-only"]).is_empty());
        let status = repo.git(&["status", "--porcelain"]);
        assert!(status.contains(" D f1.txt") && status.contains("?? moved.txt"));
    }

    /// Runs `f` with the process in `repo/sub`, like gct started from a subfolder.
    fn in_sub<T>(repo: &TempRepo, f: impl FnOnce() -> T) -> T {
        crate::git::with_ctx(&repo.path().join("sub"), repo.env(), f)
    }

    #[test]
    fn executors_work_from_a_subfolder() {
        let repo = TempRepo::new(1);
        repo.write("same.txt", "root\n");
        repo.write("sub/same.txt", "sub\n");
        repo.git(&["add", "."]);
        repo.git(&["commit", "-qm", "two"]);
        repo.write("same.txt", "root changed\n");
        repo.write("sub/same.txt", "sub changed\n");
        let dir = d(&repo);
        in_sub(&repo, || stage_paths(&dir, &["same.txt".to_string()])).unwrap();
        assert_eq!(repo.git(&["diff", "--cached", "--name-only"]), "same.txt");
        in_sub(&repo, || unstage_paths(&dir, &["same.txt".to_string()])).unwrap();
        assert!(repo.git(&["diff", "--cached", "--name-only"]).is_empty());
        // Hunk staging of the root file via its root-relative path.
        let e = entry("same.txt", '.', 'M', EntryKind::Ordinary);
        let files = in_sub(&repo, || load_files(&dir, Section::Unstaged, &e)).unwrap();
        in_sub(&repo, || stage_hunk(&dir, &files[0], 0)).unwrap();
        assert_eq!(repo.git(&["diff", "--cached", "--name-only"]), "same.txt");
        // Discards hit the root file only.
        in_sub(&repo, || discard_tracked_exec(&dir, "same.txt")).unwrap();
        assert_eq!(
            std::fs::read_to_string(repo.path().join("sub/same.txt")).unwrap(),
            "sub changed\n"
        );
        repo.write("new.txt", "x");
        repo.write("sub/new.txt", "y");
        in_sub(&repo, || discard_untracked_exec(&dir, "new.txt")).unwrap();
        assert!(!repo.path().join("new.txt").exists() && repo.path().join("sub/new.txt").exists());
    }

    #[test]
    fn hunks_survive_user_diff_settings() {
        let repo = base_repo();
        repo.git(&["config", "diff.noprefix", "true"]);
        repo.git(&["config", "diff.mnemonicPrefix", "true"]);
        repo.run(|| {
            let e = entry("big.txt", '.', 'M', EntryKind::Ordinary);
            let files = load_files(&d(&repo), Section::Unstaged, &e).unwrap();
            stage_hunk(&d(&repo), &files[0], 0).unwrap();
        });
        let cached = repo.git(&["diff", "--cached"]);
        assert!(cached.contains("+THREE") && !cached.contains("THIRTY-EIGHT"));
    }
}