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
//! One snapshot of the repository: branch, upstream, changed files, stash count and any
//! operation in progress. Built from `git status --porcelain=v2 -z --branch --show-stash`.

use crate::git::{self, Opts};
use anyhow::{anyhow, Result};
use serde::Serialize;
use std::path::{Path, PathBuf};

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub enum Head {
    Branch {
        name: String,
        oid: String,
    },
    /// A branch with no commits yet.
    Unborn {
        name: String,
    },
    Detached {
        oid: String,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum EntryKind {
    Ordinary,
    Renamed,
    Unmerged,
    Untracked,
    Ignored,
}

/// One changed path. `x`/`y` are the index/worktree status letters ('.' = unchanged,
/// '?' for untracked, '!' for ignored).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Entry {
    pub path: String,
    /// The old path of a rename or copy.
    pub orig_path: Option<String>,
    pub x: char,
    pub y: char,
    pub kind: EntryKind,
}

impl Entry {
    /// Has changes in the index (tracked, non-conflicted entries only).
    pub fn staged(&self) -> bool {
        matches!(self.kind, EntryKind::Ordinary | EntryKind::Renamed) && self.x != '.'
    }

    /// Has worktree changes not yet staged (tracked, non-conflicted entries only).
    pub fn unstaged(&self) -> bool {
        matches!(self.kind, EntryKind::Ordinary | EntryKind::Renamed) && self.y != '.'
    }

    pub fn conflicted(&self) -> bool {
        self.kind == EntryKind::Unmerged
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum InProgress {
    Merge,
    Rebase,
    CherryPick,
    Revert,
    Am,
    Bisect,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct BranchInfo {
    pub head: Head,
    /// e.g. "origin/main"; set even when the upstream branch is gone.
    pub upstream: Option<String>,
    pub ahead: u32,
    pub behind: u32,
    pub stash_count: usize,
    /// An upstream is configured but its remote branch no longer exists.
    pub upstream_gone: bool,
}

#[derive(Debug, Clone, Serialize)]
pub struct RepoState {
    pub branch: BranchInfo,
    pub entries: Vec<Entry>,
    pub op: Option<InProgress>,
    pub git_dir: PathBuf,
    pub workdir: PathBuf,
}

/// Parses `git status --porcelain=v2 -z --branch --show-stash` output. Pure; paths are
/// decoded as lossy UTF-8.
pub fn parse_status_v2(z: &[u8]) -> (BranchInfo, Vec<Entry>) {
    let mut oid = String::new();
    let mut head_name: Option<String> = None;
    let mut detached = false;
    let mut upstream = None;
    let mut ab: Option<(u32, u32)> = None;
    let mut stash_count = 0usize;
    let mut entries = Vec::new();

    let mut records = z.split(|b| *b == 0).filter(|r| !r.is_empty());
    while let Some(record) = records.next() {
        let text = String::from_utf8_lossy(record);
        if let Some(header) = text.strip_prefix("# ") {
            let (key, value) = header.split_once(' ').unwrap_or((header, ""));
            match key {
                "branch.oid" => {
                    oid = if value == "(initial)" {
                        String::new()
                    } else {
                        value.into()
                    }
                }
                "branch.head" if value == "(detached)" => detached = true,
                "branch.head" => head_name = Some(value.into()),
                "branch.upstream" => upstream = Some(value.to_string()),
                "branch.ab" => {
                    let mut parts = value.split_whitespace();
                    let mut number = |sign: char| {
                        parts
                            .next()
                            .and_then(|p| p.strip_prefix(sign))
                            .and_then(|n| n.parse().ok())
                            .unwrap_or(0)
                    };
                    let ahead = number('+');
                    let behind = number('-');
                    ab = Some((ahead, behind));
                }
                "stash" => stash_count = value.trim().parse().unwrap_or(0),
                _ => {}
            }
            continue;
        }
        let kind_char = text.chars().next().unwrap_or(' ');
        // Fields before the path; the path itself may contain spaces, so split a fixed count.
        let (fields, kind) = match kind_char {
            '1' => (8, EntryKind::Ordinary),
            '2' => (9, EntryKind::Renamed),
            'u' => (10, EntryKind::Unmerged),
            '?' => (1, EntryKind::Untracked),
            '!' => (1, EntryKind::Ignored),
            _ => continue,
        };
        let parts: Vec<&str> = text.splitn(fields + 1, ' ').collect();
        let Some(path) = parts.get(fields) else {
            continue;
        };
        let (x, y) = match kind {
            EntryKind::Untracked => ('?', '?'),
            EntryKind::Ignored => ('!', '!'),
            _ => {
                let mut xy = parts.get(1).copied().unwrap_or("..").chars();
                (xy.next().unwrap_or('.'), xy.next().unwrap_or('.'))
            }
        };
        let orig_path = if kind == EntryKind::Renamed {
            records
                .next()
                .map(|r| String::from_utf8_lossy(r).into_owned())
        } else {
            None
        };
        entries.push(Entry {
            path: path.to_string(),
            orig_path,
            x,
            y,
            kind,
        });
    }

    let head = match (detached, head_name) {
        (true, _) | (false, None) => Head::Detached { oid: oid.clone() },
        (false, Some(name)) if oid.is_empty() => Head::Unborn { name },
        (false, Some(name)) => Head::Branch { name, oid },
    };
    let upstream_gone = upstream.is_some() && ab.is_none();
    let (ahead, behind) = ab.unwrap_or((0, 0));
    (
        BranchInfo {
            head,
            upstream,
            ahead,
            behind,
            stash_count,
            upstream_gone,
        },
        entries,
    )
}

/// The operation a repository is in the middle of, from marker files in `git_dir`.
pub fn detect_in_progress(git_dir: &Path) -> Option<InProgress> {
    if git_dir.join("rebase-merge").is_dir() {
        return Some(InProgress::Rebase);
    }
    let apply = git_dir.join("rebase-apply");
    if apply.is_dir() {
        return Some(if apply.join("applying").exists() {
            InProgress::Am
        } else {
            InProgress::Rebase
        });
    }
    let markers = [
        ("MERGE_HEAD", InProgress::Merge),
        ("CHERRY_PICK_HEAD", InProgress::CherryPick),
        ("REVERT_HEAD", InProgress::Revert),
        ("BISECT_LOG", InProgress::Bisect),
    ];
    markers
        .into_iter()
        .find(|(file, _)| git_dir.join(file).exists())
        .map(|(_, op)| op)
}

/// True inside a git working tree (honours `git::with_ctx`).
pub fn in_repo() -> bool {
    git::git_raw(&["rev-parse", "--is-inside-work-tree"], &Opts::default())
        .is_ok_and(|out| out.ok() && out.text() == "true")
}

/// Reads the current repository state.
pub fn load() -> Result<RepoState> {
    let dirs = git::git_ok(
        &["rev-parse", "--absolute-git-dir", "--show-toplevel"],
        &Opts::default(),
    )
    .map_err(|_| anyhow!("Not a git repository"))?;
    let mut lines = dirs.lines();
    let git_dir = PathBuf::from(lines.next().unwrap_or_default());
    let workdir = PathBuf::from(lines.next().unwrap_or_default());
    let out = git::git_raw(
        &["status", "--porcelain=v2", "-z", "--branch", "--show-stash"],
        &Opts::default(),
    )?;
    if !out.ok() {
        return Err(anyhow!("{}", out.stderr.trim()));
    }
    let (branch, entries) = parse_status_v2(&out.stdout);
    Ok(RepoState {
        branch,
        entries,
        op: detect_in_progress(&git_dir),
        git_dir,
        workdir,
    })
}

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

    const OID: &str = "1234567890abcdef1234567890abcdef12345678";

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

    #[test]
    fn parses_fixtures() {
        let ordinary = format!(
            "# branch.oid {OID}\0# branch.head main\0# branch.upstream origin/main\0# branch.ab +2 -1\0\
             1 .M N... 100644 100644 100644 {OID} {OID} src/a file.rs\0"
        );
        let rename = format!(
            "# branch.oid {OID}\0# branch.head dev\0\
             2 R. N... 100644 100644 100644 {OID} {OID} R100 new name.txt\0old.txt\0\
             1 A. N... 000000 100644 100644 {OID} {OID} added.txt\0"
        );
        let unmerged = format!(
            "# branch.oid {OID}\0# branch.head main\0\
             u UU N... 100644 100644 100644 100644 {OID} {OID} {OID} both.txt\0? new.txt\0! target/\0"
        );
        let cases: Vec<(&str, Vec<u8>, BranchInfo, Vec<Entry>)> = vec![
            (
                "ordinary with upstream ahead/behind",
                ordinary.into_bytes(),
                BranchInfo {
                    head: Head::Branch {
                        name: "main".into(),
                        oid: OID.into(),
                    },
                    upstream: Some("origin/main".into()),
                    ahead: 2,
                    behind: 1,
                    stash_count: 0,
                    upstream_gone: false,
                },
                vec![entry("src/a file.rs", '.', 'M', EntryKind::Ordinary)],
            ),
            (
                "rename and no upstream",
                rename.into_bytes(),
                BranchInfo {
                    head: Head::Branch {
                        name: "dev".into(),
                        oid: OID.into(),
                    },
                    upstream: None,
                    ahead: 0,
                    behind: 0,
                    stash_count: 0,
                    upstream_gone: false,
                },
                vec![
                    Entry {
                        orig_path: Some("old.txt".into()),
                        ..entry("new name.txt", 'R', '.', EntryKind::Renamed)
                    },
                    entry("added.txt", 'A', '.', EntryKind::Ordinary),
                ],
            ),
            (
                "unmerged, untracked, ignored",
                unmerged.into_bytes(),
                BranchInfo {
                    head: Head::Branch {
                        name: "main".into(),
                        oid: OID.into(),
                    },
                    upstream: None,
                    ahead: 0,
                    behind: 0,
                    stash_count: 0,
                    upstream_gone: false,
                },
                vec![
                    entry("both.txt", 'U', 'U', EntryKind::Unmerged),
                    entry("new.txt", '?', '?', EntryKind::Untracked),
                    entry("target/", '!', '!', EntryKind::Ignored),
                ],
            ),
            (
                "unborn",
                b"# branch.oid (initial)\0# branch.head main\0".to_vec(),
                BranchInfo {
                    head: Head::Unborn {
                        name: "main".into(),
                    },
                    upstream: None,
                    ahead: 0,
                    behind: 0,
                    stash_count: 0,
                    upstream_gone: false,
                },
                vec![],
            ),
            (
                "detached with stash",
                format!("# branch.oid {OID}\0# branch.head (detached)\0# stash 3\0").into_bytes(),
                BranchInfo {
                    head: Head::Detached { oid: OID.into() },
                    upstream: None,
                    ahead: 0,
                    behind: 0,
                    stash_count: 3,
                    upstream_gone: false,
                },
                vec![],
            ),
            (
                "gone upstream",
                format!(
                    "# branch.oid {OID}\0# branch.head topic\0# branch.upstream origin/topic\0"
                )
                .into_bytes(),
                BranchInfo {
                    head: Head::Branch {
                        name: "topic".into(),
                        oid: OID.into(),
                    },
                    upstream: Some("origin/topic".into()),
                    ahead: 0,
                    behind: 0,
                    stash_count: 0,
                    upstream_gone: true,
                },
                vec![],
            ),
            (
                "non-UTF8 path is lossy",
                b"# branch.oid (initial)\0# branch.head main\0? caf\xe9.txt\0".to_vec(),
                BranchInfo {
                    head: Head::Unborn {
                        name: "main".into(),
                    },
                    upstream: None,
                    ahead: 0,
                    behind: 0,
                    stash_count: 0,
                    upstream_gone: false,
                },
                vec![entry("caf\u{fffd}.txt", '?', '?', EntryKind::Untracked)],
            ),
            (
                "empty input",
                Vec::new(),
                BranchInfo {
                    head: Head::Detached { oid: String::new() },
                    upstream: None,
                    ahead: 0,
                    behind: 0,
                    stash_count: 0,
                    upstream_gone: false,
                },
                vec![],
            ),
        ];
        for (name, input, branch, entries) in cases {
            let (got_branch, got_entries) = parse_status_v2(&input);
            assert_eq!(got_branch, branch, "{name}");
            assert_eq!(got_entries, entries, "{name}");
        }
    }

    #[test]
    fn entry_flags() {
        let both = entry("a", 'M', 'M', EntryKind::Ordinary);
        assert!(both.staged() && both.unstaged() && !both.conflicted());
        let staged = entry("a", 'A', '.', EntryKind::Ordinary);
        assert!(staged.staged() && !staged.unstaged());
        let conflict = entry("a", 'U', 'U', EntryKind::Unmerged);
        assert!(conflict.conflicted() && !conflict.staged() && !conflict.unstaged());
        let new = entry("a", '?', '?', EntryKind::Untracked);
        assert!(!new.staged() && !new.unstaged() && !new.conflicted());
    }

    #[test]
    fn detects_operations() {
        let repo = TempRepo::new(0);
        let dir = repo.path().join(".git");
        assert_eq!(detect_in_progress(&dir), None);
        let checks: [(&str, bool, InProgress); 6] = [
            ("MERGE_HEAD", false, InProgress::Merge),
            ("CHERRY_PICK_HEAD", false, InProgress::CherryPick),
            ("REVERT_HEAD", false, InProgress::Revert),
            ("BISECT_LOG", false, InProgress::Bisect),
            ("rebase-merge", true, InProgress::Rebase),
            ("rebase-apply", true, InProgress::Rebase),
        ];
        for (name, is_dir, op) in checks {
            let path = dir.join(name);
            if is_dir {
                std::fs::create_dir(&path).unwrap();
            } else {
                std::fs::write(&path, "x").unwrap();
            }
            assert_eq!(detect_in_progress(&dir), Some(op), "{name}");
            if is_dir {
                if name == "rebase-apply" {
                    std::fs::write(path.join("applying"), "").unwrap();
                    assert_eq!(detect_in_progress(&dir), Some(InProgress::Am));
                }
                std::fs::remove_dir_all(&path).unwrap();
            } else {
                std::fs::remove_file(&path).unwrap();
            }
        }
    }

    #[test]
    fn loads_a_real_repo() {
        let repo = TempRepo::new(2).with_remote();
        repo.write("f2.txt", "changed\n");
        repo.write("new file.txt", "x\n");
        repo.git(&["stash", "push", "-m", "keep", "--", "f2.txt"]);
        repo.write("f1.txt", "edited\n");
        repo.git(&["add", "f1.txt"]);
        let state = repo.run(load).unwrap();
        assert!(repo.run(in_repo));
        let Head::Branch { name, oid } = &state.branch.head else {
            panic!("{:?}", state.branch.head)
        };
        assert_eq!(name, "main");
        assert_eq!(oid, &repo.git(&["rev-parse", "HEAD"]));
        assert_eq!(state.branch.upstream.as_deref(), Some("origin/main"));
        assert_eq!((state.branch.ahead, state.branch.behind), (0, 0));
        assert_eq!(state.branch.stash_count, 1);
        assert_eq!(state.op, None);
        assert!(state.git_dir.ends_with(".git"));
        let staged: Vec<&str> = state
            .entries
            .iter()
            .filter(|e| e.staged())
            .map(|e| e.path.as_str())
            .collect();
        assert_eq!(staged, ["f1.txt"]);
        assert!(state
            .entries
            .iter()
            .any(|e| e.path == "new file.txt" && e.kind == EntryKind::Untracked));
        let outside = TempRepo::outside();
        assert!(!outside.run(in_repo));
        assert!(outside.run(load).is_err());
    }
}