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
//! Git config mode: identity, default branch, pull strategy, line endings, aliases and a
//! read-only look at hooks. Global writes always show the exact command and ask first.

use crate::{git, model::Config, screen, ui};
use anyhow::{bail, Result};
use std::path::{Path, PathBuf};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Scope {
    Local,
    Global,
}

impl Scope {
    fn flag(self) -> &'static str {
        match self {
            Scope::Local => "--local",
            Scope::Global => "--global",
        }
    }
}

/// Where a config value comes from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Origin {
    Local,
    Global,
    Other,
}

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

/// Parses the first line of `git config --show-origin --get <key>`: `file:<path>\t<value>`.
pub fn parse_show_origin(text: &str) -> Option<(String, String)> {
    let line = text
        .lines()
        .map(|l| l.trim_end_matches('\r'))
        .find(|l| !l.trim().is_empty())?;
    let (origin, value) = line.split_once('\t')?;
    if origin.is_empty() {
        return None;
    }
    Some((origin.to_string(), value.to_string()))
}

/// Parses `git config --get-regexp ^alias\.` output into (name, command).
pub fn parse_aliases(text: &str) -> Vec<(String, String)> {
    let mut out: Vec<(String, String)> = text
        .lines()
        .map(|l| l.trim_end_matches('\r'))
        .filter_map(|line| {
            let (key, command) = line.split_once(char::is_whitespace).unwrap_or((line, ""));
            let name = key.strip_prefix("alias.")?;
            if name.is_empty() {
                return None;
            }
            Some((name.to_string(), command.trim().to_string()))
        })
        .collect();
    out.sort();
    out
}

/// Hook file names that are active: not `*.sample`, not empty. Windows `.exe` and extensionless
/// names are kept as they are.
pub fn active_hooks(names: &[String]) -> Vec<String> {
    let mut out: Vec<String> = names
        .iter()
        .map(|n| n.trim().to_string())
        .filter(|n| !n.is_empty() && !n.to_ascii_lowercase().ends_with(".sample"))
        .collect();
    out.sort();
    out.dedup();
    out
}

/// Git C-quotes origin paths containing backslashes (`"C:\\x"` means `C:\x`).
fn unquote(p: &str) -> String {
    match p.strip_prefix('"').and_then(|r| r.strip_suffix('"')) {
        Some(inner) => inner.replace("\\\\", "\\").replace("\\\"", "\""),
        None => p.to_string(),
    }
}

fn norm_path(p: &str) -> String {
    unquote(p)
        .replace('\\', "/")
        .trim_end_matches('/')
        .to_ascii_lowercase()
}

/// Classifies an origin string (`file:<path>`) against the local and global config paths.
pub fn classify_scope(origin: &str, local: Option<&str>, global: Option<&str>) -> Origin {
    let Some(path) = origin.strip_prefix("file:") else {
        return Origin::Other;
    };
    let path = norm_path(path);
    if local.is_some_and(|l| norm_path(l) == path) {
        Origin::Local
    } else if global.is_some_and(|g| norm_path(g) == path) {
        Origin::Global
    } else {
        Origin::Other
    }
}

/// Trims and validates a user.name / user.email value.
pub fn validate_identity(value: &str) -> Result<String, String> {
    let v = value.trim();
    if v.is_empty() {
        return Err("The value cannot be empty.".into());
    }
    if v.chars().any(char::is_control) {
        return Err("The value cannot contain control characters.".into());
    }
    Ok(v.to_string())
}

pub fn validate_email(value: &str) -> Result<String, String> {
    let v = validate_identity(value)?;
    if !v.contains('@') || v.contains(char::is_whitespace) {
        return Err("That does not look like an email address.".into());
    }
    Ok(v)
}

pub fn validate_alias_name(name: &str) -> Result<String, String> {
    let n = name.trim();
    if n.is_empty() {
        return Err("The alias name cannot be empty.".into());
    }
    if !n
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
    {
        return Err("Use only letters, digits, - and _ in an alias name.".into());
    }
    if n.starts_with('-') {
        return Err("An alias name cannot start with '-'.".into());
    }
    Ok(n.to_string())
}

pub fn validate_alias_command(command: &str) -> Result<String, String> {
    let c = command.trim();
    if c.is_empty() {
        return Err("The alias command cannot be empty.".into());
    }
    if c.chars().any(char::is_control) {
        return Err("The command cannot contain control characters.".into());
    }
    Ok(c.to_string())
}

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

fn cfg_text(args: &[&str]) -> Option<String> {
    let out = git::git_raw(args, &git::Opts::default()).ok()?;
    out.ok().then(|| out.text())
}

/// Sets a key in the given scope.
pub fn set_value(scope: Scope, key: &str, value: &str) -> Result<()> {
    if key.starts_with('-') {
        bail!("invalid key");
    }
    git::git_ok(&["config", scope.flag(), key, value], &git::Opts::default())?;
    Ok(())
}

/// Removes a key from the given scope (missing key is not an error).
pub fn unset_value(scope: Scope, key: &str) -> Result<()> {
    if key.starts_with('-') {
        bail!("invalid key");
    }
    let out = git::git_raw(
        &["config", scope.flag(), "--unset", key],
        &git::Opts::default(),
    )?;
    // exit 5 = key was not set
    if out.ok() || out.code == Some(5) {
        Ok(())
    } else {
        bail!("{}", out.stderr.trim())
    }
}

fn local_config_path() -> Option<String> {
    let p = cfg_text(&[
        "rev-parse",
        "--path-format=absolute",
        "--git-path",
        "config",
    ])?;
    (!p.is_empty()).then_some(p)
}

fn global_config_path() -> Option<String> {
    let text = cfg_text(&["config", "--global", "--show-origin", "--list"])?;
    let first = text.lines().next()?;
    let (origin, _) = first.split_once('\t')?;
    origin.strip_prefix("file:").map(unquote)
}

/// Effective value of `key` with its origin classification.
pub fn effective(key: &str) -> Option<(Origin, String, String)> {
    let text = cfg_text(&["config", "--show-origin", "--get", key])?;
    let (origin, value) = parse_show_origin(&text)?;
    // Git reports the repository config relative to the working directory.
    let resolved = match origin.strip_prefix("file:") {
        Some(p) if !Path::new(&unquote(p)).is_absolute() => {
            match cfg_text(&["rev-parse", "--show-toplevel"]) {
                Some(top) => format!("file:{}", Path::new(&top).join(p).display()),
                None => origin.clone(),
            }
        }
        _ => origin.clone(),
    };
    let scope = classify_scope(
        &resolved,
        local_config_path().as_deref(),
        global_config_path().as_deref(),
    );
    Some((scope, origin, value))
}

pub fn list_aliases() -> Vec<(String, String)> {
    cfg_text(&["config", "--global", "--get-regexp", r"^alias\."])
        .map(|t| parse_aliases(&t))
        .unwrap_or_default()
}

pub fn add_alias(name: &str, command: &str) -> Result<()> {
    let name = validate_alias_name(name).map_err(anyhow::Error::msg)?;
    let command = validate_alias_command(command).map_err(anyhow::Error::msg)?;
    set_value(Scope::Global, &format!("alias.{name}"), &command)
}

pub fn remove_alias(name: &str) -> Result<()> {
    let name = validate_alias_name(name).map_err(anyhow::Error::msg)?;
    unset_value(Scope::Global, &format!("alias.{name}"))
}

pub struct HooksInfo {
    pub dir: Option<PathBuf>,
    pub hooks_path: Option<String>,
    pub files: Vec<String>,
}

pub fn hooks_info() -> HooksInfo {
    let hooks_path = cfg_text(&["config", "--get", "core.hooksPath"]).filter(|s| !s.is_empty());
    let dir = cfg_text(&["rev-parse", "--path-format=absolute", "--git-path", "hooks"])
        .filter(|s| !s.is_empty())
        .map(PathBuf::from);
    let effective_dir = match &hooks_path {
        Some(p) if Path::new(p).is_absolute() => Some(PathBuf::from(p)),
        Some(p) => cfg_text(&["rev-parse", "--show-toplevel"]).map(|t| Path::new(&t).join(p)),
        None => dir.clone(),
    };
    let names: Vec<String> = effective_dir
        .as_ref()
        .and_then(|d| std::fs::read_dir(d).ok())
        .map(|rd| {
            rd.flatten()
                .filter(|e| e.path().is_file())
                .map(|e| e.file_name().to_string_lossy().into_owned())
                .collect()
        })
        .unwrap_or_default();
    HooksInfo {
        dir: effective_dir,
        hooks_path,
        files: active_hooks(&names),
    }
}

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

fn origin_label(o: Origin, origin: &str) -> String {
    match o {
        Origin::Local => "this repository (local)".to_string(),
        Origin::Global => "your global config".to_string(),
        Origin::Other => format!("other ({origin})"),
    }
}

fn ask_scope(local_ok: bool) -> Result<Option<Scope>> {
    if !local_ok {
        return Ok(Some(Scope::Global));
    }
    Ok(
        match ui::choose(
            "Where should this be saved?",
            &[],
            &["This repository only (local)", "All repositories (global)"],
        )? {
            Some(0) => Some(Scope::Local),
            Some(1) => Some(Scope::Global),
            _ => None,
        },
    )
}

/// Shows the command, asks for global writes, applies, and reports.
fn apply(cfg: &Config, scope: Scope, key: &str, value: Option<&str>, what: &str) -> Result<()> {
    let command = match value {
        Some(v) => format!("git config {} {key} \"{v}\"", scope.flag()),
        None => format!("git config {} --unset {key}", scope.flag()),
    };
    if scope == Scope::Global && !ui::confirm_action(cfg, what, &command)? {
        return Ok(());
    }
    let result = match value {
        Some(v) => set_value(scope, key, v),
        None => unset_value(scope, key),
    };
    let mut lines = match result {
        Ok(()) => vec![screen::success("Saved."), format!("$ {command}")],
        Err(e) => vec![
            screen::danger(format!("Failed: {e}")),
            format!("$ {command}"),
        ],
    };
    lines.extend(ui::explain(
        cfg,
        &["Global settings apply to every repository on this computer."],
    ));
    ui::notice("Git config", &lines)
}

type Check = fn(&str) -> Result<String, String>;

fn ask_valid(prompt: &str, initial: &str, check: Check) -> Result<Option<String>> {
    loop {
        let Some(answer) = ui::ask(prompt, initial)? else {
            return Ok(None);
        };
        match check(&answer) {
            Ok(v) => return Ok(Some(v)),
            Err(msg) => ui::notice("Invalid value", &[msg])?,
        }
    }
}

/// The identity menu (also used by Start mode).
pub fn edit_identity(cfg: &mut Config) -> Result<()> {
    loop {
        let local_ok = local_config_path().is_some();
        let mut context = Vec::new();
        for (label, key) in [("Name ", "user.name"), ("Email", "user.email")] {
            context.push(match effective(key) {
                Some((o, origin, v)) => {
                    format!("{label}: {v}   [from {}]", origin_label(o, &origin))
                }
                None => format!("{label}: {}", screen::warning("not set")),
            });
        }
        let account = cfg
            .active_account
            .as_ref()
            .and_then(|a| cfg.accounts.iter().find(|x| &x.label == a))
            .cloned();
        let use_label;
        let mut options = vec!["Set name", "Set email"];
        if let Some(a) = &account {
            use_label = format!("Use my active gct account ({})", a.label);
            options.push(&use_label);
        }
        let Some(pick) = ui::choose("Identity (name and email)", &context, &options)? else {
            return Ok(());
        };
        match pick {
            0 | 1 => {
                let (key, prompt, check): (&str, &str, Check) = if pick == 0 {
                    ("user.name", "Your name", validate_identity)
                } else {
                    ("user.email", "Your email", validate_email)
                };
                let initial = effective(key).map(|(_, _, v)| v).unwrap_or_default();
                let Some(value) = ask_valid(prompt, &initial, check)? else {
                    continue;
                };
                let Some(scope) = ask_scope(local_ok)? else {
                    continue;
                };
                apply(
                    cfg,
                    scope,
                    key,
                    Some(&value),
                    &format!("Set {key} to {value}"),
                )?;
            }
            _ => {
                let Some(a) = account else { continue };
                let (Ok(name), Ok(email)) = (validate_identity(&a.name), validate_email(&a.email))
                else {
                    ui::notice(
                        "Git config",
                        &["That account has an invalid name or email.".to_string()],
                    )?;
                    continue;
                };
                let Some(scope) = ask_scope(local_ok)? else {
                    continue;
                };
                apply(
                    cfg,
                    scope,
                    "user.name",
                    Some(&name),
                    &format!("Set user.name to {name}"),
                )?;
                apply(
                    cfg,
                    scope,
                    "user.email",
                    Some(&email),
                    &format!("Set user.email to {email}"),
                )?;
            }
        }
    }
}

fn current(key: &str) -> String {
    cfg_text(&["config", "--global", "--get", key]).unwrap_or_else(|| "not set".into())
}

fn default_branch(cfg: &Config) -> Result<()> {
    let ctx = vec![
        format!(
            "init.defaultBranch (global): {}",
            current("init.defaultBranch")
        ),
        "Name given to the first branch of every new repository.".to_string(),
    ];
    let value = match ui::choose(
        "Default branch name",
        &ctx,
        &["main", "master", "Custom name"],
    )? {
        Some(0) => "main".to_string(),
        Some(1) => "master".to_string(),
        Some(2) => {
            let check: fn(&str) -> Result<String, String> = |s| {
                let v = validate_identity(s)?;
                if v.starts_with('-') || v.contains(char::is_whitespace) {
                    return Err("Invalid branch name.".into());
                }
                Ok(v)
            };
            match ask_valid("Default branch name", "", check)? {
                Some(v) => v,
                None => return Ok(()),
            }
        }
        _ => return Ok(()),
    };
    apply(
        cfg,
        Scope::Global,
        "init.defaultBranch",
        Some(&value),
        &format!("Set the default branch to {value}"),
    )
}

fn pull_strategy(cfg: &Config) -> Result<()> {
    let ctx = vec![
        format!("pull.rebase: {}", current("pull.rebase")),
        format!("pull.ff: {}", current("pull.ff")),
    ];
    let Some(which) = ui::choose(
        "Pull strategy",
        &ctx,
        &[
            "pull.rebase (merge or rebase)",
            "pull.ff (fast-forward only)",
        ],
    )?
    else {
        return Ok(());
    };
    if which == 0 {
        let mut help = vec![
            "true = replay your commits on top of the remote ones (straight history).".to_string(),
            "false = create a merge commit; unset = Git asks you to decide.".to_string(),
        ];
        help.extend(ui::explain(
            cfg,
            &["Rebase keeps history linear; merge keeps every branch point."],
        ));
        match ui::choose("pull.rebase", &help, &["true", "false", "unset"])? {
            Some(0) => apply(
                cfg,
                Scope::Global,
                "pull.rebase",
                Some("true"),
                "Pull will rebase",
            )?,
            Some(1) => apply(
                cfg,
                Scope::Global,
                "pull.rebase",
                Some("false"),
                "Pull will merge",
            )?,
            Some(2) => apply(
                cfg,
                Scope::Global,
                "pull.rebase",
                None,
                "Remove pull.rebase",
            )?,
            _ => {}
        }
    } else {
        let mut help = vec![
            "only = pull refuses unless it is a simple fast-forward (safest).".to_string(),
            "default = let Git merge when branches diverged.".to_string(),
        ];
        help.extend(ui::explain(
            cfg,
            &["'only' never creates surprise merge commits."],
        ));
        match ui::choose("pull.ff", &help, &["only", "default"])? {
            Some(0) => apply(
                cfg,
                Scope::Global,
                "pull.ff",
                Some("only"),
                "Pull will only fast-forward",
            )?,
            Some(1) => apply(
                cfg,
                Scope::Global,
                "pull.ff",
                None,
                "Return pull.ff to default",
            )?,
            _ => {}
        }
    }
    Ok(())
}

fn line_endings(cfg: &Config) -> Result<()> {
    let mut ctx = vec![format!(
        "core.autocrlf (global): {}",
        current("core.autocrlf")
    )];
    ctx.push("true = CRLF in your files, LF in the repository (Windows).".to_string());
    ctx.push("input = keep LF, never convert on checkout (macOS/Linux).".to_string());
    ctx.push("false = do not convert anything.".to_string());
    ctx.extend(ui::explain(
        cfg,
        &["Windows and Linux end lines differently; this keeps commits clean."],
    ));
    let value = match ui::choose(
        "Line endings",
        &ctx,
        &["true (Windows)", "input (macOS / Linux)", "false"],
    )? {
        Some(0) => "true",
        Some(1) => "input",
        Some(2) => "false",
        _ => return Ok(()),
    };
    apply(
        cfg,
        Scope::Global,
        "core.autocrlf",
        Some(value),
        &format!("Set core.autocrlf to {value}"),
    )
}

fn aliases(cfg: &Config) -> Result<()> {
    loop {
        let list = list_aliases();
        let ctx: Vec<String> = if list.is_empty() {
            vec!["No aliases yet. Add one, e.g. name 'st' command 'status -sb'.".to_string()]
        } else {
            list.iter().map(|(n, c)| format!("{n} = {c}")).collect()
        };
        match ui::choose(
            "Aliases (global)",
            &ctx,
            &["Add an alias", "Remove an alias"],
        )? {
            Some(0) => {
                let Some(name) = ask_valid("Alias name", "", validate_alias_name)? else {
                    continue;
                };
                let Some(command) =
                    ask_valid("Git command (without 'git')", "", validate_alias_command)?
                else {
                    continue;
                };
                let cmd = format!("git config --global alias.{name} \"{command}\"");
                if !ui::confirm_action(cfg, &format!("Add alias '{name}'"), &cmd)? {
                    continue;
                }
                let msg = match add_alias(&name, &command) {
                    Ok(()) => screen::success(format!("Alias '{name}' added. Use: git {name}")),
                    Err(e) => screen::danger(format!("Failed: {e}")),
                };
                ui::notice("Aliases", &[msg, format!("$ {cmd}")])?;
            }
            Some(1) if !list.is_empty() => {
                let names: Vec<&str> = list.iter().map(|(n, _)| n.as_str()).collect();
                let Some(i) = ui::choose("Remove which alias?", &[], &names)? else {
                    continue;
                };
                let name = &list[i].0;
                let cmd = format!("git config --global --unset alias.{name}");
                if !ui::confirm_action(cfg, &format!("Remove alias '{name}'"), &cmd)? {
                    continue;
                }
                let msg = match remove_alias(name) {
                    Ok(()) => screen::success(format!("Alias '{name}' removed.")),
                    Err(e) => screen::danger(format!("Failed: {e}")),
                };
                ui::notice("Aliases", &[msg, format!("$ {cmd}")])?;
            }
            Some(1) => ui::notice("Aliases", &["Nothing to remove.".to_string()])?,
            _ => return Ok(()),
        }
    }
}

fn hooks() -> Result<()> {
    loop {
        let info = hooks_info();
        let mut ctx = Vec::new();
        if let Some(p) = &info.hooks_path {
            ctx.push(format!("core.hooksPath = {p}"));
            ctx.push("managed by your team (husky/lefthook) \u{2014} read only".to_string());
        }
        match &info.dir {
            Some(d) => ctx.push(format!("Hooks folder: {}", d.display())),
            None => ctx.push("Not inside a repository: no hooks folder.".to_string()),
        }
        if info.files.is_empty() {
            ctx.push("No active hooks (files ending in .sample are ignored).".to_string());
            return ui::notice("Hooks (read-only)", &ctx);
        }
        ctx.push("Pick a hook to read its first lines. gct never edits hooks.".to_string());
        let names: Vec<&str> = info.files.iter().map(String::as_str).collect();
        let Some(i) = ui::choose("Hooks (read-only)", &ctx, &names)? else {
            return Ok(());
        };
        let Some(dir) = &info.dir else { return Ok(()) };
        let text = std::fs::read(dir.join(&info.files[i]))
            .map(|b| String::from_utf8_lossy(&b).into_owned())
            .unwrap_or_else(|e| format!("Cannot read: {e}"));
        let lines: Vec<String> = text.lines().take(40).map(str::to_string).collect();
        ui::pager(&info.files[i], &lines, "")?;
    }
}

/// Entry point called by the mode router inside an active terminal UI.
pub fn run(config: &mut Config) -> Result<()> {
    loop {
        let options = [
            "Identity (name and email)",
            "Default branch name",
            "Pull strategy",
            "Line endings",
            "Aliases",
            "Hooks (read-only)",
            "Ignore file (opens Ignore mode)",
        ];
        match ui::choose("Git config", &[], &options)? {
            Some(0) => edit_identity(config)?,
            Some(1) => default_branch(config)?,
            Some(2) => pull_strategy(config)?,
            Some(3) => line_endings(config)?,
            Some(4) => aliases(config)?,
            Some(5) => hooks()?,
            Some(6) => crate::modes::open("ignore", config)?,
            _ => return Ok(()),
        }
    }
}

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

    #[test]
    fn show_origin_parsing() {
        assert_eq!(
            parse_show_origin("file:C:/Users/x/.gitconfig\tAda Lovelace\r\n"),
            Some(("file:C:/Users/x/.gitconfig".into(), "Ada Lovelace".into()))
        );
        assert_eq!(parse_show_origin(""), None);
        assert_eq!(parse_show_origin("no tab here"), None);
        assert_eq!(
            parse_show_origin("file:/a\tj\u{e9}r\u{f4}me").unwrap().1,
            "j\u{e9}r\u{f4}me"
        );
    }

    #[test]
    fn alias_parsing() {
        let t =
            "alias.st status -sb\r\nalias.co checkout\nalias.lg log --oneline --graph\nother.x y\n";
        assert_eq!(
            parse_aliases(t),
            vec![
                ("co".into(), "checkout".into()),
                ("lg".into(), "log --oneline --graph".into()),
                ("st".into(), "status -sb".into())
            ]
        );
        assert!(parse_aliases("").is_empty());
    }

    #[test]
    fn hooks_filtering() {
        let names: Vec<String> = [
            "pre-commit",
            "pre-push.sample",
            "commit-msg.exe",
            "PREPARE.SAMPLE",
            "",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        assert_eq!(active_hooks(&names), vec!["commit-msg.exe", "pre-commit"]);
    }

    #[test]
    fn validation() {
        assert_eq!(validate_identity("  Ada  ").unwrap(), "Ada");
        assert!(validate_identity("   ").is_err());
        assert!(validate_identity("a\u{7}b").is_err());
        assert!(validate_email("a@b.c").is_ok());
        assert!(validate_email("nope").is_err());
        assert!(validate_alias_name("my-al_1").is_ok());
        assert!(validate_alias_name("bad name").is_err());
        assert!(validate_alias_name("-x").is_err());
        assert!(validate_alias_command("  ").is_err());
    }

    #[test]
    fn scope_classification() {
        let l = Some("C:/r/.git/config");
        let g = Some("C:/Users/x/.gitconfig");
        assert_eq!(
            classify_scope("file:C:\\R\\.git\\config", l, g),
            Origin::Local
        );
        assert_eq!(
            classify_scope("file:C:/Users/x/.gitconfig", l, g),
            Origin::Global
        );
        assert_eq!(classify_scope("file:/etc/gitconfig", l, g), Origin::Other);
        assert_eq!(classify_scope("command line:", l, g), Origin::Other);
        assert_eq!(classify_scope("file:/x", None, None), Origin::Other);
        let quoted = "file:\"C:\\Users\\x\\.gitconfig\"";
        assert_eq!(classify_scope(quoted, l, g), Origin::Global);
    }

    #[test]
    fn local_identity_round_trip() {
        let repo = TempRepo::new(1);
        repo.run(|| {
            set_value(Scope::Local, "user.name", "Zed Local").unwrap();
            let (o, origin, v) = effective("user.name").unwrap();
            assert_eq!(v, "Zed Local");
            assert_eq!(o, Origin::Local, "origin was {origin}");
        });
    }

    #[test]
    fn global_identity_uses_temp_global_only() {
        let repo = TempRepo::new(1);
        repo.git(&["config", "--unset", "user.name"]);
        repo.run(|| {
            set_value(Scope::Global, "user.name", "Glob Al").unwrap();
            let (o, origin, v) = effective("user.name").unwrap();
            assert_eq!((o, v.as_str()), (Origin::Global, "Glob Al"));
            let real = global_config_path().unwrap();
            assert!(
                real.contains("gct-ut-"),
                "global path escaped isolation: {real} ({origin})"
            );
        });
    }

    #[test]
    fn alias_round_trip_and_default_branch() {
        let repo = TempRepo::new(1);
        repo.run(|| {
            assert!(list_aliases().is_empty());
            add_alias("st", "status -sb").unwrap();
            assert_eq!(
                list_aliases(),
                vec![("st".to_string(), "status -sb".to_string())]
            );
            assert!(add_alias("bad name", "x").is_err());
            remove_alias("st").unwrap();
            assert!(list_aliases().is_empty());
            remove_alias("st").unwrap();
            set_value(Scope::Global, "init.defaultBranch", "trunk").unwrap();
            assert_eq!(current("init.defaultBranch"), "trunk");
        });
    }

    #[test]
    fn hooks_listing() {
        let repo = TempRepo::new(1);
        repo.write(".git/hooks/pre-commit", "#!/bin/sh\nexit 0\n");
        repo.write(".git/hooks/pre-push.sample", "#!/bin/sh\n");
        let info = repo.run(hooks_info);
        assert_eq!(info.files, vec!["pre-commit"]);
        assert!(info.hooks_path.is_none());
        assert!(info.dir.is_some());
    }
}