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
//! Files mode: browse tracked files, per-file history (following renames), blame and line
//! history.

use crate::git::{self, Opts};
use crate::history::{self, LogEntry};
use crate::{model::Config, ui};
use anyhow::{bail, Result};
use std::collections::HashMap;

const EMPTY_TREE: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
const ZERO_OID: &str = "0000000000000000000000000000000000000000";
const MAX_FILE_ROWS: usize = 500;
const BIG_FILE_LINES: usize = 3000;
const BLAME_WINDOW: usize = 500;

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

/// Turns Windows separators into `/` and drops a leading `./`.
pub fn normalize_path(path: &str) -> String {
    let p = path.trim().replace('\\', "/");
    p.strip_prefix("./").unwrap_or(&p).to_string()
}

/// A pathspec that always means "from the repository root", whatever the current directory.
pub fn top_spec(path: &str) -> String {
    format!(":(top,literal){}", normalize_path(path))
}

/// One entry of `git ... --name-status`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NameStatus {
    /// First letter of the status: A M D R C T U.
    pub status: char,
    /// Similarity score of a rename/copy (R75 -> 75).
    pub score: Option<u32>,
    pub path: String,
    /// Old path for renames and copies.
    pub old: Option<String>,
}

/// Parses `--name-status -z` output: NUL separated tokens, a status code followed by one path
/// (two for renames and copies). Odd framing (stray newlines, empty tokens) is tolerated and
/// unknown statuses are skipped.
pub fn parse_name_status(text: &str) -> Vec<NameStatus> {
    let mut tokens = text.split('\0');
    let mut out = Vec::new();
    while let Some(raw) = tokens.next() {
        let code = raw.trim();
        let Some(status) = code.chars().next().filter(|c| "AMDRCTU".contains(*c)) else {
            continue;
        };
        let score = code[1..].parse().ok();
        let Some(first) = tokens.next() else { break };
        if matches!(status, 'R' | 'C') {
            let Some(new) = tokens.next() else { break };
            out.push(NameStatus {
                status,
                score,
                path: new.to_string(),
                old: Some(first.to_string()),
            });
        } else {
            out.push(NameStatus {
                status,
                score,
                path: first.to_string(),
                old: None,
            });
        }
    }
    out
}

/// A short plain-English label for a change.
pub fn describe_change(n: &NameStatus) -> String {
    match (n.status, &n.old) {
        ('A', _) => "added".into(),
        ('M', _) => "modified".into(),
        ('D', _) => "deleted".into(),
        ('T', _) => "type changed".into(),
        ('U', _) => "unmerged".into(),
        ('R', Some(old)) => format!("renamed, was {old}"),
        ('C', Some(old)) => format!("copied from {old}"),
        (c, _) => c.to_string(),
    }
}

/// Splits `ls-files -z` output and filters case-insensitively by substring. Returns the
/// shown rows (at most `MAX_FILE_ROWS`) and how many more matched.
pub fn filter_files(list: &str, filter: &str) -> (Vec<String>, usize) {
    let needle = filter.trim().to_lowercase();
    let all: Vec<String> = list
        .split('\0')
        .filter(|p| !p.is_empty())
        .filter(|p| needle.is_empty() || p.to_lowercase().contains(&needle))
        .map(String::from)
        .collect();
    let more = all.len().saturating_sub(MAX_FILE_ROWS);
    (all.into_iter().take(MAX_FILE_ROWS).collect(), more)
}

/// What `git diff --numstat <empty-tree> HEAD -- path` says about a file.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileKind {
    Binary,
    Lines(usize),
    Unknown,
}

pub fn file_kind(numstat: &str) -> FileKind {
    let Some(line) = numstat.lines().next() else {
        return FileKind::Unknown;
    };
    let mut f = line.split('\t');
    match (f.next(), f.next()) {
        (Some("-"), Some("-")) => FileKind::Binary,
        (Some(added), Some(_)) => added.parse().map_or(FileKind::Unknown, FileKind::Lines),
        _ => FileKind::Unknown,
    }
}

/// Parses "12,40" or "12" into an inclusive line range.
pub fn parse_range(text: &str) -> Option<(usize, usize)> {
    let t = text.trim();
    let (a, b) = match t.split_once(',') {
        Some((a, b)) => (a.trim().parse().ok()?, b.trim().parse().ok()?),
        None => {
            let a: usize = t.parse().ok()?;
            (a, a)
        }
    };
    (a >= 1 && b >= a).then_some((a, b))
}

/// First line of the blame window that contains `line` (1-based), clamped to the file.
pub fn window_start(line: usize, total: usize) -> usize {
    let start = line.saturating_sub(BLAME_WINDOW / 2).max(1);
    start.min(total.saturating_sub(BLAME_WINDOW).max(1))
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlameLine {
    pub oid: String,
    pub author: String,
    /// YYYY-MM-DD in the author's time zone.
    pub date: String,
    pub orig_line: usize,
    pub line_no: usize,
    pub text: String,
    pub boundary: bool,
    pub uncommitted: bool,
    /// `previous <sha> <path>`: where this line's commit last saw the file.
    pub previous: Option<(String, String)>,
    /// The file's path in the blamed commit (differs from the current one after a rename).
    pub filename: String,
    pub summary: String,
}

#[derive(Default, Clone)]
struct Meta {
    author: String,
    time: i64,
    tz: i64,
    boundary: bool,
    previous: Option<(String, String)>,
    filename: String,
    summary: String,
}

fn is_blame_header(line: &str) -> Option<(String, usize, usize)> {
    let mut f = line.split(' ');
    let oid = f.next()?;
    if !(oid.len() == 40 || oid.len() == 64) || !oid.bytes().all(|b| b.is_ascii_hexdigit()) {
        return None;
    }
    let orig = f.next()?.parse().ok()?;
    let fin = f.next()?.parse().ok()?;
    Some((oid.to_string(), orig, fin))
}

/// Parses `git blame --porcelain`. Header fields only appear the first time a commit shows
/// up; later lines of the same commit reuse them.
pub fn parse_blame_porcelain(text: &str) -> Vec<BlameLine> {
    let mut metas: HashMap<String, Meta> = HashMap::new();
    let mut out = Vec::new();
    let mut current: Option<(String, usize, usize)> = None;
    for raw in text.split('\n') {
        let line = raw.strip_suffix('\r').unwrap_or(raw);
        if let Some(content) = line.strip_prefix('\t') {
            if let Some((oid, orig, fin)) = current.take() {
                let m = metas.get(&oid).cloned().unwrap_or_default();
                let uncommitted = oid == ZERO_OID;
                out.push(BlameLine {
                    author: if uncommitted {
                        "Not committed yet".into()
                    } else {
                        m.author
                    },
                    date: if uncommitted {
                        String::new()
                    } else {
                        format_date(m.time, m.tz)
                    },
                    uncommitted,
                    oid,
                    orig_line: orig,
                    line_no: fin,
                    text: content.to_string(),
                    boundary: m.boundary,
                    previous: m.previous,
                    filename: m.filename,
                    summary: m.summary,
                });
            }
            continue;
        }
        if let Some(h) = is_blame_header(line) {
            metas.entry(h.0.clone()).or_default();
            current = Some(h);
            continue;
        }
        let Some((oid, _, _)) = &current else {
            continue;
        };
        let m = metas.entry(oid.clone()).or_default();
        let (key, value) = line.split_once(' ').unwrap_or((line, ""));
        match key {
            "author" => m.author = value.to_string(),
            "author-time" => m.time = value.parse().unwrap_or(0),
            "author-tz" => m.tz = parse_tz(value).unwrap_or(0),
            "summary" => m.summary = value.to_string(),
            "boundary" => m.boundary = true,
            "filename" => m.filename = value.to_string(),
            "previous" => {
                m.previous = value
                    .split_once(' ')
                    .map(|(sha, path)| (sha.to_string(), path.to_string()));
            }
            _ => {}
        }
    }
    out
}

/// "+0530" -> seconds east of UTC. None unless it is a sign plus exactly four ASCII digits.
fn parse_tz(tz: &str) -> Option<i64> {
    let sign = match tz.as_bytes().first()? {
        b'-' => -1,
        b'+' => 1,
        _ => return None,
    };
    let digits = &tz[1..];
    if digits.len() != 4 || !digits.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    let h: i64 = digits[..2].parse().ok()?;
    let m: i64 = digits[2..].parse().ok()?;
    Some(sign * (h * 3600 + m * 60))
}

/// Epoch seconds + zone offset -> "YYYY-MM-DD".
fn format_date(epoch: i64, tz: i64) -> String {
    let days = (epoch + tz).div_euclid(86_400);
    // Howard Hinnant's civil-from-days.
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };
    format!("{y:04}-{m:02}-{d:02}")
}

/// One commit of a file's history and what it did to the file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HistoryRow {
    pub entry: LogEntry,
    pub change: Option<NameStatus>,
}

/// Parses `log --format=%x1d<LOG_FORMAT> --name-status` output.
pub fn parse_history(text: &str) -> Vec<HistoryRow> {
    text.split('\u{1d}')
        .filter_map(|section| {
            let (record, rest) = section.split_once('\u{1e}')?;
            let entry = history::parse_log(&format!("{record}\u{1e}"))
                .into_iter()
                .next()?;
            let change = parse_name_status(rest).into_iter().next();
            Some(HistoryRow { entry, change })
        })
        .collect()
}

fn date10(iso: &str) -> &str {
    iso.get(..10).unwrap_or(iso)
}

fn history_row_text(r: &HistoryRow) -> String {
    let what = r.change.as_ref().map(describe_change).unwrap_or_default();
    format!(
        "{} {} {:<14.14} {}  [{}]",
        r.entry.short,
        date10(&r.entry.author_date),
        r.entry.author,
        r.entry.subject,
        what
    )
}

fn blame_row_text(l: &BlameLine) -> String {
    let text = l.text.replace('\t', "    ");
    if l.uncommitted {
        return format!(
            "{:<8} {:<14} {:<10} {:>5} | {text}",
            "-", "Not committed yet", "", l.line_no
        );
    }
    let mark = if l.boundary { "^" } else { "" };
    format!(
        "{:<8} {:<14.14} {:<10} {:>5} | {text}",
        format!("{mark}{}", l.oid.get(..7).unwrap_or(&l.oid)),
        l.author,
        l.date,
        l.line_no
    )
}

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

fn opts(max_lines: usize) -> Opts<'static> {
    Opts {
        max_lines: Some(max_lines),
        ..Opts::default()
    }
}

/// Tracked files (paths relative to the repository root).
pub fn list_files() -> Result<String> {
    git::git_ok(
        &["ls-files", "-z", "--full-name", "--", ":(top)"],
        &Opts::default(),
    )
}

/// History of `path`, following renames, newest first.
pub fn file_history(path: &str) -> Result<Vec<HistoryRow>> {
    let fmt = format!("--format=%x1d{}", history::LOG_FORMAT);
    let spec = top_spec(path);
    let text = git::git_ok(
        &[
            "-c",
            "core.quotepath=false",
            "log",
            "--follow",
            "-M",
            &fmt,
            "--name-status",
            "-z",
            "-n",
            "200",
            "--",
            &spec,
        ],
        &opts(5000),
    )?;
    Ok(parse_history(&text))
}

/// Classifies `path` at HEAD (binary, or its line count).
pub fn kind_of(path: &str) -> FileKind {
    let spec = top_spec(path);
    git::git_ok(
        &["diff", "--numstat", EMPTY_TREE, "HEAD", "--", &spec],
        &Opts::default(),
    )
    .map_or(FileKind::Unknown, |t| file_kind(&t))
}

fn is_text_attr_unset(path: &str) -> bool {
    let spec = top_spec(path);
    git::git_ok(&["check-attr", "text", "--", &spec], &Opts::default())
        .map(|t| t.trim_end().ends_with(": unset"))
        .unwrap_or(false)
}

/// Blame of `path` (repo-root relative) at `rev` (None = working tree), optionally only the
/// `BLAME_WINDOW` lines starting at `start`.
pub fn blame(path: &str, rev: Option<&str>, start: Option<usize>) -> Result<Vec<BlameLine>> {
    let cdup = git::git_ok(&["rev-parse", "--show-cdup"], &Opts::default())?;
    let rel = format!("{}{}", cdup.trim(), normalize_path(path));
    let range = start.map(|s| format!("{s},+{BLAME_WINDOW}"));
    let mut args: Vec<&str> = vec!["blame", "--porcelain", "-M", "-w"];
    if let Some(r) = &range {
        args.extend(["-L", r]);
    }
    if let Some(rev) = rev {
        if rev.starts_with('-') {
            bail!("Invalid revision: {rev}");
        }
        args.push(rev);
    }
    args.extend(["--", &rel]);
    let text = git::git_ok(&args, &opts(80_000))?;
    Ok(parse_blame_porcelain(&text))
}

/// `git log -L` output for lines a..b of `path`.
pub fn line_history(path: &str, a: usize, b: usize) -> Result<Vec<String>> {
    let cdup = git::git_ok(&["rev-parse", "--show-cdup"], &Opts::default())?;
    let spec = format!("{a},{b}:{}{}", cdup.trim(), normalize_path(path));
    let text = git::git_ok(&["log", "-L", &spec, "--no-color", "-n", "50"], &opts(5000))?;
    Ok(text.lines().map(String::from).collect())
}

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

/// Entry point called by the mode router (`modes::run_mode`) inside an active terminal UI.
pub fn run(config: &mut Config) -> Result<()> {
    let list = ui::git_job("Listing files...", list_files)?;
    let mut filter = match ui::ask("Filter files (part of a name, empty for all)", "")? {
        Some(f) => f,
        None => return Ok(()),
    };
    let mut index = 0;
    loop {
        let (files, more) = filter_files(&list, &filter);
        let mut header = vec![format!("{} file(s) shown", files.len())];
        if more > 0 {
            header.push(format!("+{more} more, refine the filter"));
        }
        if files.is_empty() {
            header.push("No tracked file matches. Press F to change the filter.".into());
        }
        let keys = [ui::Key {
            key: 'f',
            label: "change filter",
        }];
        match ui::action_list("Files", &header, &files, &keys, &mut index)? {
            ui::Choice::Back => return Ok(()),
            ui::Choice::Open(i) => {
                if let Some(path) = files.get(i) {
                    file_menu(config, path)?;
                }
            }
            ui::Choice::Action(_, _) => {
                if let Some(f) = ui::ask("Filter files (part of a name, empty for all)", &filter)? {
                    filter = f;
                    index = 0;
                }
            }
        }
    }
}

/// Opens the history/blame view of `path` (cross-mode entry point).
#[allow(dead_code)] // entry point for other modes
pub fn open(cfg: &mut Config, path: &str) -> Result<()> {
    file_menu(cfg, &normalize_path(path))
}

fn file_menu(cfg: &mut Config, path: &str) -> Result<()> {
    loop {
        let ctx = vec![path.to_string()];
        let opts = [
            "History (follows renames)",
            "Blame (who wrote each line)",
            "Line history",
        ];
        match ui::choose("File", &ctx, &opts)? {
            Some(0) => history_view(cfg, path)?,
            Some(1) => blame_view(cfg, path)?,
            Some(2) => line_history_view(path)?,
            _ => return Ok(()),
        }
    }
}

fn history_view(cfg: &mut Config, path: &str) -> Result<()> {
    let p = path.to_string();
    let rows = ui::git_job("Reading history...", move || file_history(&p))?;
    if rows.is_empty() {
        return ui::notice(
            "History",
            &[
                format!("No commits touch {path} yet."),
                "Commit the file first.".into(),
            ],
        );
    }
    let texts: Vec<String> = rows.iter().map(history_row_text).collect();
    let header = vec![format!(
        "History of {path} (newest first, renames followed)"
    )];
    let mut index = 0;
    loop {
        match ui::action_list("File history", &header, &texts, &[], &mut index)? {
            ui::Choice::Open(i) => {
                if let Some(r) = rows.get(i) {
                    super::log::show(cfg, &r.entry.oid)?;
                }
            }
            ui::Choice::Action(_, _) => {}
            ui::Choice::Back => return Ok(()),
        }
    }
}

fn blame_view(cfg: &mut Config, path: &str) -> Result<()> {
    match kind_of(path) {
        FileKind::Binary => {
            return ui::notice(
                "Blame",
                &[format!(
                    "{path} is a binary file; blame only works on text."
                )],
            );
        }
        _ if is_text_attr_unset(path) => {
            return ui::notice(
                "Blame",
                &[format!(
                    "{path} is marked as binary (-text); blame skipped."
                )],
            );
        }
        _ => {}
    }
    let total = match kind_of(path) {
        FileKind::Lines(n) => n,
        _ => 0,
    };
    let mut start = None;
    if total > BIG_FILE_LINES {
        let answer = ui::ask(&format!("{total} lines: start at which line?"), "1")?;
        let Some(answer) = answer else { return Ok(()) };
        let line = answer.trim().parse().unwrap_or(1);
        start = Some(window_start(line, total));
    }
    // Each "blame before this change" pushes a level; Esc pops one.
    let mut stack: Vec<(Option<String>, String)> = vec![(None, path.to_string())];
    let mut index = 0;
    loop {
        let Some((rev, p)) = stack.last().cloned() else {
            return Ok(());
        };
        let (r2, p2) = (rev.clone(), p.clone());
        let lines = match ui::git_job("Running blame...", move || blame(&p2, r2.as_deref(), start))
        {
            Ok(l) => l,
            Err(e) if e.to_string() == crate::input::CANCELLED => return Err(e),
            Err(e) => {
                ui::notice("Blame", &[e.to_string()])?;
                stack.pop();
                continue;
            }
        };
        let texts: Vec<String> = lines.iter().map(blame_row_text).collect();
        let at = rev
            .as_deref()
            .map_or("working tree".to_string(), |r| r.chars().take(8).collect());
        let mut header = vec![format!("Blame of {p} at {at}")];
        if let Some(s) = start {
            header.push(format!(
                "Showing lines {s}-{} (N next window, P previous)",
                s + BLAME_WINDOW - 1
            ));
        }
        header.push("Enter opens the commit, B shows the file before that change.".into());
        let keys = [
            ui::Key {
                key: 'b',
                label: "blame before this change",
            },
            ui::Key {
                key: 'n',
                label: "next window",
            },
            ui::Key {
                key: 'p',
                label: "previous window",
            },
        ];
        match ui::action_list("Blame", &header, &texts, &keys, &mut index)? {
            ui::Choice::Back => {
                stack.pop();
                index = 0;
            }
            ui::Choice::Open(i) => {
                if let Some(l) = lines.get(i) {
                    if l.uncommitted {
                        ui::notice("Blame", &["This line is not committed yet.".into()])?;
                    } else {
                        super::log::show(cfg, &l.oid)?;
                    }
                }
            }
            ui::Choice::Action('b', i) => {
                let Some(l) = lines.get(i) else { continue };
                if l.uncommitted {
                    stack.push((Some("HEAD".into()), p.clone()));
                } else if let Some((sha, prev_path)) = &l.previous {
                    stack.push((Some(sha.clone()), prev_path.clone()));
                } else {
                    ui::notice(
                        "Blame",
                        &["This line comes from the first commit that has the file; nothing earlier to show.".into()],
                    )?;
                    continue;
                }
                index = 0;
            }
            ui::Choice::Action('n', _) => {
                if let Some(s) = start {
                    if s + BLAME_WINDOW <= total {
                        start = Some(s + BLAME_WINDOW);
                        index = 0;
                    }
                }
            }
            ui::Choice::Action('p', _) => {
                if let Some(s) = start {
                    start = Some(s.saturating_sub(BLAME_WINDOW).max(1));
                    index = 0;
                }
            }
            ui::Choice::Action(_, _) => {}
        }
    }
}

fn line_history_view(path: &str) -> Result<()> {
    let Some(answer) = ui::ask("Line range (start,end), e.g. 10,25", "1,20")? else {
        return Ok(());
    };
    let Some((a, b)) = parse_range(&answer) else {
        return ui::notice(
            "Line history",
            &["Type two line numbers like 10,25 (start at 1).".into()],
        );
    };
    let p = path.to_string();
    match ui::git_job("Tracing lines...", move || line_history(&p, a, b)) {
        Ok(lines) if lines.is_empty() => ui::notice(
            "Line history",
            &["No history found for those lines.".into()],
        ),
        Ok(lines) => ui::pager(&format!("Lines {a}-{b} of {path}"), &lines, "Esc back"),
        Err(e) if e.to_string() == crate::input::CANCELLED => Err(e),
        Err(e) => ui::notice("Line history", &[e.to_string()]),
    }
}

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

    #[test]
    fn name_status_variants() {
        let t = "A\0a.txt\0M\0dir/b c.txt\0D\0d.txt\0T\0t.txt\0U\0u.txt\0R100\0old/x.rs\0new/x.rs\0C75\0s.rs\0copy of s.rs\0bogus\0";
        let v = parse_name_status(t);
        assert_eq!(v.len(), 7);
        assert_eq!(v[1].path, "dir/b c.txt");
        assert_eq!(v[3].status, 'T');
        assert_eq!(v[4].status, 'U');
        assert_eq!(v[5].old.as_deref(), Some("old/x.rs"));
        assert_eq!(v[5].path, "new/x.rs");
        assert_eq!(v[5].score, Some(100));
        assert_eq!(v[6].status, 'C');
        assert_eq!(v[6].score, Some(75));
        assert_eq!(v[6].path, "copy of s.rs");
        assert_eq!(describe_change(&v[5]), "renamed, was old/x.rs");
        assert!(parse_name_status("").is_empty());
        assert_eq!(parse_name_status("\nM\0a.txt\0\0")[0].path, "a.txt");
        // Tabs, quotes and newlines in names come through untouched.
        let odd = parse_name_status("R090\0we\tird\"\n.txt\0new\tname.txt\0");
        assert_eq!(odd[0].old.as_deref(), Some("we\tird\"\n.txt"));
        assert_eq!(odd[0].path, "new\tname.txt");
        // Truncated input never panics.
        assert!(parse_name_status("R100\0only-one").is_empty());
    }

    #[test]
    fn tz_is_total() {
        assert_eq!(parse_tz("+0530"), Some(19_800));
        assert_eq!(parse_tz("-0500"), Some(-18_000));
        for bad in [
            "",
            "+",
            "0530",
            "+05",
            "+05300",
            "+\u{e9}\u{e9}",
            "+0a30",
            "\u{e9}0530",
            "++530",
            "+-530",
        ] {
            assert_eq!(parse_tz(bad), None, "{bad:?}");
        }
    }

    #[test]
    fn history_handles_odd_names_and_literal_brackets() {
        let repo = crate::testutil::TempRepo::new(0);
        repo.write("a1.txt", "decoy line one\nline two\nline three\n");
        repo.write("a[1].txt", "bracket file content here\nmore\nmore again\n");
        repo.git(&["add", "."]);
        repo.git(&["commit", "-qm", "first"]);
        repo.git(&["mv", "a[1].txt", "we ird.txt"]);
        repo.git(&["commit", "-qm", "renamed"]);
        let rows = repo.run(|| file_history("we ird.txt")).unwrap();
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0].change.as_ref().unwrap().status, 'R');
        assert_eq!(
            rows[0].change.as_ref().unwrap().old.as_deref(),
            Some("a[1].txt")
        );
        let lit = repo.run(|| file_history("a[1].txt")).unwrap();
        assert!(lit
            .iter()
            .all(|r| r.change.as_ref().is_some_and(|c| c.path != "a1.txt")));
        // Added, then renamed away: two commits; the decoy a1.txt is not mixed in.
        assert_eq!(lit.len(), 2);
        assert_eq!(repo.run(|| file_history("a1.txt")).unwrap().len(), 1);
    }

    #[test]
    fn blame_parsing() {
        let a = "a".repeat(40);
        let b = "b".repeat(40);
        let text = format!(
            "{a} 1 1 2\nauthor Ann\nauthor-mail <a@x>\nauthor-time 1704110400\nauthor-tz +0000\nsummary first\nboundary\nfilename old.txt\n\tone\n{a} 2 2\n\ttwo\n{b} 3 3 1\nauthor Bob\nauthor-time 1704110400\nauthor-tz -0500\nsummary edit\nprevious {a} old.txt\nfilename new.txt\n\tthr\u{e9}e\n{ZERO_OID} 4 4 1\nauthor Not Committed Yet\nauthor-time 1704110400\nauthor-tz +0000\nsummary Version of new.txt from new.txt\nfilename new.txt\n\tfour\r\n"
        );
        let v = parse_blame_porcelain(&text);
        assert_eq!(v.len(), 4);
        assert!(v[0].boundary && v[1].boundary);
        assert_eq!(v[1].author, "Ann");
        assert_eq!(v[1].text, "two");
        assert_eq!(v[0].date, "2024-01-01");
        assert_eq!(v[2].previous, Some((a.clone(), "old.txt".into())));
        assert_eq!(v[2].filename, "new.txt");
        assert_eq!(v[2].text, "thr\u{e9}e");
        assert_eq!(v[2].date, "2024-01-01");
        assert!(v[3].uncommitted);
        assert_eq!(v[3].author, "Not committed yet");
        assert_eq!(v[3].text, "four");
        assert!(parse_blame_porcelain("").is_empty());
    }

    #[test]
    fn normalize_and_helpers() {
        assert_eq!(normalize_path("src\\modes\\files.rs"), "src/modes/files.rs");
        assert_eq!(normalize_path("./a b.txt"), "a b.txt");
        assert_eq!(top_spec("a\\b"), ":(top,literal)a/b");
        assert_eq!(parse_range("10,25"), Some((10, 25)));
        assert_eq!(parse_range("5"), Some((5, 5)));
        assert_eq!(parse_range("0,3"), None);
        assert_eq!(parse_range("9,3"), None);
        assert_eq!(file_kind("-\t-\tpic.png"), FileKind::Binary);
        assert_eq!(file_kind("12\t0\ta.txt"), FileKind::Lines(12));
        assert_eq!(file_kind(""), FileKind::Unknown);
        assert_eq!(window_start(1, 10_000), 1);
        assert_eq!(window_start(5000, 10_000), 4750);
        assert_eq!(window_start(9999, 10_000), 9500);
        let (rows, more) = filter_files("a/B.rs\0c.txt\0\0x/b.rs\0", "B.RS");
        assert_eq!(rows, vec!["a/B.rs", "x/b.rs"]);
        assert_eq!(more, 0);
        let big: String = (0..600).map(|i| format!("f{i}\0")).collect();
        let (rows, more) = filter_files(&big, "");
        assert_eq!((rows.len(), more), (500, 100));
        assert_eq!(format_date(0, 0), "1970-01-01");
        assert_eq!(format_date(1_704_110_400, 0), "2024-01-01");
    }

    #[test]
    fn history_follows_rename() {
        let repo = TempRepo::new(1);
        repo.write("old name.txt", "a\nb\nc\nd\n");
        repo.git(&["add", "."]);
        repo.git(&["commit", "-qm", "add file"]);
        repo.git(&["mv", "old name.txt", "new.txt"]);
        repo.git(&["commit", "-qm", "rename"]);
        repo.write("new.txt", "a\nb\nc\nd\ne\n");
        repo.git(&["commit", "-qam", "edit"]);
        let rows = repo.run(|| file_history("new.txt")).unwrap();
        let subjects: Vec<&str> = rows.iter().map(|r| r.entry.subject.as_str()).collect();
        assert_eq!(subjects, vec!["edit", "rename", "add file"]);
        let rename = rows[1].change.as_ref().unwrap();
        assert_eq!(rename.status, 'R');
        assert_eq!(rename.old.as_deref(), Some("old name.txt"));
        assert_eq!(rows[2].change.as_ref().unwrap().status, 'A');
    }

    #[test]
    fn blame_attributes_lines() {
        let repo = TempRepo::new(1);
        repo.write("sub/f.txt", "one\ntwo\nthree\n");
        repo.git(&["add", "."]);
        repo.git(&["commit", "-qm", "first"]);
        let first = repo.git(&["rev-parse", "HEAD"]);
        repo.write("sub/f.txt", "one\nTWO\nthree\n");
        repo.git(&["commit", "-qam", "second"]);
        let second = repo.git(&["rev-parse", "HEAD"]);
        let lines = repo.run(|| blame("sub\\f.txt", None, None)).unwrap();
        assert_eq!(lines.len(), 3);
        assert_eq!(lines[0].oid, first);
        assert_eq!(lines[1].oid, second);
        assert_eq!(lines[1].text, "TWO");
        assert_eq!(lines[2].oid, first);
        assert_eq!(
            lines[1].previous.as_ref().map(|p| p.0.clone()),
            Some(first.clone())
        );
        let before = repo.run(|| blame("sub/f.txt", Some(&first), None)).unwrap();
        assert_eq!(before[1].text, "two");
        let kind = repo.run(|| kind_of("sub/f.txt"));
        assert_eq!(kind, FileKind::Lines(3));
        let hist = repo.run(|| line_history("sub/f.txt", 2, 2)).unwrap();
        assert!(hist.iter().any(|l| l.contains("second")));
        let files = repo.run(list_files).unwrap();
        assert!(files.split('\0').any(|f| f == "sub/f.txt"));
    }
}