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
//! Compare mode: pick two revisions, see how far apart they are, which files differ and
//! which commits are only on one side.

use super::files::{describe_change, parse_name_status, top_spec, NameStatus};
use crate::git::{self, Opts};
use crate::history::{self, LogEntry};
use crate::{model::Config, ui};
use anyhow::{bail, Result};

const DIFF_MAX_LINES: usize = 5000;

// ---------------------------------------------------------------- pure helpers

/// `git rev-list --left-right --count A...B` prints "<only in A>\t<only in B>".
pub fn parse_left_right_count(text: &str) -> Option<(usize, usize)> {
    let mut f = text.split_whitespace();
    let left = f.next()?.parse().ok()?;
    let right = f.next()?.parse().ok()?;
    Some((left, right))
}

/// The revision arguments for diff: `A...B` (since the split) or `A B` (tips only).
pub fn compare_args(a: &str, b: &str, three_dot: bool) -> Vec<String> {
    if three_dot {
        vec![format!("{a}...{b}")]
    } else {
        vec![a.to_string(), b.to_string()]
    }
}

/// "B is 3 ahead, 1 behind A" in plain English.
pub fn describe_counts(a: &str, b: &str, left: usize, right: usize) -> String {
    let s = |n: usize| if n == 1 { "commit" } else { "commits" };
    match (right, left) {
        (0, 0) => format!("{b} and {a} point at the same history."),
        (r, 0) => format!("{b} is {r} {} ahead of {a} (and 0 behind)", s(r)),
        (0, l) => format!("{b} is 0 ahead, {l} {} behind {a}", s(l)),
        (r, l) => format!("{b} is {r} {} ahead, {l} {} behind {a}", s(r), s(l)),
    }
}

/// One sentence explaining the current dot mode.
pub fn dots_explanation(three_dot: bool) -> &'static str {
    if three_dot {
        "Three dots (A...B): only what B changed since the two branched apart."
    } else {
        "Two dots (A..B): every difference between the two tips right now, including A's own new work."
    }
}

/// Splits `log --left-right --cherry-mark --format=%m%x1d<LOG_FORMAT>` into (mark, commit).
pub fn parse_marked_log(text: &str) -> Vec<(char, LogEntry)> {
    text.split('\u{1e}')
        .filter_map(|rec| {
            let rec = rec.trim_start_matches(['\n', '\r', ' ']);
            let (mark, rest) = rec.split_once('\u{1d}')?;
            let entry = history::parse_log(&format!("{rest}\u{1e}"))
                .into_iter()
                .next()?;
            Some((mark.chars().next().unwrap_or('?'), entry))
        })
        .collect()
}

fn check_rev(rev: &str) -> Result<()> {
    if rev.trim().is_empty() || rev.starts_with('-') {
        bail!("Invalid revision: {rev}");
    }
    Ok(())
}

fn row_text(n: &NameStatus) -> String {
    format!("{} {}  ({})", n.status, n.path, describe_change(n))
}

// ---------------------------------------------------------------- executors

/// What the compare screen shows for one pair of revisions.
#[derive(Debug, Clone)]
pub struct Comparison {
    pub header: Vec<String>,
    pub files: Vec<NameStatus>,
    /// The dot mode actually used (falls back to two dots without a merge-base).
    pub three_dot: bool,
}

fn rev_oid(rev: &str) -> Result<String> {
    let spec = format!("{rev}^{{commit}}");
    git::git_ok(
        &["rev-parse", "--verify", "--end-of-options", &spec],
        &Opts::default(),
    )
}

pub fn compare(a: &str, b: &str, want_three_dot: bool) -> Result<Comparison> {
    check_rev(a)?;
    check_rev(b)?;
    let (oa, ob) = (rev_oid(a)?, rev_oid(b)?);
    let mut header = Vec::new();
    let mut three_dot = want_three_dot;
    if three_dot
        && git::git_raw(&["merge-base", &oa, &ob], &Opts::default())?
            .text()
            .is_empty()
    {
        three_dot = false;
        header.push(
            "Warning: these two share no history; comparing the tips directly (two dots)."
                .to_string(),
        );
    }
    if oa == ob {
        header.insert(0, format!("{a} and {b} are the same commit."));
        return Ok(Comparison {
            header,
            files: vec![],
            three_dot,
        });
    }
    let sym = format!("{oa}...{ob}");
    let counts = git::git_ok(
        &["rev-list", "--left-right", "--count", &sym],
        &Opts::default(),
    )?;
    if let Some((l, r)) = parse_left_right_count(&counts) {
        header.insert(0, describe_counts(a, b, l, r));
    }
    header.push(dots_explanation(three_dot).to_string());
    let range = compare_args(&oa, &ob, three_dot);
    let mut args: Vec<&str> = vec![
        "-c",
        "core.quotepath=false",
        "diff",
        "--name-status",
        "-z",
        "-M",
    ];
    args.extend(range.iter().map(String::as_str));
    let text = git::git_ok(
        &args,
        &Opts {
            max_lines: Some(20_000),
            ..Opts::default()
        },
    )?;
    let files = parse_name_status(&text);
    if files.is_empty() {
        header.push("Nothing differs: the files are identical.".into());
    }
    Ok(Comparison {
        header,
        files,
        three_dot,
    })
}

/// The diff of one file between `a` and `b`, capped at `DIFF_MAX_LINES`.
pub fn file_diff(a: &str, b: &str, three_dot: bool, f: &NameStatus) -> Result<Vec<String>> {
    check_rev(a)?;
    check_rev(b)?;
    let range = compare_args(a, b, three_dot);
    let mut specs = vec![top_spec(&f.path)];
    if let Some(old) = &f.old {
        specs.push(top_spec(old));
    }
    let mut args: Vec<&str> = vec!["diff", "-M", "--no-color"];
    args.extend(range.iter().map(String::as_str));
    args.push("--");
    args.extend(specs.iter().map(String::as_str));
    let text = git::git_ok(
        &args,
        &Opts {
            max_lines: Some(DIFF_MAX_LINES),
            ..Opts::default()
        },
    )?;
    Ok(text.lines().map(String::from).collect())
}

/// Commits on either side (`<` only in A, `>` only in B, `=` same change on both).
pub fn side_commits(a: &str, b: &str) -> Result<Vec<(char, LogEntry)>> {
    check_rev(a)?;
    check_rev(b)?;
    let fmt = format!("--format=%m%x1d{}", history::LOG_FORMAT);
    let sym = format!("{a}...{b}");
    let text = git::git_ok(
        &[
            "log",
            "--left-right",
            "--cherry-mark",
            &fmt,
            "-n",
            "300",
            &sym,
        ],
        &Opts {
            max_lines: Some(5000),
            ..Opts::default()
        },
    )?;
    Ok(parse_marked_log(&text))
}

// ---------------------------------------------------------------- UI

/// Entry point called by the mode router (`modes::run_mode`) inside an active terminal UI.
pub fn run(config: &mut Config) -> Result<()> {
    let Some(a) = ui::pick_ref("Compare: pick A (the base)", true, true, true)? else {
        return Ok(());
    };
    let Some(b) = ui::pick_ref("Compare: pick B (what to look at)", true, true, true)? else {
        return Ok(());
    };
    open(config, &a, &b)
}

/// Compares revisions `a` and `b` (cross-mode entry point).
pub fn open(cfg: &mut Config, a: &str, b: &str) -> Result<()> {
    let (mut a, mut b) = (a.to_string(), b.to_string());
    let mut three_dot = true;
    let mut index = 0;
    loop {
        let (x, y) = (a.clone(), b.clone());
        let cmp = match ui::git_job("Comparing...", move || compare(&x, &y, three_dot)) {
            Ok(c) => c,
            Err(e) if e.to_string() == crate::input::CANCELLED => return Err(e),
            Err(e) => {
                ui::notice("Compare", &[e.to_string()])?;
                return Ok(());
            }
        };
        three_dot = cmp.three_dot;
        let mut header = vec![format!("A = {a}    B = {b}")];
        header.extend(cmp.header.iter().cloned());
        header.push("Enter shows a file diff. M opens the menu.".into());
        let rows: Vec<String> = cmp.files.iter().map(row_text).collect();
        let keys = [
            ui::Key {
                key: 't',
                label: "two/three dots",
            },
            ui::Key {
                key: 'c',
                label: "commits",
            },
            ui::Key {
                key: 'x',
                label: "swap A and B",
            },
            ui::Key {
                key: 'r',
                label: "refresh",
            },
            ui::Key {
                key: 'm',
                label: "menu",
            },
        ];
        let action = match ui::action_list("Compare", &header, &rows, &keys, &mut index)? {
            ui::Choice::Back => return Ok(()),
            ui::Choice::Open(i) => {
                if let Some(f) = cmp.files.get(i) {
                    show_file(&a, &b, cmp.three_dot, f)?;
                }
                continue;
            }
            ui::Choice::Action(c, _) => c,
        };
        let action = if action == 'm' {
            let ctx = vec![format!("{a} vs {b}")];
            let opts = [
                "Commits on each side",
                "Switch two/three dots",
                "Swap A and B",
                "Pick A again",
                "Pick B again",
                "Refresh",
            ];
            match ui::choose("Compare menu", &ctx, &opts)? {
                Some(0) => 'c',
                Some(1) => 't',
                Some(2) => 'x',
                Some(3) => 'A',
                Some(4) => 'B',
                Some(5) => 'r',
                _ => continue,
            }
        } else {
            action
        };
        match action {
            't' => {
                three_dot = !three_dot;
                index = 0;
            }
            'x' => {
                std::mem::swap(&mut a, &mut b);
                index = 0;
            }
            'A' => {
                if let Some(r) = ui::pick_ref("Compare: pick A", true, true, true)? {
                    a = r;
                    index = 0;
                }
            }
            'B' => {
                if let Some(r) = ui::pick_ref("Compare: pick B", true, true, true)? {
                    b = r;
                    index = 0;
                }
            }
            'c' => commits_view(cfg, &a, &b)?,
            _ => {}
        }
    }
}

fn show_file(a: &str, b: &str, three_dot: bool, f: &NameStatus) -> Result<()> {
    let (x, y, f2) = (a.to_string(), b.to_string(), f.clone());
    let lines = match ui::git_job("Reading diff...", move || file_diff(&x, &y, three_dot, &f2)) {
        Ok(l) => l,
        Err(e) if e.to_string() == crate::input::CANCELLED => return Err(e),
        Err(e) => return ui::notice("Compare", &[e.to_string()]),
    };
    let binary = lines
        .iter()
        .any(|l| l.starts_with("Binary files") || l.starts_with("GIT binary patch"));
    if binary {
        return ui::notice("Compare", &[format!("Binary files differ: {}", f.path)]);
    }
    if lines.is_empty() {
        return ui::notice("Compare", &["Nothing differs in this file.".into()]);
    }
    ui::diff_view(&format!("{} ({a} vs {b})", f.path), &lines, &[])?;
    Ok(())
}

fn commits_view(cfg: &mut Config, a: &str, b: &str) -> Result<()> {
    let (x, y) = (a.to_string(), b.to_string());
    let commits = ui::git_job("Reading commits...", move || side_commits(&x, &y))?;
    if commits.is_empty() {
        return ui::notice("Commits", &["No commits differ between these two.".into()]);
    }
    let rows: Vec<String> = commits
        .iter()
        .map(|(m, e)| {
            format!(
                "{m} {} {} {:<14.14} {}",
                e.short,
                e.author_date.get(..10).unwrap_or(""),
                e.author,
                e.subject
            )
        })
        .collect();
    let header = vec![
        format!("< only in A ({a})   > only in B ({b})   = same change on both"),
        "Enter opens the commit.".into(),
    ];
    let mut index = 0;
    loop {
        match ui::action_list("Commits", &header, &rows, &[], &mut index)? {
            ui::Choice::Open(i) => {
                if let Some((_, e)) = commits.get(i) {
                    super::log::show(cfg, &e.oid)?;
                }
            }
            ui::Choice::Action(_, _) => {}
            ui::Choice::Back => return Ok(()),
        }
    }
}

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

    #[test]
    fn counts_and_args() {
        assert_eq!(parse_left_right_count("1\t3\n"), Some((1, 3)));
        assert_eq!(parse_left_right_count(""), None);
        assert_eq!(parse_left_right_count("x y"), None);
        assert_eq!(compare_args("main", "dev", true), vec!["main...dev"]);
        assert_eq!(compare_args("main", "dev", false), vec!["main", "dev"]);
        assert_eq!(
            describe_counts("main", "dev", 1, 3),
            "dev is 3 commits ahead, 1 commit behind main"
        );
        assert!(describe_counts("a", "b", 0, 0).contains("same"));
        assert!(dots_explanation(true).contains("Three dots"));
        assert!(dots_explanation(false).contains("Two dots"));
    }

    #[test]
    fn marked_log_parses() {
        let rec = |m: &str, o: &str| {
            format!("{m}\u{1d}{o}\u{1f}{}\u{1f}\u{1f}An\u{1f}a@x\u{1f}2024-01-01T00:00:00+00:00\u{1f}2024-01-01T00:00:00+00:00\u{1f}\u{1f}subj\u{1e}\n", &o[..3])
        };
        let text = format!("{}{}", rec("<", &"1".repeat(40)), rec(">", &"2".repeat(40)));
        let v = parse_marked_log(&text);
        assert_eq!(v.len(), 2);
        assert_eq!(v[0].0, '<');
        assert_eq!(v[1].0, '>');
        assert_eq!(v[1].1.subject, "subj");
    }

    fn diverged() -> TempRepo {
        let repo = TempRepo::new(2);
        repo.git(&["checkout", "-qb", "dev"]);
        repo.write("dev.txt", "d\n");
        repo.git(&["add", "."]);
        repo.git(&["commit", "-qm", "dev 1"]);
        repo.write("dev2.txt", "d\n");
        repo.git(&["add", "."]);
        repo.git(&["commit", "-qm", "dev 2"]);
        repo.git(&["checkout", "-q", "main"]);
        repo.write("main.txt", "m\n");
        repo.git(&["add", "."]);
        repo.git(&["commit", "-qm", "main 1"]);
        repo
    }

    #[test]
    fn compare_counts_after_divergence() {
        let repo = diverged();
        let c = repo.run(|| compare("main", "dev", true)).unwrap();
        assert!(c.three_dot && !c.files.is_empty());
        assert_eq!(c.header[0], "dev is 2 commits ahead, 1 commit behind main");
        let paths: Vec<&str> = c.files.iter().map(|f| f.path.as_str()).collect();
        assert_eq!(paths, vec!["dev.txt", "dev2.txt"]);
        let two = repo.run(|| compare("main", "dev", false)).unwrap();
        assert_eq!(two.files.len(), 3);
        let commits = repo.run(|| side_commits("main", "dev")).unwrap();
        assert_eq!(commits.iter().filter(|(m, _)| *m == '>').count(), 2);
        assert_eq!(commits.iter().filter(|(m, _)| *m == '<').count(), 1);
        let f = c.files[0].clone();
        let d = repo.run(|| file_diff("main", "dev", true, &f)).unwrap();
        assert!(d.iter().any(|l| l == "+d"));
    }

    #[test]
    fn compare_identical_and_unrelated() {
        let repo = TempRepo::new(2);
        let c = repo.run(|| compare("main", "HEAD", true)).unwrap();
        assert!(c.files.is_empty());
        assert!(c.header[0].contains("same commit"));
        repo.git(&["checkout", "-q", "--orphan", "other"]);
        repo.write("o.txt", "o\n");
        repo.git(&["add", "o.txt"]);
        repo.git(&["commit", "-qm", "orphan"]);
        let u = repo.run(|| compare("main", "other", true)).unwrap();
        assert!(!u.three_dot);
        assert!(u.header.iter().any(|h| h.starts_with("Warning")));
        assert!(!u.files.is_empty());
        assert!(repo.run(|| compare("-x", "main", true)).is_err());
    }
}