mod accounts;
mod cmdlog;
mod config;
mod diff;
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;
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 {
#[arg(long)]
settings: bool,
#[arg(long)]
hub: bool,
#[arg(long, value_name = "NAME")]
mode: Option<String>,
#[arg(long)]
commit: bool,
#[arg(long)]
stage: bool,
#[arg(long)]
status: bool,
#[arg(long)]
sync: bool,
#[arg(long)]
log: bool,
#[arg(long)]
stash: bool,
#[arg(long)]
undo: bool,
#[arg(long)]
tag: bool,
#[arg(long, conflicts_with = "clear_config")]
account: bool,
#[arg(long)]
clear_config: bool,
#[arg(long)]
agent: bool,
#[arg(short = 'd', long)]
date: Option<String>,
#[arg(short = 't', long)]
time: Option<String>,
#[arg(short = 'b', long)]
branch: Option<String>,
#[arg(short = 'm', long)]
message: Option<String>,
#[arg(long = "ml", allow_hyphen_values = true)]
ml: Option<String>,
#[arg(long)]
push: bool,
#[arg(
long,
conflicts_with_all = ["push", "amend", "dry_run", "message", "ml", "date", "time"]
)]
push_only: bool,
#[arg(long)]
amend: bool,
#[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."#;
fn stay(error: anyhow::Error, prefix: &str) -> Result<Step> {
if error.is::<JobPanic>() {
return Err(error);
}
Ok(Step::Stay(Some(format!("{prefix}{}", masked(&error)))))
}
fn masked(error: &anyhow::Error) -> String {
cmdlog::mask(&format!("{error:#}"))
}
fn staging(staged_only: bool) -> (bool, Option<&'static str>) {
if staged_only {
(false, Some(" Mode: commit staged changes only"))
} else {
(true, None)
}
}
static START_DIR: std::sync::OnceLock<Option<PathBuf>> = std::sync::OnceLock::new();
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())
}
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()?;
staging_dir(Some(&canonical), &cwd, &root).map(|_| start.clone())
}
#[derive(Debug, PartialEq, Eq)]
enum PushGate {
Go,
Ask,
Refuse(String),
}
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}"
)
}
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()))
}
}
}
}
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,
}
}
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}"))
}
enum Step {
Stay(Option<String>),
Finish(Vec<String>),
}
fn run() -> Result<Vec<String>> {
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);
}
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)
}
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)))
}
fn run_accounts(config: &mut Config) -> Result<()> {
let result = input::accounts_screen(config);
config::save(config)?;
result
}
fn run_commit_tui(config: &mut Config) -> Result<Vec<String>> {
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");
}
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;
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()?;
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,
});
}
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)
}
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 {
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)));
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
}
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))
}
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)
}
fn direct_commit(args: Args) -> Result<Vec<String>> {
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");
}
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}");
}
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);
if let (Some(account), true) = (account, args.push) {
accounts::verify_login(&account.github_username).context("Not committed")?;
}
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);
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));
}
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 {
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: ");
}
config.last_date = date.clone();
config.last_branch = values.branch.clone();
config.last_message = values.message.clone();
config::save(config)?;
let amended = values.amend;
values.amend = false;
screen::set_mood(Mood::Happy);
let mut created = vec![screen::success("Commit created.")];
created.extend(backup_note.clone());
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),
};
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() {
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
);
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"));
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");
assert_eq!(staging_dir(Some(sub), root, root), Some(sub.to_path_buf()));
assert_eq!(staging_dir(Some(sub), sub, root), None);
assert_eq!(staging_dir(Some(root), root, root), None);
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}");
}
}