git-custom-cli 2.3.1

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
mod accounts;
mod config;
mod git;
mod gitconfig;
mod input;
mod mascot;
mod model;
#[path = "terminal.rs"]
mod screen;

use anyhow::{anyhow, bail, Context, Result};
use clap::Parser;
use mascot::Mood;
use model::{first_problem, initial_values, preview, set_keymap, Config, Values};
use std::io::{stdin, stdout, IsTerminal};

#[derive(Parser, Debug)]
#[command(name = "gct", version, about = "Fast Git commit TUI")]
struct Args {
    /// 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."#;

/// A background job panicked; the panic hook already restored the terminal, so this is fatal.
#[derive(Debug)]
struct JobPanic;

impl std::fmt::Display for JobPanic {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "git step panicked")
    }
}

impl std::error::Error for JobPanic {}

/// 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}{error:#}"))))
}

/// 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);
    }
    if !stdin().is_terminal() || !stdout().is_terminal() {
        bail!("gct needs an interactive terminal; run it directly in a shell");
    }
    if args.account {
        let _terminal = screen::Guard::enter()?;
        let mut config = config::load()?;
        apply_theme(&config);
        // Save before propagating any error, so a Ctrl+C after a switch keeps the snapshot.
        let result = input::accounts_screen(&mut config);
        config::save(&config)?;
        result?;
        return Ok(vec![]);
    }

    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 config = config::load()?;
    set_keymap(config.keys.clone());
    apply_theme(&config);
    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 _terminal = screen::Guard::enter()?;

    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(&mut 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(&mut config, &label) {
                            notice = Some(error.to_string());
                        } else {
                            config::save(&config)?;
                        }
                    }
                    Some(input::Pick::GitDefault) => {
                        accounts::deactivate(&mut 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, &mut config, account.as_ref(), &mut force_push)? {
                    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()));
    }
    let force = values.amend || *force_push;
    let question = if force {
        format!("Push to origin/{branch} with --force-with-lease (amended commit)?")
    } else {
        format!("Push to origin/{branch}?")
    };
    match input::confirm(&[], &question, 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: {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> {
    const FRAMES: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
    screen::set_mood(Mood::Thinking);
    std::thread::scope(|scope| {
        let handle = scope.spawn(job);
        let mut tick = 0;
        while !handle.is_finished() {
            let line = format!("{} {}", FRAMES[tick % FRAMES.len()], message.as_ref());
            let _ = screen::draw(&[screen::accent(line)], "Please wait...", None);
            tick += 1;
            std::thread::sleep(std::time::Duration::from_millis(80));
        }
        handle.join().map_err(|_| anyhow::Error::new(JobPanic))?
    })
}

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);
        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}");
    }
    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")?;
    }
    let (identity, login) = identity_and_login(account);
    let date = format!("{} {}", values.date, values.time);

    git::run(&["add", "."]).context("Staging all files failed")?;
    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()
    })?;
    if !args.push {
        return Ok(vec![format!(
            "Done. commit ({date}) -> local only (add --push to push)"
        )]);
    }
    git::push(&values.branch, values.amend, login).context("Committed locally, but push failed")?;
    Ok(vec![format!(
        "Done. commit ({date}) -> push origin/{}",
        values.branch
    )])
}

fn finalize(
    values: &mut Values,
    config: &mut Config,
    account: Option<&accounts::Account>,
    force_push: &mut bool,
) -> Result<Step> {
    if let Some(problem) = first_problem(values) {
        return Ok(Step::Stay(Some(problem.into())));
    }
    // 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
            ));
        }
    }
    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"
        };
        return Ok(Step::Finish(vec![
            "Dry run - commands that would be executed:".into(),
            "  git add .".into(),
            format!(
                "  git {command} -m {:?} (author/committer date: {date})",
                values.message
            ),
        ]));
    }

    if let Err(error) = working("Staging all files...", || {
        git::run(&["add", "."]).context("Staging all files failed")
    }) {
        return stay(error, "");
    }
    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 push = match input::confirm(
        &[screen::success("Commit created.")],
        "Push to GitHub?",
        true,
    ) {
        Ok(answer) => answer,
        Err(error) if input::is_cancel(&error) => false,
        Err(error) => return Err(error),
    };
    let outcome = if push {
        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: {error:#}. Use \"Push only\" to retry."
            ))));
        }
        format!("Done. commit -> push origin/{}", values.branch)
    } else {
        "Done. commit -> local only (no push)".to_string()
    };
    screen::set_mood(Mood::Happy);
    input::wait_key(&[screen::success(&outcome)], "Press any key to exit")?;
    Ok(Step::Finish(vec![outcome]))
}

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);
    }));

    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: {error:#}");
            std::process::exit(1);
        }
    }
}