git-custom-cli 2.4.0

Fast, keyboard-driven terminal UI for dated Git commits
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
mod accounts;
mod cmdlog;
mod config;
mod diff;
// Shared helpers for the git modes; parts stay unused until every mode is filled in.
mod explain;
mod git;
mod gitconfig;
mod history;
mod input;
mod mascot;
mod model;
mod modes;
mod policy;
mod release;
mod repo_state;
mod safety;
#[path = "terminal.rs"]
mod screen;
#[cfg(test)]
mod testutil;
mod ui;

use anyhow::{anyhow, bail, Context, Result};
use clap::{ArgGroup, Parser};
use mascot::Mood;
use model::{first_problem, initial_values, preview, set_keymap, Config, Values};
use modes::Mode;
use policy::Verdict;
use std::io::{stdin, stdout, IsTerminal};
use std::path::{Path, PathBuf};
use std::sync::atomic::Ordering;
use ui::JobPanic;

/// The legacy commit flow always pushes to this remote.
const REMOTE: &str = "origin";

#[derive(Parser, Debug)]
#[command(
    name = "gct",
    version,
    about = "Fast Git commit TUI",
    group(
        ArgGroup::new("mode_select")
            .multiple(false)
            .args([
                "settings", "hub", "mode", "commit", "stage", "status", "sync", "log", "stash",
                "undo", "tag",
            ])
            .conflicts_with_all([
                "account", "clear_config", "date", "time", "branch", "message", "ml", "push",
                "push_only", "amend", "dry_run",
            ])
    )
)]
struct Args {
    /// Open the settings screen (default mode, remote, confirmations, theme)
    #[arg(long)]
    settings: bool,
    /// Open the hub, a launcher for every mode
    #[arg(long)]
    hub: bool,
    /// Open a mode by name or alias, e.g. commit, hub, status, stage, branch, sync, log, undo (rescue), conflicts (resolve), start; a wrong name lists them all
    #[arg(long, value_name = "NAME")]
    mode: Option<String>,
    /// Open the commit TUI (the default unless settings choose another mode)
    #[arg(long)]
    commit: bool,
    /// Open stage mode (same as --mode stage)
    #[arg(long)]
    stage: bool,
    /// Open status mode (same as --mode status)
    #[arg(long)]
    status: bool,
    /// Open sync mode (same as --mode sync)
    #[arg(long)]
    sync: bool,
    /// Open log mode (same as --mode log)
    #[arg(long)]
    log: bool,
    /// Open stash mode (same as --mode stash)
    #[arg(long)]
    stash: bool,
    /// Open undo mode (same as --mode undo)
    #[arg(long)]
    undo: bool,
    /// Open tag mode (same as --mode tag)
    #[arg(long)]
    tag: bool,
    /// Open the saved-accounts screen
    #[arg(long, conflicts_with = "clear_config")]
    account: bool,
    /// Delete the saved configuration file
    #[arg(long)]
    clear_config: bool,
    /// Print a usage guide for AI agents and exit
    #[arg(long)]
    agent: bool,
    /// Commit date YYYY-MM-DD (YYYY:MM:DD also works); default today. Any of -d/-t/-b/-m/-ml skips the TUI
    #[arg(short = 'd', long)]
    date: Option<String>,
    /// Commit time HH:MM:SS; default now
    #[arg(short = 't', long)]
    time: Option<String>,
    /// Branch to push to; default the current branch
    #[arg(short = 'b', long)]
    branch: Option<String>,
    /// One-line commit message (required without the TUI)
    #[arg(short = 'm', long)]
    message: Option<String>,
    /// Description as bullets: -ml "- first item - second item"
    #[arg(long = "ml", allow_hyphen_values = true)]
    ml: Option<String>,
    /// Also push to origin/<branch> after committing (default: local commit only)
    #[arg(long)]
    push: bool,
    /// Push existing local commits to origin/<branch> without committing
    #[arg(
        long,
        conflicts_with_all = ["push", "amend", "dry_run", "message", "ml", "date", "time"]
    )]
    push_only: bool,
    /// Amend the last commit instead of creating a new one
    #[arg(long)]
    amend: bool,
    /// Print what would run without changing anything
    #[arg(long)]
    dry_run: bool,
}

const AGENT_GUIDE: &str = r#"gct - commit with a custom date/time. Run inside a git repo.
It runs `git add .` (stages everything) and commits. With --push it also pushes to origin/<branch>.

Command format:
  gct -d YYYY-MM-DD -t HH:MM:SS -b <branch> -m "<type>: <one-line summary>" -ml "- <item> - <item>" [--push] [--amend] [--dry-run]
  gct --push-only [-b <branch>]

Flags:
  -d   commit date YYYY-MM-DD (default: today)
  -t   commit time HH:MM:SS, 24h (default: now)
  -b   branch to push to (default: current branch)
  -m   one-line commit message (required)
  -ml  optional description; each item becomes a bullet
  --push  push after committing (without it the commit stays local)
  --push-only  push existing local commits to origin/<branch>; commits nothing
  --amend  amend the last commit instead of creating a new one
  --dry-run  print the commands that would run; changes nothing

Example:
  gct -d 2026-05-05 -t 15:45:15 -b main -m "feat: add auth" -ml "- integrate login - integrate register"
Produces the commit message:
  feat: add auth

  - integrate login
  - integrate register

Rules: quote -m and -ml values. In -ml, separate items with " - " (space, dash, space).
Text inside an item may then contain flags like -d or --agent and words like log-in.
Short form "-one -two" also works, but splits at every " -", so avoid it when items mention flags.
Without any of these flags, gct opens its TUI.
The TUI modes (gct --hub, gct --mode <name>) need a terminal and are not for scripts or agents;
without a TTY, gct --mode <name> fails. Use the flags above for non-interactive commits."#;

/// Turns a failed step into a menu notice, except a panic, which propagates as fatal.
fn stay(error: anyhow::Error, prefix: &str) -> Result<Step> {
    if error.is::<JobPanic>() {
        return Err(error);
    }
    Ok(Step::Stay(Some(format!("{prefix}{}", masked(&error)))))
}

/// An error as text with credentials hidden (git's stderr can echo a remote URL with a token).
fn masked(error: &anyhow::Error) -> String {
    cmdlog::mask(&format!("{error:#}"))
}

/// Whether the commit flow runs `git add .` first, and the summary line when it does not.
/// Stage mode sets `modes::STAGED_ONLY` so that only what it staged is committed.
fn staging(staged_only: bool) -> (bool, Option<&'static str>) {
    if staged_only {
        (false, Some("  Mode:   commit staged changes only"))
    } else {
        (true, None)
    }
}

/// The folder gct was started in (set once in `main`, before any mode changes folder).
static START_DIR: std::sync::OnceLock<Option<PathBuf>> = std::sync::OnceLock::new();

/// Where the commit flow should run `git add .`: the start folder when a repository mode moved
/// the process to the repository root (a jump into Commit from Status, Guide...) and the start
/// folder lies below that root; None keeps the current folder (Commit opened directly or from
/// the Hub, or the start folder is elsewhere, e.g. after Start mode cloned a repository).
/// All three paths must be canonical.
fn staging_dir(start: Option<&Path>, cwd: &Path, root: &Path) -> Option<PathBuf> {
    let start = start?;
    (cwd == root && start != root && start.starts_with(root)).then(|| start.to_path_buf())
}

/// `staging_dir` for this process, resolved through git and the file system.
fn current_staging_dir() -> Option<PathBuf> {
    let start = START_DIR.get()?.as_ref()?;
    let out = git::git_raw(&["rev-parse", "--show-toplevel"], &git::Opts::default()).ok()?;
    if !out.ok() {
        return None;
    }
    let root = std::fs::canonicalize(out.text()).ok()?;
    let cwd = std::fs::canonicalize(std::env::current_dir().ok()?).ok()?;
    let canonical = std::fs::canonicalize(start).ok()?;
    // Compared canonically, but git gets the folder as the shell gave it (on Windows a
    // canonical path is a `\\?\` path).
    staging_dir(Some(&canonical), &cwd, &root).map(|_| start.clone())
}

/// What to do before a force push (an amended commit), given the policy verdict.
#[derive(Debug, PartialEq, Eq)]
enum PushGate {
    Go,
    /// Ask the user through `ui::gate` (interactive only).
    Ask,
    Refuse(String),
}

/// Without a terminal nobody can answer a Danger prompt: the push goes ahead only when the
/// policy did not deny it (a protected branch is always Deny for ForcePush).
fn force_push_gate(verdict: &Verdict, interactive: bool) -> PushGate {
    match verdict {
        Verdict::Allow => PushGate::Go,
        Verdict::Deny(message) => PushGate::Refuse(message.clone()),
        Verdict::Confirm | Verdict::Danger if !interactive => PushGate::Go,
        Verdict::Typed(_) if !interactive => {
            PushGate::Refuse("this push needs a typed confirmation; run gct in a terminal".into())
        }
        _ => PushGate::Ask,
    }
}

fn force_push_command(branch: &str) -> String {
    format!(
        "git push --force-with-lease=refs/heads/{branch} --force-if-includes {REMOTE} refs/heads/{branch}:refs/heads/{branch}"
    )
}

/// TUI check before a force push: Ok(None) = go ahead, Ok(Some(reason)) = do not push.
fn tui_force_gate(config: &Config, branch: &str) -> Result<Option<String>> {
    let verdict = policy::check(
        config,
        &policy::Op::ForcePush {
            remote: REMOTE,
            branch,
        },
    );
    match force_push_gate(&verdict, true) {
        PushGate::Go => Ok(None),
        PushGate::Refuse(message) => Ok(Some(format!("push refused: {message}"))),
        PushGate::Ask => {
            let what = format!(
                "Overwrite {REMOTE}/{branch} with your amended commit. Commits only on the remote are lost."
            );
            if ui::gate(config, &verdict, &what, &force_push_command(branch))? {
                Ok(None)
            } else {
                Ok(Some("force push skipped".into()))
            }
        }
    }
}

/// Why the policy refuses the forced push an amend on `branch` needs (None = not refused;
/// a Danger/Typed verdict is still asked after the amend, by `tui_force_gate`).
fn amend_push_refusal(config: &Config, branch: &str) -> Option<String> {
    let verdict = policy::check(
        config,
        &policy::Op::ForcePush {
            remote: REMOTE,
            branch,
        },
    );
    match force_push_gate(&verdict, true) {
        PushGate::Refuse(message) => Some(message),
        PushGate::Go | PushGate::Ask => None,
    }
}

/// Saves HEAD under refs/gct/backup before an amend; None when HEAD has no commit yet.
fn amend_backup() -> Result<Option<String>> {
    let born = git::git_raw(
        &["rev-parse", "--verify", "--quiet", "HEAD"],
        &git::Opts::default(),
    )?;
    if !born.ok() {
        return Ok(None);
    }
    safety::backup("amend", "HEAD")
        .map(Some)
        .context("Could not back up the commit before amending")
}

fn backup_line(backup: Option<&str>) -> Option<String> {
    backup.map(|refname| format!("Backup of the previous commit: {refname}"))
}

/// What the menu does after a finalize attempt.
enum Step {
    /// Stay in the menu, optionally explaining why the commit did not run.
    Stay(Option<String>),
    /// Leave the TUI and print these lines to the normal terminal.
    Finish(Vec<String>),
}

fn run() -> Result<Vec<String>> {
    // clap short flags are one letter, so `-ml` would parse as `-m l`; rewrite it to `--ml`.
    let args =
        Args::parse_from(
            std::env::args().map(|arg| if arg == "-ml" { "--ml".into() } else { arg }),
        );
    if args.agent {
        return Ok(vec![AGENT_GUIDE.into()]);
    }
    if args.clear_config {
        config::clear()?;
        return Ok(vec!["Saved configuration cleared.".into()]);
    }
    if args.date.is_some()
        || args.time.is_some()
        || args.branch.is_some()
        || args.message.is_some()
        || args.ml.is_some()
        || args.push
        || args.push_only
        || args.amend
        || args.dry_run
    {
        return direct_commit(args);
    }
    // An unknown --mode is reported before the terminal check, so scripts see the valid names.
    let requested = requested_mode(&args)?;
    if !stdin().is_terminal() || !stdout().is_terminal() {
        bail!("gct needs an interactive terminal; run it directly in a shell");
    }
    let mut config = config::load()?;
    set_keymap(config.keys.clone());
    apply_theme(&config);
    let mode = requested.unwrap_or_else(|| Mode::from_config(&config.default_mode));
    modes::start(mode, &mut config)
}

/// The mode named by the flags, None when no mode flag was given.
fn requested_mode(args: &Args) -> Result<Option<Mode>> {
    if let Some(name) = &args.mode {
        return Mode::parse(name).map(Some).ok_or_else(|| {
            anyhow!(
                "unknown mode '{}'; valid modes: {}",
                name.trim(),
                Mode::names()
            )
        });
    }
    let flags = [
        (args.account, "account"),
        (args.settings, "settings"),
        (args.hub, "hub"),
        (args.commit, "commit"),
        (args.stage, "stage"),
        (args.status, "status"),
        (args.sync, "sync"),
        (args.log, "log"),
        (args.stash, "stash"),
        (args.undo, "undo"),
        (args.tag, "tag"),
    ];
    Ok(flags
        .into_iter()
        .find(|(on, _)| *on)
        .and_then(|(_, name)| Mode::parse(name)))
}

/// The saved-accounts screen (`gct --account`). Expects the terminal UI to be active.
fn run_accounts(config: &mut Config) -> Result<()> {
    // Save before propagating any error, so a Ctrl+C after a switch keeps the snapshot.
    let result = input::accounts_screen(config);
    config::save(config)?;
    result
}

/// The commit TUI (main menu). Expects the terminal UI to be active; returns the lines to print
/// after it closes.
fn run_commit_tui(config: &mut Config) -> Result<Vec<String>> {
    // Consumed on entry, so leaving this screen without committing never carries it over.
    let staged_only = modes::STAGED_ONLY.swap(false, Ordering::Relaxed);
    let branch = git::current_branch().map_err(|_| anyhow!("Not a git repository"))?;
    if branch == "HEAD" {
        bail!("HEAD is detached; check out a branch before committing");
    }
    // Branch, status and identity are independent git calls, so run them side by side.
    let (status, name) = std::thread::scope(|scope| {
        let status = scope.spawn(git::status_lines);
        let name = scope.spawn(gitconfig::name);
        (status.join(), name.join())
    });
    let status = status
        .map_err(|_| anyhow!("git step panicked"))?
        .map_err(|_| anyhow!("Not a git repository"))?;
    let mut name = name.ok().flatten();
    let mut status = status;
    let mut values = initial_values(config.clone(), &branch);
    let mut context = status_context(&branch, &status, name.as_deref());
    let branches = git::local_branches().unwrap_or_default();

    let mut index = 0;
    let mut notice = None;
    // True after an amended commit whose push failed, so "Push only" still force-with-leases.
    let mut force_push = false;
    loop {
        screen::set_mood(if notice.is_some() {
            Mood::Error
        } else {
            Mood::Idle
        });
        let active = config
            .active_account
            .clone()
            .unwrap_or_else(|| "git default".into());
        screen::set_subtitle(false);
        let choice = input::menu(
            &context,
            &mut values,
            notice.take().as_deref(),
            &mut index,
            &active,
            &branches,
        );
        screen::set_subtitle(true);
        let choice = choice?;
        match choice.as_str() {
            "push" => notice = push_only(&values, config, &mut force_push)?,
            "account-next" | "account-prev" => {
                let step = if choice == "account-next" { 1 } else { -1 };
                if let Err(error) = cycle_account(config, step) {
                    if error.is::<JobPanic>() {
                        return Err(error);
                    }
                    notice = Some(error.to_string());
                }
                name = gitconfig::name();
                context = status_context(&branch, &status, name.as_deref());
            }
            "account" => {
                match input::pick_account(&config.accounts, config.active_account.as_deref())? {
                    Some(input::Pick::Account(label)) => {
                        if let Err(error) = accounts::activate(config, &label) {
                            notice = Some(error.to_string());
                        } else {
                            config::save(config)?;
                        }
                    }
                    Some(input::Pick::GitDefault) => {
                        accounts::deactivate(config)?;
                        config::save(config)?;
                    }
                    None => {}
                }
                name = gitconfig::name();
                context = status_context(&branch, &status, name.as_deref());
            }
            "date" => values.date = input::masked("Commit date (YYYY-MM-DD):", &values.date, true)?,
            "time" => values.time = input::masked("Commit time (HH:MM:SS):", &values.time, false)?,
            "branch" => values.branch = input::read_line("Branch to push:", &values.branch, false)?,
            "message" => {
                values.message = input::read_line("Commit message:", &values.message, true)?
            }
            "editor" => match input::external_editor(&values.message) {
                Ok(message) => values.message = message,
                Err(error) if input::is_cancel(&error) => {}
                Err(error) => notice = Some(error.to_string()),
            },
            "options" => input::options(&mut values)?,
            "history" => input::history()?,
            "tree" => {
                input::working_tree()?;
                // Files may have changed since startup, so refresh the header too.
                if let Ok(fresh) = git::status_lines() {
                    status = fresh;
                }
                name = gitconfig::name();
                context = status_context(&branch, &status, name.as_deref());
            }
            "finalize" => {
                let account = active_account(config).cloned();
                match finalize(
                    &mut values,
                    config,
                    account.as_ref(),
                    &mut force_push,
                    staged_only,
                )? {
                    Step::Stay(message) => notice = message,
                    Step::Finish(summary) => return Ok(summary),
                }
            }
            _ => unreachable!(),
        }
    }
}

fn apply_theme(config: &Config) {
    screen::set_theme(screen::ThemeSettings {
        accent: config.theme.accent_rgb(),
        show_header: config.theme.show_header,
        show_mascot: config.theme.show_mascot,
        show_subtitle: config.theme.show_subtitle,
    });
}

/// Switches to the next/previous entry of [git default] + accounts, wrapping around.
fn cycle_account(config: &mut Config, step: i32) -> Result<()> {
    let mut entries: Vec<Option<String>> = vec![None];
    entries.extend(config.accounts.iter().map(|a| Some(a.label.clone())));
    let current = entries
        .iter()
        .position(|e| *e == config.active_account)
        .unwrap_or(0) as i32;
    let next = (current + step).rem_euclid(entries.len() as i32) as usize;
    match &entries[next] {
        Some(label) => accounts::activate(config, label)?,
        None => accounts::deactivate(config)?,
    }
    config::save(config)
}

/// Push-only flow from the menu: no commit; failures become a notice instead of leaving the TUI.
fn push_only(values: &Values, config: &Config, force_push: &mut bool) -> Result<Option<String>> {
    let branch = values.branch.trim();
    if branch.is_empty() {
        return Ok(Some("Set a branch to push first".into()));
    }
    if let Err(error) = git::check_branch_name(branch) {
        return Ok(Some(format!("Not pushed: {error}")));
    }
    let force = values.amend || *force_push;
    if force {
        // The policy decides (protected branch = refused) and asks with the exact command.
        match tui_force_gate(config, branch) {
            Ok(None) => {}
            Ok(Some(reason)) => return Ok(Some(format!("Not pushed: {reason}"))),
            Err(error) if input::is_cancel(&error) => return Ok(None),
            Err(error) => return Err(error),
        }
    } else {
        match input::confirm(&[], &format!("Push to origin/{branch}?"), true) {
            Ok(true) => {}
            Ok(false) => return Ok(None),
            Err(error) if input::is_cancel(&error) => return Ok(None),
            Err(error) => return Err(error),
        }
    }
    let account = active_account(config);
    if let Some(account) = account {
        if let Err(error) = accounts::verify_login(&account.github_username) {
            return Ok(Some(format!("Not pushed: {error}")));
        }
    }
    let (_, login) = identity_and_login(account);
    let result = working(format!("Pushing to origin/{branch}..."), || {
        git::push(branch, force, login)
    });
    Ok(Some(match result {
        Ok(()) => {
            *force_push = false;
            format!("Pushed to origin/{branch}")
        }
        Err(error) if error.is::<JobPanic>() => return Err(error),
        Err(error) => format!("Push failed: {}", masked(&error)),
    }))
}

fn status_context(branch: &str, status: &[String], name: Option<&str>) -> Vec<String> {
    let mut lines = vec![format!(
        "{} {}",
        screen::muted("Branch"),
        screen::accent(branch)
    )];
    let who = name.unwrap_or("not set").to_string();
    lines.push(format!("{} {}", screen::muted("GitHub"), screen::tag(who)));
    // The file list lives in the working-tree view; selecting this line opens it.
    let tree = if status == ["(clean working tree)"] {
        "Working tree clean".to_string()
    } else {
        format!("Working tree: {} changes", status.len())
    };
    lines.push(format!(
        "{} {}",
        screen::tag(tree),
        screen::muted("(click to view)")
    ));
    lines
}

/// Runs a blocking git step on a thread while an animated spinner frame redraws.
fn working<T: Send>(message: impl AsRef<str>, job: impl FnOnce() -> Result<T> + Send) -> Result<T> {
    ui::git_job(message.as_ref(), job)
}

fn active_account(config: &Config) -> Option<&accounts::Account> {
    config
        .active_account
        .as_deref()
        .and_then(|label| config.accounts.iter().find(|a| a.label == label))
}

/// With no active account, both stay None and git uses its own config as before.
fn identity_and_login(
    account: Option<&accounts::Account>,
) -> (Option<git::Identity>, Option<&str>) {
    let identity = account.map(|a| git::Identity {
        name: if a.name.trim().is_empty() {
            a.github_username.clone()
        } else {
            a.name.clone()
        },
        email: a.email.clone(),
    });
    let login = account
        .map(|a| a.github_username.as_str())
        .filter(|login| !login.is_empty());
    (identity, login)
}

/// Commits from flags without the TUI, so scripts and agents can run gct.
fn direct_commit(args: Args) -> Result<Vec<String>> {
    let branch = git::current_branch().map_err(|_| anyhow!("Not a git repository"))?;
    // A detached commit would not be on the branch that gets pushed, same rule as the TUI.
    if branch == "HEAD" {
        bail!("HEAD is detached; check out a branch before committing");
    }
    if args.push_only {
        let target = args.branch.unwrap_or(branch);
        git::check_branch_name(&target)?;
        let config = config::load()?;
        let account = active_account(&config);
        if let Some(account) = account {
            accounts::verify_login(&account.github_username).context("Not pushed")?;
        }
        let (_, login) = identity_and_login(account);
        git::push(&target, false, login).context("Push failed")?;
        return Ok(vec![format!("Done. push origin/{target}")]);
    }
    let now = chrono::Local::now();
    let values = Values {
        date: args.date.map_or_else(
            || now.format("%Y-%m-%d").to_string(),
            |d| d.replace(':', "-"),
        ),
        time: args
            .time
            .unwrap_or_else(|| now.format("%H:%M:%S").to_string()),
        branch: args.branch.unwrap_or(branch),
        message: match (args.message, args.ml) {
            (Some(m), Some(list)) => model::with_bullets(&m, &list),
            (Some(m), None) => m.trim().into(),
            (None, _) => bail!("-m <message> is required (run `gct --agent` for the format)"),
        },
        amend: args.amend,
        dry_run: args.dry_run,
    };
    if let Some(problem) = first_problem(&values) {
        bail!("{problem}");
    }
    // The branch ends up in git's arguments; a value like `--mirror` must never become an option.
    git::check_branch_name(&values.branch)?;
    if values.dry_run {
        let date = format!("{} {}", values.date, values.time);
        let command = if values.amend {
            "commit --amend"
        } else {
            "commit"
        };
        let mut lines = vec![
            "Dry run - commands that would be executed:".into(),
            "  git add .".into(),
            format!(
                "  git {command} -m {:?} (author/committer date: {date})",
                values.message
            ),
        ];
        if args.push {
            lines.push(format!("  git push origin {}", values.branch));
        }
        return Ok(lines);
    }
    let config = config::load()?;
    let account = active_account(&config);
    // Check the push login before committing, so a wrong token never leaves a commit behind.
    if let (Some(account), true) = (account, args.push) {
        accounts::verify_login(&account.github_username).context("Not committed")?;
    }
    // An amended commit needs a forced push: decide before amending, so a refused push
    // (protected branch) leaves the repository untouched. No terminal: never asked.
    if values.amend && args.push {
        let verdict = policy::check(
            &config,
            &policy::Op::ForcePush {
                remote: REMOTE,
                branch: &values.branch,
            },
        );
        if let PushGate::Refuse(message) = force_push_gate(&verdict, false) {
            bail!("push refused: {message} (nothing was amended)");
        }
    }
    let (identity, login) = identity_and_login(account);
    let date = format!("{} {}", values.date, values.time);

    git::add_all().context("Staging all files failed")?;
    let backup = if values.amend { amend_backup()? } else { None };
    git::commit(&values.message, &date, values.amend, identity.as_ref())?;
    config::save(&Config {
        last_date: date.clone(),
        last_branch: values.branch.clone(),
        last_message: values.message.clone(),
        ..config.clone()
    })?;
    let mut lines = Vec::new();
    if !args.push {
        lines.push(format!(
            "Done. commit ({date}) -> local only (add --push to push)"
        ));
        lines.extend(backup_line(backup.as_deref()));
        return Ok(lines);
    }
    git::push(&values.branch, values.amend, login).context("Committed locally, but push failed")?;
    lines.push(format!(
        "Done. commit ({date}) -> push origin/{}",
        values.branch
    ));
    lines.extend(backup_line(backup.as_deref()));
    Ok(lines)
}

fn finalize(
    values: &mut Values,
    config: &mut Config,
    account: Option<&accounts::Account>,
    force_push: &mut bool,
    staged_only: bool,
) -> Result<Step> {
    if let Some(problem) = first_problem(values) {
        return Ok(Step::Stay(Some(problem.into())));
    }
    if let Err(error) = git::check_branch_name(&values.branch) {
        return Ok(Step::Stay(Some(error.to_string())));
    }
    let (add_all, staging_note) = staging(staged_only);
    // Check the push login before committing, so a wrong token never leaves a commit behind.
    if let Some(account) = account {
        if let Err(error) = accounts::verify_login(&account.github_username) {
            return Ok(Step::Stay(Some(format!("Not committed: {error}"))));
        }
    }

    let (identity, login) = identity_and_login(account);

    let date = format!("{} {}", values.date, values.time);
    let mut summary = vec![
        screen::accent("Final summary"),
        format!("  Date:   {date}"),
        format!("  Branch: {}", values.branch),
        format!("  Msg:    {}", preview(&values.message, 60)),
    ];
    if values.amend {
        summary.push("  Mode:   amend last commit".into());
        if let Some(id) = &identity {
            summary.push(format!(
                "  Mode:   amend keeps the original author; committer is {}",
                id.name
            ));
        }
    }
    summary.extend(staging_note.map(String::from));
    if values.dry_run {
        summary.push("  Mode:   dry run".into());
    }
    if identity.is_some() {
        let mut keys = vec!["user.name", "user.email"];
        if login.is_some() {
            keys.push("credential.https://github.com.username");
        }
        for key in keys {
            if git::has_local_config(key) {
                summary.push(screen::warning(format!(
                    "This repo sets its own {key}; gct overrides it for this commit."
                )));
            }
        }
    }
    if !input::confirm(&summary, "Proceed with these actions?", true)? {
        return Ok(Step::Stay(None));
    }

    if values.dry_run {
        let command = if values.amend {
            "commit --amend"
        } else {
            "commit"
        };
        let mut lines = vec!["Dry run - commands that would be executed:".to_string()];
        if add_all {
            lines.push("  git add .".into());
        }
        lines.push(format!(
            "  git {command} -m {:?} (author/committer date: {date})",
            values.message
        ));
        return Ok(Step::Finish(lines));
    }

    // An amended commit can only go up with a forced push. When the policy refuses that
    // (protected branch), say so BEFORE amending and amend only on an explicit yes.
    let push_refused = if values.amend {
        match amend_push_refusal(config, &values.branch) {
            Some(message) => {
                let context = vec![screen::warning(format!(
                    "The amended commit cannot be pushed to {REMOTE}/{}: push refused: {message}",
                    values.branch
                ))];
                match input::confirm(&context, "Amend locally only (no push)?", false) {
                    Ok(true) => Some(message),
                    Ok(false) => {
                        return Ok(Step::Stay(Some(format!(
                            "Not amended: push refused: {message}"
                        ))))
                    }
                    Err(error) if input::is_cancel(&error) => {
                        return Ok(Step::Stay(Some(format!(
                            "Not amended: push refused: {message}"
                        ))))
                    }
                    Err(error) => return Err(error),
                }
            }
            None => None,
        }
    } else {
        None
    };

    if add_all {
        // A jump from a repository mode runs this flow at the repository root; stage the
        // folder gct was started in, as when Commit is opened directly.
        let folder = current_staging_dir();
        if let Err(error) = working("Staging all files...", || {
            match &folder {
                Some(folder) => git::with_ctx(folder, Vec::new(), git::add_all),
                None => git::add_all(),
            }
            .context("Staging all files failed")
        }) {
            return stay(error, "");
        }
    }
    let backup = if values.amend {
        match working("Backing up the last commit...", amend_backup) {
            Ok(backup) => backup,
            Err(error) => return stay(error, "Commit failed: "),
        }
    } else {
        None
    };
    let backup_note = backup_line(backup.as_deref());
    if let Err(error) = working("Creating commit...", || {
        git::commit(&values.message, &date, values.amend, identity.as_ref())
    }) {
        return stay(error, "Commit failed: ");
    }
    // Keep the in-memory config current so later account switches do not save stale values.
    config.last_date = date.clone();
    config.last_branch = values.branch.clone();
    config.last_message = values.message.clone();
    config::save(config)?;
    // The commit exists now: a retry must push it, never amend it a second time.
    let amended = values.amend;
    values.amend = false;

    screen::set_mood(Mood::Happy);
    // Ctrl+C at the push question means "keep the local commit", not an error.
    let mut created = vec![screen::success("Commit created.")];
    created.extend(backup_note.clone());
    // Already known to be refused (and the user chose local only): do not ask.
    let push = push_refused.is_none()
        && match input::confirm(&created, "Push to GitHub?", true) {
            Ok(answer) => answer,
            Err(error) if input::is_cancel(&error) => false,
            Err(error) => return Err(error),
        };
    // Appended to notices that stay in the menu, so the backup name is never lost.
    let backup_suffix = backup_note
        .as_deref()
        .map_or_else(String::new, |line| format!(" {line}"));
    let outcome = if push {
        if amended {
            let gate = match tui_force_gate(config, &values.branch) {
                Err(error) if input::is_cancel(&error) => Ok(Some("force push skipped".into())),
                other => other,
            };
            if let Some(reason) = gate? {
                *force_push = true;
                return Ok(Step::Stay(Some(format!(
                    "Committed locally, but {reason}.{backup_suffix}"
                ))));
            }
        }
        if let Err(error) = working(format!("Pushing to origin/{}...", values.branch), || {
            git::push(&values.branch, amended, login)
        }) {
            if error.is::<JobPanic>() {
                return Err(error);
            }
            *force_push = amended;
            return Ok(Step::Stay(Some(format!(
                "Committed locally, but push failed: {}. Use \"Push only\" to retry.{backup_suffix}",
                masked(&error)
            ))));
        }
        format!("Done. commit -> push origin/{}", values.branch)
    } else if let Some(message) = &push_refused {
        format!("Done. commit -> local only (push refused: {message})")
    } else {
        "Done. commit -> local only (no push)".to_string()
    };
    screen::set_mood(Mood::Happy);
    let mut done = vec![outcome];
    done.extend(backup_note);
    let shown: Vec<String> = done.iter().map(screen::success).collect();
    input::wait_key(&shown, "Press any key to exit")?;
    Ok(Step::Finish(done))
}

fn main() {
    // Restore the terminal before the panic message prints, so it is not lost on the alternate screen.
    let default_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        screen::restore();
        default_hook(info);
    }));

    let _ = START_DIR.set(std::env::current_dir().ok());
    match run() {
        Ok(summary) => {
            for line in summary {
                println!("{line}");
            }
        }
        Err(error) if input::is_cancel(&error) => {
            println!("Cancelled.");
            std::process::exit(130);
        }
        Err(error) => {
            eprintln!("Error: {}", masked(&error));
            std::process::exit(1);
        }
    }
}

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

    #[test]
    fn mode_flags_map_to_registered_modes() {
        let flags = [
            "account", "settings", "hub", "commit", "stage", "status", "sync", "log", "stash",
            "undo", "tag",
        ];
        for flag in flags {
            let args = Args::parse_from(["gct".to_string(), format!("--{flag}")]);
            assert_eq!(requested_mode(&args).unwrap().map(|m| m.name()), Some(flag));
        }
        let args = Args::parse_from(["gct", "--mode", " Rescue "]);
        assert_eq!(
            requested_mode(&args).unwrap().map(|m| m.name()),
            Some("undo")
        );
        let error = requested_mode(&Args::parse_from(["gct", "--mode", "x"])).unwrap_err();
        assert!(error.to_string().contains(&Mode::names()));
        assert!(requested_mode(&Args::parse_from(["gct"]))
            .unwrap()
            .is_none());
    }

    #[test]
    fn staged_only_skips_add_all() {
        assert_eq!(staging(false), (true, None));
        let (add_all, note) = staging(true);
        assert!(!add_all);
        assert!(note.unwrap().contains("commit staged changes only"));
    }

    #[test]
    fn force_push_gate_by_policy() {
        let deny = Verdict::Deny("main is protected".into());
        assert_eq!(
            force_push_gate(&deny, true),
            PushGate::Refuse("main is protected".into())
        );
        assert_eq!(
            force_push_gate(&deny, false),
            PushGate::Refuse("main is protected".into())
        );
        assert_eq!(force_push_gate(&Verdict::Danger, true), PushGate::Ask);
        assert_eq!(force_push_gate(&Verdict::Danger, false), PushGate::Go);
        assert_eq!(force_push_gate(&Verdict::Allow, true), PushGate::Go);
        assert!(matches!(
            force_push_gate(&Verdict::Typed("x".into()), false),
            PushGate::Refuse(_)
        ));
        assert_eq!(
            force_push_gate(&Verdict::Typed("x".into()), true),
            PushGate::Ask
        );
        // With the default protected branches: main/master are refused without a terminal.
        let cfg = Config::default();
        let check = |branch: &str| {
            force_push_gate(
                &policy::check(
                    &cfg,
                    &policy::Op::ForcePush {
                        remote: REMOTE,
                        branch,
                    },
                ),
                false,
            )
        };
        assert!(matches!(check("main"), PushGate::Refuse(_)));
        assert!(matches!(check("master"), PushGate::Refuse(_)));
        assert_eq!(check("feat/x"), PushGate::Go);
        assert!(force_push_command("feat").contains("--force-if-includes"));
        // The TUI asks this before amending: protected branches are refused up front.
        assert!(amend_push_refusal(&cfg, "main").is_some());
        assert!(amend_push_refusal(&cfg, "master").is_some());
        assert_eq!(amend_push_refusal(&cfg, "feat/x"), None);
    }

    #[test]
    fn staging_dir_only_restores_a_subfolder_after_a_root_jump() {
        let root = Path::new("/r");
        let sub = Path::new("/r/a/b");
        // Jumped from a repository mode: cwd is the root, gct started in a subfolder.
        assert_eq!(staging_dir(Some(sub), root, root), Some(sub.to_path_buf()));
        // Commit opened directly / from the Hub: cwd is still the start folder.
        assert_eq!(staging_dir(Some(sub), sub, root), None);
        // Started at the root: nothing to change.
        assert_eq!(staging_dir(Some(root), root, root), None);
        // Start folder outside this repository (Start mode moved to another one).
        assert_eq!(staging_dir(Some(Path::new("/other")), root, root), None);
        assert_eq!(staging_dir(Some(Path::new("/rx")), root, root), None);
        assert_eq!(staging_dir(None, root, root), None);
    }

    #[test]
    fn amend_backup_saves_head_and_skips_unborn() {
        let repo = testutil::TempRepo::new(2);
        let head = repo.git(&["rev-parse", "HEAD"]);
        let refname = repo.run(amend_backup).unwrap().unwrap();
        assert!(
            refname.starts_with("refs/gct/backup/") && refname.ends_with("-amend"),
            "{refname}"
        );
        assert_eq!(repo.git(&["rev-parse", &refname]), head);
        assert!(backup_line(Some(&refname)).unwrap().contains(&refname));
        let unborn = testutil::TempRepo::new(0);
        assert_eq!(unborn.run(amend_backup).unwrap(), None);
        assert_eq!(backup_line(None), None);
    }

    #[test]
    fn masked_hides_tokens_in_errors() {
        let error = anyhow!("fatal: unable to access 'https://me:ghp_secret123@github.com/x.git'");
        let text = masked(&error);
        assert!(!text.contains("ghp_secret123"), "{text}");
    }
}