delta-gitu 0.1.18

An experimental fork of gitu (a git client inspired by Magit), published as a library for delta to embed
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
//! The git command whose output gitu is paging.
//!
//! Set as git's pager, gitu is handed a patch and told nothing about the
//! question it answers — not the subcommand, not the revs, not the options. The
//! command is in the process tree, though: git spawns its pager as a child, and
//! a shell pipeline puts the two side by side. Finding it there is what lets
//! gitu ask git the same question again — for more of the file around each
//! change — and know what the patch is a diff *of*, which is what decides
//! whether staging part of it means anything.

use crate::Res;
use crate::error::Error;
use crate::git::diff::DiffType;
use std::iter;
use std::path::Path;
use std::process::Command;
use sysinfo::{Pid, Process, ProcessRefreshKind, ProcessesToUpdate, System, UpdateKind};

/// The subcommands whose output gitu structures.
const SUBCOMMANDS: [&str; 3] = ["diff", "show", "log"];

/// The subcommands an edited command may ask for. gitu re-runs the command it
/// holds on every rebuild — staging a hunk re-asks it — so a command that
/// changed anything would run repeatedly and unbidden.
const READ_ONLY: [&str; 10] = [
    "diff", "show", "log", "blame", "grep", "shortlog", "reflog", "ls-files", "describe", "status",
];

/// git's own options that take the next word as their value.
const VALUED: [&str; 6] = [
    "-C",
    "-c",
    "--git-dir",
    "--work-tree",
    "--namespace",
    "--config-env",
];

/// How many aliases deep to look for the command an alias stands for. git
/// itself stops only at a loop.
const ALIAS_DEPTH: usize = 16;

/// How far above gitu to look for the git process: git may spawn its pager
/// through a shell, and that shell through another.
const ANCESTORS: usize = 3;

/// The diffstat a command asks for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Stat {
    No,
    /// git's own and no patch, as `git log --stat` asks for: shown as git
    /// prints it. With no patch there is no context to ask for.
    Git,
    /// A diffstat and the patch, as `git log -p --stat` asks for: gitu counts
    /// it from the patch, and heads each file with its stat row.
    WithPatch,
    /// `git diff --stat`: gitu asks for the patch, counts the stat from it,
    /// and starts each file folded to its stat row.
    Folded,
}

impl Stat {
    /// Whether gitu counts it from the patch.
    pub(crate) fn is_counted(self) -> bool {
        matches!(self, Self::WithPatch | Self::Folded)
    }
}

/// Whether `arg` is git's `--stat` option.
fn is_stat_option(arg: &str) -> bool {
    arg == "--stat" || arg.starts_with("--stat=")
}

/// A git invocation gitu can put again.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct GitCommand {
    argv: Vec<String>,
    /// Where the subcommand sits in `argv`. What precedes it is git's own
    /// (`-c k=v`, `--git-dir=…`) and has to stay in front of it.
    subcommand: usize,
    /// Where git ran it, relative to the repository's root, as git's
    /// `GIT_PREFIX` says: empty at the root, else ending in `/`. Its paths are
    /// relative to there.
    prefix: String,
}

impl GitCommand {
    /// The invocation `argv` is, if it is one whose output gitu structures.
    pub(crate) fn of(argv: Vec<String>) -> Option<Self> {
        let subcommand = subcommand_at(&argv)?;
        SUBCOMMANDS
            .contains(&argv[subcommand].as_str())
            .then_some(Self {
                argv,
                subcommand,
                prefix: String::new(),
            })
    }

    /// The same command run in `prefix` (see [`Self::prefix`]).
    pub(crate) fn run_in(self, prefix: String) -> Self {
        Self { prefix, ..self }
    }

    pub(crate) fn prefix(&self) -> &str {
        &self.prefix
    }

    /// What the patch is a diff of, which is what decides whether staging or
    /// unstaging part of it means anything (see [`DiffType`]). Only a `git diff`
    /// of the working tree or of the index is either of those; naming a rev
    /// makes it a comparison of two trees, as `git show` and `git log -p`
    /// always are.
    pub(crate) fn diff_type(&self) -> DiffType {
        if self.subcommand() != "diff" {
            return DiffType::TreeToTree;
        }

        let args: Vec<&str> = self.arguments().take_while(|arg| *arg != "--").collect();
        if args.contains(&"--cached") || args.contains(&"--staged") {
            DiffType::IndexToTree
        } else if args.iter().any(|arg| !arg.starts_with('-')) {
            // The value of a separated option (`-U 8`) reads as a rev here, so
            // such a diff is taken for a comparison of two trees. Nothing reads
            // the other way round, so the mistake only ever narrows the ops.
            DiffType::TreeToTree
        } else {
            DiffType::WorkdirToIndex
        }
    }

    /// The diffstat the command asks for. git takes `-U` as asking for the
    /// patch too; here it is the context of the patches a stat's files unfold
    /// to, which is how gitu writes the context it is asked for into the
    /// command.
    pub(crate) fn stat(&self) -> Stat {
        let args: Vec<&str> = self.arguments().take_while(|arg| *arg != "--").collect();
        let stat = args
            .iter()
            .any(|arg| is_stat_option(arg) || *arg == "--patch-with-stat");
        let patch = args
            .iter()
            .any(|arg| matches!(*arg, "-p" | "-u" | "--patch" | "--patch-with-stat"));
        match (stat, patch) {
            (false, _) => Stat::No,
            (true, true) => Stat::WithPatch,
            (true, false) if self.subcommand() == "diff" => Stat::Folded,
            (true, false) => Stat::Git,
        }
    }

    /// The same command asking for the patch alone in place of any diffstat,
    /// which gitu counts from the patch itself rather than have git work it
    /// out before writing anything else.
    pub(crate) fn as_patch(&self) -> Self {
        let end = self
            .argv
            .iter()
            .position(|arg| arg == "--")
            .unwrap_or(self.argv.len());
        let argv = self
            .argv
            .iter()
            .enumerate()
            .filter(|&(i, arg)| i >= end || !(is_stat_option(arg) || arg == "--patch-with-stat"))
            .map(|(_, arg)| arg.clone());
        let mut argv: Vec<String> = argv.collect();
        argv.insert(self.subcommand + 1, "--patch".to_owned());
        Self {
            argv,
            subcommand: self.subcommand,
            prefix: self.prefix.clone(),
        }
    }

    /// The command again, asking for `context` around each change (`-U8`,
    /// `-W`) in place of whatever it originally asked for. `None` puts the
    /// question exactly as git put it.
    pub(crate) fn command(&self, context: Option<&str>) -> Command {
        let words = self.words(context);
        let mut command = Command::new(words[0]);
        // git colours what it writes to a pager, and colours a format asks for
        // (`%C(blue)`) are the user's: they reach the renderer as they would
        // in a terminal, and gitu strips them before parsing what comes back.
        command.args(["-c", "color.ui=always"]);
        command.args(&words[1..=self.subcommand]);
        // An external differ must not stand in for the patch gitu parses.
        command.arg("--no-ext-diff");
        command.args(&words[self.subcommand + 1..]);
        command
    }

    /// The command as gitu is putting it, for the user to edit. The flags gitu
    /// forces are left out: they are not the question, and not the user's to
    /// change.
    pub(crate) fn line(&self, context: Option<&str>) -> String {
        let words = self.words(context);
        iter::once("git")
            .chain(words[1..].iter().copied())
            .map(quoted)
            .collect::<Vec<_>>()
            .join(" ")
    }

    /// The command an edit of [`Self::line`] asks for. git's program and its own
    /// options are fixed — gitu's ops act on the repository gitu opened, and an
    /// edit pointing git elsewhere would make the view and the ops disagree —
    /// and the subcommand must be one that only reports.
    pub(crate) fn edited(&self, line: &str) -> Res<Self> {
        let words = shell_words::split(line).map_err(|_| Error::EditedCommandQuotes)?;
        let own = &self.argv[1..self.subcommand];

        let [program, rest @ ..] = words.as_slice() else {
            return Err(Error::EditedCommandFixed);
        };
        if program != "git" || !rest.starts_with(own) {
            return Err(Error::EditedCommandFixed);
        }

        match rest.get(own.len()) {
            None => return Err(Error::EditedCommandFixed),
            Some(subcommand) if !READ_ONLY.contains(&subcommand.as_str()) => {
                return Err(Error::EditedCommandWrites(subcommand.clone()));
            }
            Some(_) => (),
        }

        Ok(Self {
            argv: iter::once(self.argv[0].clone())
                .chain(rest.iter().cloned())
                .collect(),
            subcommand: self.subcommand,
            prefix: self.prefix.clone(),
        })
    }

    /// The paths the command limits itself to, as the user writes them (see
    /// [`pattern_of`]). What follows `--` is pathspecs; a command that names
    /// none limits nothing.
    pub(crate) fn file_patterns(&self) -> Vec<String> {
        self.pathspecs()
            .map(|pathspec| pattern_of(pathspec, &self.prefix))
            .collect()
    }

    /// The same command asking for these paths in place of whatever it asked
    /// for before.
    pub(crate) fn asking_for(&self, patterns: &[String]) -> Self {
        let mut argv: Vec<String> = self.argv[..=self.subcommand].to_vec();
        argv.extend(
            self.arguments()
                .take_while(|arg| *arg != "--")
                .map(str::to_owned),
        );
        if !patterns.is_empty() {
            argv.push("--".to_owned());
            argv.extend(patterns.iter().map(|pattern| pathspec_of(pattern)));
        }

        Self {
            argv,
            subcommand: self.subcommand,
            prefix: self.prefix.clone(),
        }
    }

    fn pathspecs(&self) -> impl Iterator<Item = &str> {
        self.arguments().skip_while(|arg| *arg != "--").skip(1)
    }

    /// git's own options and the subcommand, then what is asked of it with
    /// `context` in place of whatever it said.
    fn words<'a>(&'a self, context: Option<&'a str>) -> Vec<&'a str> {
        let mut words: Vec<&str> = self.argv[..=self.subcommand]
            .iter()
            .map(String::as_str)
            .collect();
        words.extend(context);
        match context {
            Some(_) => words.extend(without_context(self.arguments())),
            None => words.extend(self.arguments()),
        }
        words
    }

    /// The git subcommand, such as `log`.
    pub(crate) fn subcommand(&self) -> &str {
        &self.argv[self.subcommand]
    }

    /// What was asked of the subcommand.
    fn arguments(&self) -> impl Iterator<Item = &str> + Clone {
        self.argv[self.subcommand + 1..].iter().map(String::as_str)
    }
}

/// The pathspec a file pattern asks for. The language is git's own, less the
/// magic: a bare pattern limits the diff to what it matches, `!` excludes what
/// it matches, and a pattern that is already a pathspec is passed on as it is.
/// The wildcards are git's, so `*_test.go` matches at any depth and a directory
/// matches its subtree.
///
/// `:(top)` is not decoration: a pathspec is relative to git's working
/// directory and gitu asks from the root of the repository, where the paths a
/// diff names are also rooted.
fn pathspec_of(pattern: &str) -> String {
    match pattern {
        _ if pattern.starts_with(':') => pattern.to_owned(),
        _ if let Some(glob) = pattern.strip_prefix('!') => format!(":(top,exclude){glob}"),
        _ => format!(":(top){pattern}"),
    }
}

/// The pattern a pathspec came from, so that a command's paths can be offered
/// back for editing. A pathspec of git's own is relative to `prefix`, where git
/// ran, and a pattern to the root, where the diff's paths are; one with magic
/// gitu does not write is shown as it is.
fn pattern_of(pathspec: &str, prefix: &str) -> String {
    if let Some(glob) = pathspec.strip_prefix(":(top,exclude)") {
        return format!("!{glob}");
    }
    if let Some(glob) = pathspec.strip_prefix(":(top)") {
        return glob.to_owned();
    }
    if pathspec.starts_with(':') {
        return pathspec.to_owned();
    }

    format!("{prefix}{pathspec}")
}

/// The pattern that excludes one file and nothing else. A path holding
/// wildcards has to say it means them literally; anything else reads better,
/// and round-trips through [`pattern_of`], as a glob.
pub(crate) fn excluding(path: &str) -> String {
    if path.contains(['*', '?', '[', '\\']) {
        return format!(":(top,exclude,literal){path}");
    }

    format!("!{path}")
}

/// `word` as it has to be written to survive being read back, and to mean the
/// same thing if it is pasted into a shell. Revisions (`HEAD~2`, `x^!`) and
/// git's own `k=v` options are left bare; a pathspec's parentheses and
/// wildcards are not.
fn quoted(word: &str) -> String {
    const BARE: &str = "_@%+=:,./-~^";

    if !word.is_empty()
        && word
            .chars()
            .all(|c| c.is_alphanumeric() || BARE.contains(c))
    {
        return word.to_owned();
    }

    format!("'{}'", word.replace('\'', r"'\''"))
}

/// `args` with whatever they said about context dropped, so that what gitu asks
/// for is what git is asked for.
fn without_context<'a>(args: impl Iterator<Item = &'a str>) -> Vec<&'a str> {
    let mut kept = Vec::new();
    let mut value_follows = false;

    for arg in args {
        if std::mem::take(&mut value_follows) {
            continue;
        }
        match arg {
            "-U" | "--unified" => value_follows = true,
            "-W" | "--function-context" | "--no-function-context" => {}
            _ if arg.starts_with("-U") || arg.starts_with("--unified=") => {}
            _ => kept.push(arg),
        }
    }

    kept
}

/// The argv of the git command gitu is paging the output of, looked for in the
/// two places it can be: above gitu, which is where git puts its pager, and
/// beside it, which is where a shell pipeline puts it.
///
/// As delta finds its calling process: each ancestor is read on its own, and
/// for a sibling the process numbered just below gitu is tried first, since a
/// shell starting a pipeline usually numbers its commands in order. Reading
/// every process on the machine, which takes most of the time, is the last
/// resort.
pub(crate) fn paging_for() -> Option<Vec<String>> {
    let mut system = System::new();
    let me = Pid::from_u32(std::process::id());

    let mut descendant = me;
    refresh(&mut system, &[me]);
    for _ in 0..ANCESTORS {
        let Some(ancestor) = system.process(descendant).and_then(Process::parent) else {
            break;
        };
        refresh(&mut system, &[ancestor]);
        if let Some(argv) = git_argv(&system, ancestor) {
            return Some(argv);
        }
        descendant = ancestor;
    }

    // `git diff | gitu`: the shell created both, so git is the sibling
    // of gitu rather than its ancestor.
    let shell = system.process(me)?.parent()?;
    let is_sibling = |system: &System, pid: Pid| {
        pid != me && system.process(pid).and_then(Process::parent) == Some(shell)
    };

    let previous = Pid::from_u32(std::process::id().checked_sub(1)?);
    refresh(&mut system, &[previous]);
    if is_sibling(&system, previous)
        && let Some(argv) = git_argv(&system, previous)
    {
        return Some(argv);
    }

    // Two of them and there is no telling which produced the input.
    system.refresh_processes_specifics(ProcessesToUpdate::All, true, command_lines());
    let mut siblings = system
        .processes()
        .keys()
        .filter(|&&pid| is_sibling(&system, pid))
        .filter_map(|&pid| git_argv(&system, pid));

    siblings.next().filter(|_| siblings.next().is_none())
}

fn refresh(system: &mut System, pids: &[Pid]) {
    system.refresh_processes_specifics(ProcessesToUpdate::Some(pids), true, command_lines());
}

fn command_lines() -> ProcessRefreshKind {
    ProcessRefreshKind::nothing().with_cmd(UpdateKind::Always)
}

/// The argv of `pid`, if it is a git command gitu can put again.
fn git_argv(system: &System, pid: Pid) -> Option<Vec<String>> {
    let argv: Vec<String> = system
        .process(pid)?
        .cmd()
        .iter()
        .map(|arg| arg.to_string_lossy().into_owned())
        .collect();

    GitCommand::of(expanded(argv)).map(|git| git.argv)
}

/// `argv` with the alias it runs, if it runs one, replaced by what it stands
/// for, as git expands it: an alias may stand for another. One that does not
/// come to a command, or comes back to itself, is left as it is.
///
/// git runs a command of its own, or a `git-<name>` on its path, in preference
/// to an alias of the same name. gitu looks only at its own few subcommands,
/// so an alias with the name of another command is wrongly expanded.
fn expanded(argv: Vec<String>) -> Vec<String> {
    let mut expanding = argv.clone();
    for _ in 0..ALIAS_DEPTH {
        let Some(at) = subcommand_at(&expanding) else {
            return argv;
        };
        if SUBCOMMANDS.contains(&expanding[at].as_str()) {
            return expanding;
        }
        let Some(words) = alias(&expanding[..at], &expanding[at]) else {
            return expanding;
        };
        expanding.splice(at..=at, words);
    }
    argv
}

/// Where the subcommand of a git invocation is: the first word that is not one
/// of git's own options or an option's value.
fn subcommand_at(argv: &[String]) -> Option<usize> {
    let program = Path::new(argv.first()?).file_stem()?.to_str()?;
    if !program.eq_ignore_ascii_case("git") {
        return None;
    }

    let mut value_follows = false;
    argv.iter().enumerate().skip(1).find_map(|(i, arg)| {
        if std::mem::take(&mut value_follows) {
            return None;
        }
        value_follows = VALUED.contains(&arg.as_str());
        (!arg.starts_with('-')).then_some(i)
    })
}

/// The words alias `name` stands for, read as git reads it with `own`, git and
/// its own options. A shell alias (`!…`) runs a command of its own and stands
/// for none.
fn alias(own: &[String], name: &str) -> Option<Vec<String>> {
    let output = Command::new(&own[0])
        .args(&own[1..])
        .args(["config", "--get", &format!("alias.{name}")])
        .output()
        .ok()?;
    let value = String::from_utf8(output.stdout).ok()?;
    let value = value.trim_end_matches('\n');
    if !output.status.success() || value.starts_with('!') {
        return None;
    }
    shell_words::split(value)
        .ok()
        .filter(|words| !words.is_empty())
}

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

    fn git(args: &[&str]) -> GitCommand {
        GitCommand::of(args.iter().map(|arg| (*arg).to_owned()).collect()).unwrap()
    }

    fn rerun(args: &[&str], context: Option<&str>) -> Vec<String> {
        let command = git(args).command(context);
        std::iter::once(command.get_program())
            .chain(command.get_args())
            .map(|arg| arg.to_string_lossy().into_owned())
            .collect()
    }

    #[test]
    fn a_git_command_is_recognised_behind_its_own_options() {
        assert_eq!(
            git(&["/usr/bin/git", "-c", "color.diff=always", "diff"]).subcommand(),
            "diff"
        );
        assert_eq!(git(&["git.exe", "show", "HEAD"]).subcommand(), "show");
        assert_eq!(GitCommand::of(vec!["ls".to_owned()]), None);
        assert_eq!(GitCommand::of(vec!["git".to_owned()]), None);
        assert_eq!(
            GitCommand::of(["git", "status"].map(String::from).to_vec()),
            None
        );
    }

    /// Whether a patch is of the working tree, of the index, or of two trees is
    /// what the command says it is.
    #[test]
    fn the_command_says_what_the_patch_is_a_diff_of() {
        assert_eq!(git(&["git", "diff"]).diff_type(), DiffType::WorkdirToIndex);
        assert_eq!(
            git(&["git", "diff", "-U8", "--", "src/lib.rs"]).diff_type(),
            DiffType::WorkdirToIndex
        );
        assert_eq!(
            git(&["git", "diff", "--cached"]).diff_type(),
            DiffType::IndexToTree
        );
        assert_eq!(
            git(&["git", "diff", "main"]).diff_type(),
            DiffType::TreeToTree
        );
        assert_eq!(
            git(&["git", "show", "HEAD"]).diff_type(),
            DiffType::TreeToTree
        );
    }

    /// What the user is given to edit is the question as gitu is putting it,
    /// less the flags gitu forces on every ask.
    #[test]
    fn the_line_offered_for_editing_is_the_effective_command() {
        assert_eq!(git(&["git", "diff", "main"]).line(None), "git diff main");
        assert_eq!(
            git(&["/usr/bin/git", "-c", "color.ui=always", "diff"]).line(None),
            "git -c color.ui=always diff"
        );
        assert_eq!(
            git(&["git", "diff", "-U10", "main"]).line(Some("-U2")),
            "git diff -U2 main"
        );
        assert_eq!(
            git(&["git", "log", "-p", "--", "a file"]).line(None),
            "git log -p -- 'a file'"
        );
    }

    #[test]
    fn an_edit_may_ask_git_anything_that_only_reports() {
        let edited = |line: &str| {
            git(&["/usr/bin/git", "diff", "main"])
                .edited(line)
                .map(|git| git.line(None))
        };

        assert_eq!(edited("git show HEAD~2").unwrap(), "git show HEAD~2");
        assert_eq!(edited("git log -p -- src").unwrap(), "git log -p -- src");
        assert_eq!(
            edited("git diff main -- ':(top,exclude)*_test.go'").unwrap(),
            "git diff main -- ':(top,exclude)*_test.go'"
        );
    }

    /// The program gitu found is the program gitu runs, whatever the edit says.
    #[test]
    fn an_edit_leaves_the_program_and_gits_own_options_alone() {
        let git = git(&["/usr/bin/git", "-c", "color.ui=always", "diff"]);
        let program = |line: &str| Ok::<_, Error>(git.edited(line)?.argv[0].clone());

        assert_eq!(
            program("git -c color.ui=always show").unwrap(),
            "/usr/bin/git"
        );
        assert!(matches!(
            program("/usr/bin/git -c color.ui=always show"),
            Err(Error::EditedCommandFixed)
        ));
        assert!(matches!(
            program("git show"),
            Err(Error::EditedCommandFixed)
        ));
        assert!(matches!(
            program("git -c color.ui=always --git-dir=/elsewhere show"),
            Err(Error::EditedCommandWrites(_))
        ));
    }

    /// The held command is re-run on every rebuild, so nothing that writes may
    /// be held.
    #[test]
    fn an_edit_that_would_change_the_repository_is_refused() {
        let git = git(&["git", "diff"]);

        assert!(matches!(
            git.edited("git commit --amend"),
            Err(Error::EditedCommandWrites(subcommand)) if subcommand == "commit"
        ));
        assert!(matches!(
            git.edited("git reset --hard"),
            Err(Error::EditedCommandWrites(_))
        ));
        assert!(matches!(git.edited("git"), Err(Error::EditedCommandFixed)));
        assert!(matches!(
            git.edited("git diff 'unbalanced"),
            Err(Error::EditedCommandQuotes)
        ));
    }

    /// The paths a command asks for are what the user wrote, so they can be
    /// offered back and asked again unchanged.
    #[test]
    fn the_paths_asked_for_round_trip_through_their_patterns() {
        let patterns = ["src", "!*_test.go", ":(top,exclude,literal)a[1].go"].map(String::from);
        let asked = git(&["git", "diff", "main"]).asking_for(&patterns);

        assert_eq!(
            asked.line(None),
            "git diff main -- ':(top)src' ':(top,exclude)*_test.go' ':(top,exclude,literal)a[1].go'"
        );
        assert_eq!(asked.file_patterns(), patterns);
        assert_eq!(asked.asking_for(&asked.file_patterns()), asked);
    }

    /// Asking for other paths replaces the ones asked for before, and asking
    /// for none leaves no `--` behind.
    #[test]
    fn the_paths_asked_for_are_replaced_wholesale() {
        let git = git(&["git", "diff", "-U8", "main", "--", "src"]);

        assert_eq!(
            git.asking_for(&["lib".to_owned()]).line(None),
            "git diff -U8 main -- ':(top)lib'"
        );
        assert_eq!(git.asking_for(&[]).line(None), "git diff -U8 main");
    }

    /// A file is hidden by name, and a name that holds wildcards has to say it
    /// means them literally.
    #[test]
    fn one_file_is_excluded_by_its_own_name() {
        assert_eq!(excluding("src/gen/a.pb.go"), "!src/gen/a.pb.go");
        assert_eq!(
            excluding("src/a[1].go"),
            ":(top,exclude,literal)src/a[1].go"
        );
    }

    #[test]
    fn asking_again_keeps_the_question_and_replaces_the_context() {
        assert_eq!(
            rerun(&["git", "-c", "color.ui=always", "diff", "main"], None),
            [
                "git",
                "-c",
                "color.ui=always",
                "-c",
                "color.ui=always",
                "diff",
                "--no-ext-diff",
                "main"
            ]
        );
        assert_eq!(
            rerun(&["git", "diff", "-U10", "main", "--", "src"], Some("-U2")),
            [
                "git",
                "-c",
                "color.ui=always",
                "diff",
                "--no-ext-diff",
                "-U2",
                "main",
                "--",
                "src"
            ]
        );
        assert_eq!(
            rerun(&["git", "diff", "--unified", "10"], Some("-W")),
            [
                "git",
                "-c",
                "color.ui=always",
                "diff",
                "--no-ext-diff",
                "-W"
            ]
        );
        assert_eq!(
            rerun(&["git", "diff", "--function-context"], Some("-U3")),
            [
                "git",
                "-c",
                "color.ui=always",
                "diff",
                "--no-ext-diff",
                "-U3"
            ]
        );
    }

    fn repo_with_aliases(aliases: &[(&str, &str)]) -> temp_dir::TempDir {
        let dir = temp_dir::TempDir::new().unwrap();
        let git = |args: &[&str]| {
            let status = Command::new("git")
                .arg("-C")
                .arg(dir.path())
                .args(args)
                .status()
                .unwrap();
            assert!(status.success());
        };
        git(&["init", "-q"]);
        for (name, value) in aliases {
            git(&["config", &format!("alias.{name}"), value]);
        }
        dir
    }

    fn expanded_in(dir: &temp_dir::TempDir, args: &[&str]) -> Vec<String> {
        let dir = dir.path().to_string_lossy();
        let argv = ["git", "-C", &dir]
            .iter()
            .chain(args)
            .map(|arg| (*arg).to_owned())
            .collect();
        expanded(argv)[3..].to_vec()
    }

    /// git expands an alias in its own process, so the command line gitu finds
    /// is the alias.
    #[test]
    fn an_alias_is_expanded_to_the_command_it_stands_for() {
        let dir = repo_with_aliases(&[("lg", "log --oneline --format='%h %s'")]);
        assert_eq!(
            expanded_in(&dir, &["lg", "-p"]),
            ["log", "--oneline", "--format=%h %s", "-p"]
        );
    }

    #[test]
    fn an_alias_of_an_alias_is_expanded_to_the_command() {
        let dir = repo_with_aliases(&[("l", "lg -p"), ("lg", "log --oneline")]);
        assert_eq!(expanded_in(&dir, &["l"]), ["log", "--oneline", "-p"]);
    }

    #[test]
    fn an_alias_given_on_the_command_line_is_expanded() {
        let dir = repo_with_aliases(&[]);
        assert_eq!(
            expanded_in(&dir, &["-c", "alias.d=diff --cached", "d"]),
            ["-c", "alias.d=diff --cached", "diff", "--cached"]
        );
    }

    /// A shell alias runs a command of its own, which is not git's.
    #[test]
    fn a_shell_alias_is_left_as_it_is() {
        let dir = repo_with_aliases(&[("sh", "!git log")]);
        assert_eq!(expanded_in(&dir, &["sh"]), ["sh"]);
    }

    #[test]
    fn a_subcommand_is_not_looked_up_as_an_alias() {
        let dir = repo_with_aliases(&[("log", "diff")]);
        assert_eq!(expanded_in(&dir, &["log"]), ["log"]);
    }

    #[test]
    fn aliases_that_expand_to_each_other_are_left_as_they_are() {
        let dir = repo_with_aliases(&[("a", "b"), ("b", "a")]);
        assert_eq!(expanded_in(&dir, &["a"]), ["a"]);
    }
}