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
//! Modes of gct and the router that opens them.
//!
//! Every mode is one row of `REGISTRY`. To add a mode: create `src/modes/<name>.rs` with
//! `pub fn run(config: &mut Config) -> anyhow::Result<()>`, add `pub mod <name>;` below and one
//! `ModeInfo` line to `REGISTRY` (its `run` wraps yours with `unit`). It then appears in the hub,
//! in `--mode <name>`, and as a default-mode choice in settings.
//!
//! `start` enters the terminal UI (`screen::Guard`) once and runs a mode; `run_mode` only
//! dispatches (with the repository checks), so the hub and `open` can switch modes inside the
//! same terminal session.

pub mod branch;
pub mod commands;
pub mod compare;
pub mod conflicts;
pub mod files;
pub mod gitcfg;
pub mod guide;
pub mod hub;
pub mod ignore;
pub mod log;
pub mod settings;
pub mod stage;
pub mod start;
pub mod stash;
pub mod status;
pub mod sync;
pub mod tag;
pub mod timetravel;
pub mod undo;

use crate::{input, mascot::Mood, model::Config, repo_state, screen, ui};
use anyhow::Result;
use std::sync::atomic::{AtomicBool, Ordering};

/// Hub sections, in display order.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Group {
    Start,
    Everyday,
    History,
    Fix,
    Release,
    Setup,
}

impl Group {
    pub const ALL: [Group; 6] = [
        Group::Start,
        Group::Everyday,
        Group::History,
        Group::Fix,
        Group::Release,
        Group::Setup,
    ];

    pub fn title(&self) -> &'static str {
        match self {
            Group::Start => "Start",
            Group::Everyday => "Everyday",
            Group::History => "History",
            Group::Fix => "Fix",
            Group::Release => "Release",
            Group::Setup => "Setup",
        }
    }
}

/// Basic modes show in the hub by default; Advanced ones after Tab (or at the Pro level).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Tier {
    Basic,
    Advanced,
}

pub struct ModeInfo {
    /// Lowercase name for `--mode`, the config and settings.
    pub name: &'static str,
    /// Other names `--mode` accepts.
    pub aliases: &'static [&'static str],
    pub title: &'static str,
    pub description: &'static str,
    pub group: Group,
    pub tier: Tier,
    /// The router shows a "Not a git repository" notice instead of running it outside a repo.
    pub needs_repo: bool,
    /// Lines returned are printed after the UI closes (or shown by the hub).
    pub run: fn(&mut Config) -> Result<Vec<String>>,
}

/// Adapts a mode's `run(&mut Config) -> Result<()>` to the registry shape.
fn unit(result: Result<()>) -> Result<Vec<String>> {
    result.map(|()| Vec::new())
}

/// Every mode, in `Mode::names()` order.
/// Set by Stage mode right before it opens the commit flow, so that flow commits only what is already
/// staged instead of running `git add .`. The commit flow reads and clears it.
pub(crate) static STAGED_ONLY: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(false);

pub static REGISTRY: &[ModeInfo] = &[
    ModeInfo {
        name: "commit",
        aliases: &[],
        title: "Commit",
        description: "Dated commits: date, time, branch, message, push",
        group: Group::Everyday,
        tier: Tier::Basic,
        needs_repo: false,
        run: |c| crate::run_commit_tui(c),
    },
    ModeInfo {
        name: "account",
        aliases: &[],
        title: "Accounts",
        description: "Saved GitHub accounts and the active identity",
        group: Group::Setup,
        tier: Tier::Basic,
        needs_repo: false,
        run: |c| unit(crate::run_accounts(c)),
    },
    ModeInfo {
        name: "settings",
        aliases: &[],
        title: "Settings",
        description: "Default mode, experience, safety and theme",
        group: Group::Setup,
        tier: Tier::Basic,
        needs_repo: false,
        run: |c| unit(settings::run(c)),
    },
    ModeInfo {
        name: "hub",
        aliases: &[],
        title: "Hub",
        description: "Launcher for every mode",
        group: Group::Setup,
        tier: Tier::Basic,
        needs_repo: false,
        run: |c| unit(hub::run(c)),
    },
    ModeInfo {
        name: "commands",
        aliases: &[],
        title: "Commands",
        description: "Every git command gct ran in this session",
        group: Group::Setup,
        tier: Tier::Advanced,
        needs_repo: false,
        run: |c| unit(commands::run(c)),
    },
    ModeInfo {
        name: "status",
        aliases: &[],
        title: "Status",
        description: "Where you are: branch, upstream and changes",
        group: Group::Everyday,
        tier: Tier::Basic,
        needs_repo: true,
        run: |c| unit(status::run(c)),
    },
    ModeInfo {
        name: "guide",
        aliases: &[],
        title: "Guide",
        description: "What to do next, explained step by step",
        group: Group::Start,
        tier: Tier::Basic,
        needs_repo: false,
        run: |c| unit(guide::run(c)),
    },
    ModeInfo {
        name: "stage",
        aliases: &[],
        title: "Stage",
        description: "Pick files and hunks for the next commit; view diffs",
        group: Group::Everyday,
        tier: Tier::Basic,
        needs_repo: true,
        run: |c| unit(stage::run(c)),
    },
    ModeInfo {
        name: "branch",
        aliases: &[],
        title: "Branches",
        description: "Create, switch, rename, merge and delete branches",
        group: Group::Everyday,
        tier: Tier::Basic,
        needs_repo: true,
        run: |c| unit(branch::run(c)),
    },
    ModeInfo {
        name: "sync",
        aliases: &[],
        title: "Sync",
        description: "Fetch, pull and push; manage remotes",
        group: Group::Everyday,
        tier: Tier::Basic,
        needs_repo: true,
        run: |c| unit(sync::run(c)),
    },
    ModeInfo {
        name: "stash",
        aliases: &[],
        title: "Stash",
        description: "Put work aside and bring it back later",
        group: Group::Everyday,
        tier: Tier::Advanced,
        needs_repo: true,
        run: |c| unit(stash::run(c)),
    },
    ModeInfo {
        name: "tag",
        aliases: &[],
        title: "Tags",
        description: "Mark releases: list, create, push and delete tags",
        group: Group::Release,
        tier: Tier::Advanced,
        needs_repo: true,
        run: |c| unit(tag::run(c)),
    },
    ModeInfo {
        name: "log",
        aliases: &[],
        title: "Log",
        description: "Browse and search commit history",
        group: Group::History,
        tier: Tier::Basic,
        needs_repo: true,
        run: |c| unit(log::run(c)),
    },
    ModeInfo {
        name: "files",
        aliases: &[],
        title: "Files",
        description: "Browse files and see who changed each line",
        group: Group::History,
        tier: Tier::Advanced,
        needs_repo: true,
        run: |c| unit(files::run(c)),
    },
    ModeInfo {
        name: "compare",
        aliases: &[],
        title: "Compare",
        description: "Compare two branches or commits",
        group: Group::History,
        tier: Tier::Advanced,
        needs_repo: true,
        run: |c| unit(compare::run(c)),
    },
    ModeInfo {
        name: "undo",
        aliases: &["rescue"],
        title: "Undo",
        description: "Undo recent actions and recover lost work",
        group: Group::Fix,
        tier: Tier::Basic,
        needs_repo: true,
        run: |c| unit(undo::run(c)),
    },
    ModeInfo {
        name: "conflicts",
        aliases: &["resolve"],
        title: "Conflicts",
        description: "Resolve merge conflicts file by file",
        group: Group::Fix,
        tier: Tier::Basic,
        needs_repo: true,
        run: |c| unit(conflicts::run(c)),
    },
    ModeInfo {
        name: "ignore",
        aliases: &[],
        title: "Ignore",
        description: "Keep files out of git with .gitignore",
        group: Group::Setup,
        tier: Tier::Advanced,
        needs_repo: true,
        run: |c| unit(ignore::run(c)),
    },
    ModeInfo {
        name: "config",
        aliases: &[],
        title: "Git config",
        description: "Your name, email and common git settings",
        group: Group::Setup,
        tier: Tier::Advanced,
        needs_repo: true,
        run: |c| unit(gitcfg::run(c)),
    },
    ModeInfo {
        name: "timetravel",
        aliases: &[],
        title: "Time travel",
        description: "Change the dates of existing commits (no rebase)",
        group: Group::Fix,
        tier: Tier::Advanced,
        needs_repo: true,
        run: |c| unit(timetravel::run(c)),
    },
    ModeInfo {
        name: "start",
        aliases: &[],
        title: "Start",
        description: "Create a new repository or clone one",
        group: Group::Start,
        tier: Tier::Basic,
        needs_repo: false,
        run: |c| unit(start::run(c)),
    },
];

/// A registered mode. Equality is by name.
#[derive(Clone, Copy)]
pub struct Mode(pub &'static ModeInfo);

impl PartialEq for Mode {
    fn eq(&self, other: &Self) -> bool {
        self.0.name == other.0.name
    }
}

impl Eq for Mode {}

impl std::fmt::Debug for Mode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Mode({})", self.0.name)
    }
}

impl Mode {
    /// Name or alias, case-insensitive, surrounding whitespace ignored. None for unknown names.
    pub fn parse(value: &str) -> Option<Mode> {
        let value = value.trim();
        REGISTRY
            .iter()
            .find(|info| {
                info.name.eq_ignore_ascii_case(value)
                    || info
                        .aliases
                        .iter()
                        .any(|alias| alias.eq_ignore_ascii_case(value))
            })
            .map(Mode)
    }

    /// The configured default mode; unknown or empty names fall back to commit.
    pub fn from_config(value: &str) -> Mode {
        Mode::parse(value).unwrap_or(Mode(&REGISTRY[0]))
    }

    /// "commit, account, ..." (names only, registry order) for error messages.
    pub fn names() -> String {
        REGISTRY
            .iter()
            .map(|info| info.name)
            .collect::<Vec<_>>()
            .join(", ")
    }

    pub fn all() -> impl Iterator<Item = Mode> {
        REGISTRY.iter().map(Mode)
    }

    pub fn name(&self) -> &'static str {
        self.0.name
    }

    pub fn title(&self) -> &'static str {
        self.0.title
    }

    pub fn description(&self) -> &'static str {
        self.0.description
    }

    pub fn info(&self) -> &'static ModeInfo {
        self.0
    }
}

/// Enters the terminal UI once and runs `mode`. Lines returned are printed after the UI closes.
///
/// When plain `gct` opens a configured default mode that needs a repository outside one, it
/// behaves like plain `gct` with the commit default ("Not a git repository", exit 1) instead of
/// showing a notice and exiting 0. An explicit `--mode`/mode flag keeps the notice.
pub fn start(mode: Mode, config: &mut Config) -> Result<Vec<String>> {
    let explicit = explicit_mode_flag(std::env::args().skip(1));
    let mode = if !explicit && mode.info().needs_repo && !repo_state::in_repo() {
        Mode(&REGISTRY[0])
    } else {
        mode
    };
    let _terminal = screen::Guard::enter()?;
    run_mode(mode, config)
}

/// True when the command line names a mode (`--mode x`, `--mode=x` or a mode shortcut flag).
fn explicit_mode_flag(args: impl Iterator<Item = String>) -> bool {
    const FLAGS: [&str; 12] = [
        "--mode",
        "--hub",
        "--settings",
        "--account",
        "--commit",
        "--stage",
        "--status",
        "--sync",
        "--log",
        "--stash",
        "--undo",
        "--tag",
    ];
    args.take_while(|arg| arg != "--")
        .any(|arg| FLAGS.contains(&arg.as_str()) || arg.starts_with("--mode="))
}

thread_local! {
    /// Names of the modes currently running on this thread, outermost first.
    static OPEN_MODES: std::cell::RefCell<Vec<&'static str>> = const { std::cell::RefCell::new(Vec::new()) };
}

/// Keeps `name` on the open-mode stack until dropped (also on errors and panics).
struct OpenGuard;

impl OpenGuard {
    fn push(name: &'static str) -> OpenGuard {
        OPEN_MODES.with(|stack| stack.borrow_mut().push(name));
        OpenGuard
    }
}

impl Drop for OpenGuard {
    fn drop(&mut self) {
        OPEN_MODES.with(|stack| {
            stack.borrow_mut().pop();
        });
    }
}

/// True when `name` is already running further up (a jump would loop, e.g. conflicts -> sync ->
/// conflicts).
fn is_open(stack: &[&str], name: &str) -> bool {
    stack.contains(&name)
}

fn open_modes() -> Vec<&'static str> {
    OPEN_MODES.with(|stack| stack.borrow().clone())
}

/// Picks the folder a repository mode runs in: git's `--show-toplevel` output, or None when git
/// failed or printed nothing.
fn repo_root(ok: bool, toplevel: &str) -> Option<std::path::PathBuf> {
    let toplevel = toplevel.trim_end_matches(['\r', '\n']);
    (ok && !toplevel.trim().is_empty()).then(|| std::path::PathBuf::from(toplevel))
}

/// Switches the working folder to the repository root while a repository mode runs (its paths
/// are root-relative), and switches back afterwards so the commit flow keeps its folder.
struct RootDir(Option<std::path::PathBuf>);

impl RootDir {
    fn enter() -> RootDir {
        let out = crate::git::git_raw(&["rev-parse", "--show-toplevel"], &Default::default());
        let root = out
            .ok()
            .and_then(|out| repo_root(out.ok(), &String::from_utf8_lossy(&out.stdout)));
        let (Some(root), Ok(previous)) = (root, std::env::current_dir()) else {
            return RootDir(None);
        };
        if previous == root || std::env::set_current_dir(&root).is_err() {
            return RootDir(None);
        }
        RootDir(Some(previous))
    }
}

impl Drop for RootDir {
    fn drop(&mut self) {
        if let Some(previous) = self.0.take() {
            let _ = std::env::set_current_dir(previous);
        }
    }
}

/// Oldest git the git modes support (--force-if-includes, porcelain v2 details).
const MIN_GIT: (u32, u32, u32) = (2, 30, 0);
static VERSION_CHECKED: AtomicBool = AtomicBool::new(false);

/// Runs one mode inside an already active terminal UI and returns lines to print on exit.
/// Modes that need a repository get a notice instead when run outside one, and the git version
/// is checked once per session.
pub fn run_mode(mode: Mode, config: &mut Config) -> Result<Vec<String>> {
    screen::set_mood(Mood::Idle);
    let _open = OpenGuard::push(mode.name());
    if !mode.info().needs_repo {
        return (mode.info().run)(config);
    }
    if !repo_state::in_repo() {
        not_a_repo(mode)?;
        return Ok(Vec::new());
    }
    if !VERSION_CHECKED.swap(true, Ordering::Relaxed) {
        if let Some(problem) = version_problem(crate::git::version().ok()) {
            ui::notice("Old git version", &[problem])?;
        }
    }
    let _root = RootDir::enter();
    (mode.info().run)(config)
}

/// The neutral notice shown when `mode` is opened outside a repository.
pub(crate) fn not_a_repo(mode: Mode) -> Result<()> {
    ui::notice(
        "Not a git repository",
        &[
            format!("{} works inside a git repository.", mode.title()),
            String::new(),
            "cd into a project folder, or".into(),
            "Open Start mode (gct --mode start) to create or clone one".into(),
        ],
    )
}

/// A message when `version` is older than `MIN_GIT` or unknown.
fn version_problem(version: Option<(u32, u32, u32)>) -> Option<String> {
    let (major, minor, patch) = MIN_GIT;
    match version {
        Some(found) if found >= MIN_GIT => None,
        Some((a, b, c)) => Some(format!(
            "gct needs git {major}.{minor}.{patch} or newer for some actions; you have {a}.{b}.{c}."
        )),
        None => Some("Could not read the git version; some actions may fail.".into()),
    }
}

/// Opens another mode by name or alias from inside a mode (a cross-mode jump), then returns.
/// Returned lines and errors show as notices like in the hub; a cancel just returns.
/// A mode that is already open further up is not opened again (no endless jump chains); a
/// notice says to go back to it instead.
pub fn open(name: &str, cfg: &mut Config) -> Result<()> {
    let Some(mode) = Mode::parse(name) else {
        return ui::notice(
            "Unknown mode",
            &[format!(
                "'{}' is not a mode. Valid modes: {}",
                name.trim(),
                Mode::names()
            )],
        );
    };
    if is_open(&open_modes(), mode.name()) {
        return ui::notice(
            mode.title(),
            &[format!(
                "{} is already open. Press Esc to go back to it.",
                mode.title()
            )],
        );
    }
    let result = run_mode(mode, cfg);
    show_result(mode, result)
}

/// Shows what a mode returned: lines as a notice, failures as a red notice. A cancel (Esc in a
/// menu or Ctrl+C) inside a nested mode is silent and goes back one level; Ctrl+C at the top
/// level (the hub, or a mode opened directly) still ends gct through `main`. A crashed
/// background job stays fatal.
pub(crate) fn show_result(mode: Mode, result: Result<Vec<String>>) -> Result<()> {
    match result {
        Ok(lines) if lines.is_empty() => Ok(()),
        Ok(lines) => ui::notice(mode.title(), &lines),
        Err(error) if input::is_cancel(&error) => Ok(()),
        Err(error) if error.is::<ui::JobPanic>() => Err(error),
        Err(error) => {
            screen::set_mood(Mood::Error);
            ui::notice(
                &format!("{} failed", mode.title()),
                &[screen::danger(format!("{error:#}"))],
            )
        }
    }
}

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

    fn mode(name: &str) -> Mode {
        Mode::parse(name).unwrap()
    }

    #[test]
    fn parse_names() {
        assert_eq!(Mode::parse("stage"), Some(mode("stage")));
        assert_eq!(Mode::parse("  LoG \n").map(|m| m.name()), Some("log"));
        assert_eq!(Mode::parse("Account").map(|m| m.name()), Some("account"));
        assert_eq!(Mode::parse("rescue").map(|m| m.name()), Some("undo"));
        assert_eq!(
            Mode::parse(" RESOLVE ").map(|m| m.name()),
            Some("conflicts")
        );
        assert_eq!(Mode::parse("config").map(|m| m.title()), Some("Git config"));
        assert_eq!(Mode::parse("nonsense"), None);
        assert_eq!(Mode::parse(""), None);
        for mode in Mode::all() {
            assert_eq!(Mode::parse(mode.name()), Some(mode));
            assert_eq!(Mode::parse(&mode.name().to_uppercase()), Some(mode));
            assert!(!mode.title().is_empty() && !mode.description().is_empty());
        }
    }

    #[test]
    fn names_are_unique() {
        let mut names: Vec<&str> = REGISTRY
            .iter()
            .flat_map(|info| std::iter::once(info.name).chain(info.aliases.iter().copied()))
            .collect();
        let total = names.len();
        names.sort_unstable();
        names.dedup();
        assert_eq!(names.len(), total);
        assert!(Mode::names().starts_with("commit, account, settings, hub"));
        assert_eq!(
            Mode::names(),
            "commit, account, settings, hub, commands, status, guide, stage, branch, sync, stash, \
             tag, log, files, compare, undo, conflicts, ignore, config, timetravel, start"
        );
        assert!(!Mode::names().contains("rescue"));
    }

    #[test]
    fn default_falls_back_to_commit() {
        assert_eq!(Mode::from_config(""), mode("commit"));
        assert_eq!(Mode::from_config("bogus"), mode("commit"));
        assert_eq!(Mode::from_config("Hub"), mode("hub"));
        assert_eq!(
            Mode::from_config(&Config::default().default_mode),
            mode("commit")
        );
    }

    #[test]
    fn registry_groups_tiers_and_repo_needs() {
        let check = |names: &[&str], f: &dyn Fn(&ModeInfo) -> bool| {
            for name in names {
                assert!(f(mode(name).info()), "{name}");
            }
        };
        check(&["start", "guide"], &|i| i.group == Group::Start);
        check(
            &["commit", "status", "stage", "branch", "sync", "stash"],
            &|i| i.group == Group::Everyday,
        );
        check(&["log", "files", "compare"], &|i| i.group == Group::History);
        check(&["undo", "conflicts", "timetravel"], &|i| {
            i.group == Group::Fix
        });
        check(&["tag"], &|i| i.group == Group::Release);
        check(
            &["account", "settings", "hub", "commands", "ignore", "config"],
            &|i| i.group == Group::Setup,
        );
        let basic = [
            "commit",
            "status",
            "guide",
            "start",
            "stage",
            "branch",
            "sync",
            "log",
            "undo",
            "conflicts",
            "account",
            "settings",
            "hub",
        ];
        for m in Mode::all() {
            let expect = if basic.contains(&m.name()) {
                Tier::Basic
            } else {
                Tier::Advanced
            };
            assert_eq!(m.info().tier, expect, "{}", m.name());
        }
        let no_repo = [
            "commit", "account", "settings", "hub", "start", "commands", "guide",
        ];
        for m in Mode::all() {
            assert_eq!(
                m.info().needs_repo,
                !no_repo.contains(&m.name()),
                "{}",
                m.name()
            );
        }
        assert_eq!(REGISTRY.len(), 21);
    }

    #[test]
    fn version_gate() {
        assert_eq!(version_problem(Some((2, 30, 0))), None);
        assert_eq!(version_problem(Some((3, 0, 0))), None);
        assert!(version_problem(Some((2, 29, 9)))
            .unwrap()
            .contains("2.29.9"));
        assert!(version_problem(None).is_some());
    }

    #[test]
    fn repo_root_choice() {
        assert_eq!(
            repo_root(true, "C:/work/project\n"),
            Some(std::path::PathBuf::from("C:/work/project"))
        );
        assert_eq!(
            repo_root(true, "/home/u/my repo\r\n"),
            Some("/home/u/my repo".into())
        );
        assert_eq!(repo_root(true, "/srv/ünï"), Some("/srv/ünï".into()));
        assert_eq!(repo_root(false, "/somewhere"), None);
        assert_eq!(repo_root(true, ""), None);
        assert_eq!(repo_root(true, "  \n"), None);
    }

    #[test]
    fn root_dir_of_a_subfolder_is_the_toplevel() {
        // The pure choice above, fed by the same git call RootDir makes, from a subfolder.
        let repo = crate::testutil::TempRepo::new(1);
        repo.write("sub/deeper/x.txt", "x");
        let top = crate::git::with_ctx(&repo.path().join("sub/deeper"), repo.env(), || {
            let out = crate::git::git_raw(&["rev-parse", "--show-toplevel"], &Default::default())
                .unwrap();
            repo_root(out.ok(), &String::from_utf8_lossy(&out.stdout))
        });
        let top = std::fs::canonicalize(top.unwrap()).unwrap();
        assert_eq!(top, std::fs::canonicalize(repo.path()).unwrap());
    }

    #[test]
    fn open_stack_blocks_loops_and_pops_on_exit() {
        assert!(open_modes().is_empty());
        {
            let _hub = OpenGuard::push("hub");
            let _conflicts = OpenGuard::push("conflicts");
            {
                let _sync = OpenGuard::push("sync");
                assert_eq!(open_modes(), ["hub", "conflicts", "sync"]);
                assert!(is_open(&open_modes(), "conflicts"));
                assert!(is_open(&open_modes(), "sync"));
                assert!(!is_open(&open_modes(), "log"));
            }
            assert!(!is_open(&open_modes(), "sync"), "popped when sync returned");
            let result = std::panic::catch_unwind(|| {
                let _log = OpenGuard::push("log");
                panic!("mode crashed");
            });
            assert!(result.is_err());
            assert_eq!(open_modes(), ["hub", "conflicts"], "popped on panic too");
        }
        assert!(open_modes().is_empty());
        assert!(!is_open(&[], "hub"));
    }

    #[test]
    fn explicit_mode_flags() {
        let args = |list: &[&str]| list.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        assert!(!explicit_mode_flag(args(&[]).into_iter()));
        assert!(explicit_mode_flag(args(&["--mode", "stage"]).into_iter()));
        assert!(explicit_mode_flag(args(&["--mode=log"]).into_iter()));
        assert!(explicit_mode_flag(args(&["--stage"]).into_iter()));
        assert!(explicit_mode_flag(args(&["--hub"]).into_iter()));
        assert!(!explicit_mode_flag(args(&["--", "--stage"]).into_iter()));
        assert!(!explicit_mode_flag(args(&["--modes"]).into_iter()));
    }
}