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
//! Stash mode: save, list, show, apply, pop, drop (with a recoverable backup ref), clear and
//! branch-from-stash. Stashes are always addressed by ref and the list is reloaded after every
//! action because indices shift.

use crate::git::{self, Opts};
use crate::model::Config;
use crate::policy::{self, Op, Verdict};
use crate::{repo_state, safety, screen, ui};
use anyhow::{bail, Result};

const LIST_FORMAT: &str = "--format=%gd%x1f%cr%x1f%gs";

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StashEntry {
    pub refname: String,
    pub age: String,
    pub message: String,
}

/// Parses `git stash list --format=%gd%x1f%cr%x1f%gs`. Malformed lines are skipped.
pub fn parse_stash_list(text: &str) -> Vec<StashEntry> {
    text.lines()
        .filter_map(|line| {
            let mut parts = line.trim_end_matches('\r').splitn(3, '\u{1f}');
            let refname = parts.next()?.trim();
            let age = parts.next()?.trim();
            let message = parts.next()?.trim();
            if !refname.starts_with("stash@{") {
                return None;
            }
            Some(StashEntry {
                refname: refname.to_string(),
                age: age.to_string(),
                message: message.to_string(),
            })
        })
        .collect()
}

pub fn list() -> Result<Vec<StashEntry>> {
    Ok(parse_stash_list(&git::git_ok(
        &["stash", "list", LIST_FORMAT],
        &Opts::default(),
    )?))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SaveMode {
    IncludeUntracked,
    TrackedOnly,
    KeepStaged,
}

/// Arguments for `git stash push`.
pub fn save_args(message: &str, mode: SaveMode) -> Vec<String> {
    let mut args = vec!["stash".to_string(), "push".to_string()];
    match mode {
        SaveMode::IncludeUntracked => args.push("-u".into()),
        SaveMode::TrackedOnly => {}
        SaveMode::KeepStaged => args.push("-k".into()),
    }
    if !message.trim().is_empty() {
        args.push("-m".into());
        args.push(message.trim().to_string());
    }
    args
}

/// Returns `Ok(None)` when there was nothing to stash.
pub fn save(message: &str, mode: SaveMode) -> Result<Option<String>> {
    let args = save_args(message, mode);
    let refs: Vec<&str> = args.iter().map(String::as_str).collect();
    let out = git::git_raw(&refs, &Opts::default())?;
    let text = format!("{}\n{}", out.text(), out.stderr.trim());
    if text.contains("No local changes to save") {
        return Ok(None);
    }
    if !out.ok() {
        bail!("{}", out.stderr.trim());
    }
    Ok(Some(out.text()))
}

/// Patch for a stash, including untracked files when this git supports it.
pub fn show_lines(refname: &str) -> Result<Vec<String>> {
    let new_enough = git::version().map(|v| v >= (2, 32, 0)).unwrap_or(false);
    if new_enough {
        let out = git::git_raw(
            &["stash", "show", "-p", "--include-untracked", refname],
            &Opts::default(),
        )?;
        if out.ok() {
            return Ok(out.text().lines().map(str::to_string).collect());
        }
    }
    let text = git::git_ok(&["stash", "show", "-p", refname], &Opts::default())?;
    Ok(text.lines().map(str::to_string).collect())
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApplyOutcome {
    pub ok: bool,
    pub conflicts: bool,
    pub output: String,
}

/// `git stash apply|pop <ref>`; checks the repo for conflicts afterwards.
pub fn apply(refname: &str, pop: bool) -> Result<ApplyOutcome> {
    let verb = if pop { "pop" } else { "apply" };
    let out = git::git_raw(&["stash", verb, refname], &Opts::default())?;
    let conflicts = repo_state::load()
        .map(|s| s.entries.iter().any(|e| e.conflicted()))
        .unwrap_or(false);
    let output = format!("{}\n{}", out.text(), out.stderr.trim())
        .trim()
        .to_string();
    Ok(ApplyOutcome {
        ok: out.ok() && !conflicts,
        conflicts,
        output,
    })
}

/// Backs up the stash commit under refs/gct/backup, then drops it. Returns the backup ref.
pub fn drop_with_backup(refname: &str) -> Result<String> {
    let oid = git::git_ok(&["rev-parse", "--verify", refname], &Opts::default())?;
    let backup = safety::backup("stash-drop", &oid)?;
    git::git_ok(&["stash", "drop", refname], &Opts::default())?;
    Ok(backup)
}

/// Backs up every stash, then clears them all. Returns the backup refs.
pub fn clear_with_backups() -> Result<Vec<String>> {
    let mut backups = Vec::new();
    for entry in list()? {
        let oid = git::git_ok(&["rev-parse", "--verify", &entry.refname], &Opts::default())?;
        backups.push(safety::backup("stash-clear", &oid)?);
    }
    git::git_ok(&["stash", "clear"], &Opts::default())?;
    Ok(backups)
}

/// Rejects empty names, leading '-' and anything git refuses as a branch name.
pub fn valid_branch_name(name: &str) -> bool {
    let name = name.trim();
    if name.is_empty() || name.starts_with('-') {
        return false;
    }
    git::git_raw(&["check-ref-format", "--branch", name], &Opts::default())
        .map(|o| o.ok())
        .unwrap_or(false)
}

pub fn branch_from(name: &str, refname: &str) -> Result<String> {
    if !valid_branch_name(name) {
        bail!("'{name}' is not a valid branch name");
    }
    git::git_ok(&["stash", "branch", name.trim(), refname], &Opts::default())
}

fn row(entry: &StashEntry) -> String {
    format!(
        "{}  {}  {}",
        entry.refname,
        screen::muted(&entry.age),
        entry.message
    )
}

const KEYS: &[ui::Key] = &[
    ui::Key {
        key: 'n',
        label: "new",
    },
    ui::Key {
        key: 'a',
        label: "apply",
    },
    ui::Key {
        key: 'p',
        label: "pop",
    },
    ui::Key {
        key: 'd',
        label: "drop",
    },
    ui::Key {
        key: 'b',
        label: "branch",
    },
    ui::Key {
        key: 'c',
        label: "clear all",
    },
    ui::Key {
        key: 'r',
        label: "refresh",
    },
];

/// Entry point called by the mode router (`modes::run_mode`) inside an active terminal UI.
pub fn run(config: &mut Config) -> Result<()> {
    let mut index = 0usize;
    loop {
        let stashes = ui::git_job("Loading stashes...", list)?;
        index = index.min(stashes.len().saturating_sub(1));
        let mut header = vec![format!("{} stash(es)", stashes.len())];
        if stashes.is_empty() {
            header.push("No stashes yet. Press n to save your current changes".to_string());
            header.extend(ui::explain(
                config,
                &["A stash is a shelf for unfinished work: it saves your changes and gives you a clean folder."],
            ));
        }
        let rows: Vec<String> = stashes.iter().map(row).collect();
        match ui::action_list("Stash", &header, &rows, KEYS, &mut index)? {
            ui::Choice::Back => return Ok(()),
            ui::Choice::Action('n', _) => save_flow(config)?,
            ui::Choice::Action('r', _) => {}
            ui::Choice::Action('c', _) => clear_flow(config, &stashes)?,
            ui::Choice::Action(key, i) => {
                if let Some(entry) = stashes.get(i) {
                    act(config, key, entry)?;
                }
            }
            ui::Choice::Open(i) => {
                let Some(entry) = stashes.get(i) else {
                    continue;
                };
                let options = [
                    "Show changes",
                    "Apply (keep the stash)",
                    "Pop (apply and remove)",
                    "Drop (delete, with backup)",
                    "New branch from it",
                ];
                let Some(pick) = ui::choose(
                    &entry.refname,
                    std::slice::from_ref(&entry.message),
                    &options,
                )?
                else {
                    continue;
                };
                act(config, ['s', 'a', 'p', 'd', 'b'][pick], entry)?;
            }
        }
    }
}

fn act(cfg: &mut Config, key: char, entry: &StashEntry) -> Result<()> {
    match key {
        's' => {
            let lines = ui::git_job("Reading stash...", || show_lines(&entry.refname))?;
            let lines = if lines.is_empty() {
                vec!["(no changes)".to_string()]
            } else {
                lines
            };
            ui::diff_view(
                &format!("{}  {}", entry.refname, entry.message),
                &lines,
                &[],
            )?;
        }
        'a' | 'p' => {
            let pop = key == 'p';
            let outcome = ui::git_job("Applying stash...", || apply(&entry.refname, pop))?;
            let cmd = format!(
                "git stash {} {}",
                if pop { "pop" } else { "apply" },
                entry.refname
            );
            let mut lines = vec![format!("$ {cmd}")];
            if outcome.conflicts {
                lines.push("Conflicts found. The stash was KEPT so nothing is lost.".to_string());
            } else if !outcome.ok {
                lines.push(format!("Failed. The stash was kept. {}", outcome.output));
            } else if pop {
                lines.push("Applied and removed the stash.".to_string());
            } else {
                lines.push("Applied. The stash is still saved.".to_string());
            }
            lines.extend(ui::explain(
                cfg,
                &["Apply copies the saved changes back; pop does the same and then deletes the stash."],
            ));
            ui::notice("Stash", &lines)?;
            if outcome.conflicts {
                crate::modes::open("conflicts", cfg)?;
            }
        }
        'd' => {
            let command = format!("git stash drop {}", entry.refname);
            let verdict = policy::check(cfg, &Op::DropStash);
            if ui::gate(cfg, &verdict, &format!("Drop {}?", entry.refname), &command)? {
                let backup = ui::git_job("Dropping stash...", || drop_with_backup(&entry.refname))?;
                let lines = vec![
                    format!("$ {command}"),
                    format!("Backup ref: {backup}"),
                    format!("Recover with: git stash apply $(git rev-parse {backup})"),
                ];
                ui::notice("Stash dropped", &lines)?;
            }
        }
        'b' => {
            let Some(name) = ui::ask("New branch name", "")? else {
                return Ok(());
            };
            if !valid_branch_name(&name) {
                return ui::notice(
                    "Stash",
                    &[format!("'{}' is not a valid branch name.", name.trim())],
                );
            }
            let out = ui::git_job("Creating branch...", || branch_from(&name, &entry.refname))?;
            ui::notice(
                "Stash",
                &[
                    format!("$ git stash branch {} {}", name.trim(), entry.refname),
                    out,
                ],
            )?;
        }
        _ => {}
    }
    Ok(())
}

fn save_flow(cfg: &Config) -> Result<()> {
    let Some(message) = ui::ask("Stash message (optional)", "")? else {
        return Ok(());
    };
    let options = [
        "Include untracked files (-u)",
        "Tracked changes only",
        "Keep staged changes in place (-k)",
    ];
    let Some(pick) = ui::choose("What to stash", &[], &options)? else {
        return Ok(());
    };
    let mode = [
        SaveMode::IncludeUntracked,
        SaveMode::TrackedOnly,
        SaveMode::KeepStaged,
    ][pick];
    let command = format!("git {}", save_args(&message, mode).join(" "));
    match ui::git_job("Saving stash...", || save(&message, mode))? {
        Some(out) => {
            let mut lines = vec![format!("$ {command}"), out];
            lines.extend(ui::explain(
                cfg,
                &["Your changes are saved on the stash shelf and removed from your folder."],
            ));
            ui::notice("Stash saved", &lines)
        }
        None => ui::notice(
            "Stash",
            &["Nothing to stash: no local changes.".to_string()],
        ),
    }
}

fn clear_flow(cfg: &Config, stashes: &[StashEntry]) -> Result<()> {
    if stashes.is_empty() {
        return ui::notice("Stash", &["There are no stashes to clear.".to_string()]);
    }
    if let Verdict::Deny(reason) = policy::check(cfg, &Op::DropStash) {
        return ui::notice("Stash", &[reason]);
    }
    let what = format!(
        "Delete ALL {} stashes? Each gets a backup ref first.",
        stashes.len()
    );
    if ui::confirm_typed(&what, "git stash clear", "clear")? {
        let backups = ui::git_job("Clearing stashes...", clear_with_backups)?;
        let mut lines = vec!["$ git stash clear".to_string()];
        lines.extend(backups.iter().map(|b| format!("Backup ref: {b}")));
        ui::notice("Stashes cleared", &lines)?;
    }
    Ok(())
}

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

    #[test]
    fn parse_table() {
        assert!(parse_stash_list("").is_empty());
        let t = "stash@{0}\u{1f}2 minutes ago\u{1f}WIP on main: abc1234 commit 3\r\nstash@{1}\u{1f}3 days ago\u{1f}On main: my msg\nstash@{2}\u{1f}now\u{1f}On dev: café ✓ 日本\ngarbage";
        let v = parse_stash_list(t);
        assert_eq!(v.len(), 3);
        assert_eq!(v[0].message, "WIP on main: abc1234 commit 3");
        assert_eq!(v[1].refname, "stash@{1}");
        assert_eq!(v[1].message, "On main: my msg");
        assert_eq!(v[2].message, "On dev: café ✓ 日本");
    }

    #[test]
    fn save_args_table() {
        assert_eq!(save_args("", SaveMode::TrackedOnly), ["stash", "push"]);
        assert_eq!(
            save_args(" hi ", SaveMode::IncludeUntracked),
            ["stash", "push", "-u", "-m", "hi"]
        );
        assert_eq!(
            save_args("x", SaveMode::KeepStaged),
            ["stash", "push", "-k", "-m", "x"]
        );
    }

    #[test]
    fn branch_name_validation() {
        let repo = TempRepo::new(1);
        repo.run(|| {
            assert!(valid_branch_name("feature/x"));
            assert!(!valid_branch_name("-bad"));
            assert!(!valid_branch_name(""));
            assert!(!valid_branch_name("a b"));
        });
    }

    #[test]
    fn save_with_and_without_untracked() {
        let repo = TempRepo::new(2);
        repo.write("f1.txt", "changed\n");
        repo.write("new.txt", "u\n");
        repo.run(|| {
            assert!(save("tracked", SaveMode::TrackedOnly).unwrap().is_some());
            let l = list().unwrap();
            assert_eq!(l.len(), 1);
            assert_eq!(l[0].message, "On main: tracked");
            // only the untracked file remains; stashing without -u finds nothing
            assert!(save("", SaveMode::TrackedOnly).unwrap().is_none());
            assert!(save("all", SaveMode::IncludeUntracked).unwrap().is_some());
            assert_eq!(list().unwrap().len(), 2);
        });
        assert!(!repo.path().join("new.txt").exists());
    }

    #[test]
    fn apply_keeps_pop_removes() {
        let repo = TempRepo::new(1);
        repo.write("f1.txt", "changed\n");
        repo.run(|| {
            save("m", SaveMode::TrackedOnly).unwrap();
            let r = apply("stash@{0}", false).unwrap();
            assert!(r.ok && !r.conflicts);
            assert_eq!(list().unwrap().len(), 1);
            git::git_ok(&["checkout", "--", "f1.txt"], &Opts::default()).unwrap();
            let r = apply("stash@{0}", true).unwrap();
            assert!(r.ok);
            assert!(list().unwrap().is_empty());
        });
    }

    #[test]
    fn drop_backup_is_recoverable() {
        let repo = TempRepo::new(1);
        repo.write("f1.txt", "precious\n");
        repo.run(|| {
            save("m", SaveMode::TrackedOnly).unwrap();
            let backup = drop_with_backup("stash@{0}").unwrap();
            assert!(backup.starts_with("refs/gct/backup/"));
            assert!(list().unwrap().is_empty());
            let oid = git::git_ok(&["rev-parse", &backup], &Opts::default()).unwrap();
            git::git_ok(&["stash", "apply", &oid], &Opts::default()).unwrap();
        });
        let text = std::fs::read_to_string(repo.path().join("f1.txt")).unwrap();
        assert_eq!(text.trim(), "precious");
    }

    #[test]
    fn conflicting_pop_keeps_stash() {
        let repo = TempRepo::new(1);
        repo.write("f1.txt", "stashed\n");
        repo.run(|| {
            save("m", SaveMode::TrackedOnly).unwrap();
        });
        repo.write("f1.txt", "other\n");
        repo.git(&["commit", "-qam", "other"]);
        repo.run(|| {
            let r = apply("stash@{0}", true).unwrap();
            assert!(!r.ok);
            assert!(r.conflicts);
            assert_eq!(list().unwrap().len(), 1);
        });
    }

    #[test]
    fn branch_from_stash_has_changes() {
        let repo = TempRepo::new(1);
        repo.write("f1.txt", "wip\n");
        repo.run(|| {
            save("m", SaveMode::TrackedOnly).unwrap();
            branch_from("topic", "stash@{0}").unwrap();
            assert!(list().unwrap().is_empty());
            let head =
                git::git_ok(&["rev-parse", "--abbrev-ref", "HEAD"], &Opts::default()).unwrap();
            assert_eq!(head, "topic");
            assert!(branch_from("-x", "stash@{0}").is_err());
        });
        let text = std::fs::read_to_string(repo.path().join("f1.txt")).unwrap();
        assert_eq!(text.trim(), "wip");
    }

    #[test]
    fn clear_makes_backups() {
        let repo = TempRepo::new(1);
        repo.run(|| {
            assert!(clear_with_backups().unwrap().is_empty());
        });
        repo.write("f1.txt", "a\n");
        repo.run(|| {
            save("1", SaveMode::TrackedOnly).unwrap();
        });
        repo.write("f1.txt", "b\n");
        repo.run(|| {
            save("2", SaveMode::TrackedOnly).unwrap();
            assert_eq!(clear_with_backups().unwrap().len(), 2);
            assert!(list().unwrap().is_empty());
        });
    }
}