pub mod branch;
pub mod commands;
pub mod compare;
pub mod conflicts;
pub mod files;
pub mod gitcfg;
pub mod guide;
pub mod hub;
pub mod ignore;
pub mod log;
pub mod settings;
pub mod stage;
pub mod start;
pub mod stash;
pub mod status;
pub mod sync;
pub mod tag;
pub mod timetravel;
pub mod undo;
use crate::{input, mascot::Mood, model::Config, repo_state, screen, ui};
use anyhow::Result;
use std::sync::atomic::{AtomicBool, Ordering};
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Group {
Start,
Everyday,
History,
Fix,
Release,
Setup,
}
impl Group {
pub const ALL: [Group; 6] = [
Group::Start,
Group::Everyday,
Group::History,
Group::Fix,
Group::Release,
Group::Setup,
];
pub fn title(&self) -> &'static str {
match self {
Group::Start => "Start",
Group::Everyday => "Everyday",
Group::History => "History",
Group::Fix => "Fix",
Group::Release => "Release",
Group::Setup => "Setup",
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Tier {
Basic,
Advanced,
}
pub struct ModeInfo {
pub name: &'static str,
pub aliases: &'static [&'static str],
pub title: &'static str,
pub description: &'static str,
pub group: Group,
pub tier: Tier,
pub needs_repo: bool,
pub run: fn(&mut Config) -> Result<Vec<String>>,
}
fn unit(result: Result<()>) -> Result<Vec<String>> {
result.map(|()| Vec::new())
}
pub(crate) static STAGED_ONLY: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);
pub static REGISTRY: &[ModeInfo] = &[
ModeInfo {
name: "commit",
aliases: &[],
title: "Commit",
description: "Dated commits: date, time, branch, message, push",
group: Group::Everyday,
tier: Tier::Basic,
needs_repo: false,
run: |c| crate::run_commit_tui(c),
},
ModeInfo {
name: "account",
aliases: &[],
title: "Accounts",
description: "Saved GitHub accounts and the active identity",
group: Group::Setup,
tier: Tier::Basic,
needs_repo: false,
run: |c| unit(crate::run_accounts(c)),
},
ModeInfo {
name: "settings",
aliases: &[],
title: "Settings",
description: "Default mode, experience, safety and theme",
group: Group::Setup,
tier: Tier::Basic,
needs_repo: false,
run: |c| unit(settings::run(c)),
},
ModeInfo {
name: "hub",
aliases: &[],
title: "Hub",
description: "Launcher for every mode",
group: Group::Setup,
tier: Tier::Basic,
needs_repo: false,
run: |c| unit(hub::run(c)),
},
ModeInfo {
name: "commands",
aliases: &[],
title: "Commands",
description: "Every git command gct ran in this session",
group: Group::Setup,
tier: Tier::Advanced,
needs_repo: false,
run: |c| unit(commands::run(c)),
},
ModeInfo {
name: "status",
aliases: &[],
title: "Status",
description: "Where you are: branch, upstream and changes",
group: Group::Everyday,
tier: Tier::Basic,
needs_repo: true,
run: |c| unit(status::run(c)),
},
ModeInfo {
name: "guide",
aliases: &[],
title: "Guide",
description: "What to do next, explained step by step",
group: Group::Start,
tier: Tier::Basic,
needs_repo: false,
run: |c| unit(guide::run(c)),
},
ModeInfo {
name: "stage",
aliases: &[],
title: "Stage",
description: "Pick files and hunks for the next commit; view diffs",
group: Group::Everyday,
tier: Tier::Basic,
needs_repo: true,
run: |c| unit(stage::run(c)),
},
ModeInfo {
name: "branch",
aliases: &[],
title: "Branches",
description: "Create, switch, rename, merge and delete branches",
group: Group::Everyday,
tier: Tier::Basic,
needs_repo: true,
run: |c| unit(branch::run(c)),
},
ModeInfo {
name: "sync",
aliases: &[],
title: "Sync",
description: "Fetch, pull and push; manage remotes",
group: Group::Everyday,
tier: Tier::Basic,
needs_repo: true,
run: |c| unit(sync::run(c)),
},
ModeInfo {
name: "stash",
aliases: &[],
title: "Stash",
description: "Put work aside and bring it back later",
group: Group::Everyday,
tier: Tier::Advanced,
needs_repo: true,
run: |c| unit(stash::run(c)),
},
ModeInfo {
name: "tag",
aliases: &[],
title: "Tags",
description: "Mark releases: list, create, push and delete tags",
group: Group::Release,
tier: Tier::Advanced,
needs_repo: true,
run: |c| unit(tag::run(c)),
},
ModeInfo {
name: "log",
aliases: &[],
title: "Log",
description: "Browse and search commit history",
group: Group::History,
tier: Tier::Basic,
needs_repo: true,
run: |c| unit(log::run(c)),
},
ModeInfo {
name: "files",
aliases: &[],
title: "Files",
description: "Browse files and see who changed each line",
group: Group::History,
tier: Tier::Advanced,
needs_repo: true,
run: |c| unit(files::run(c)),
},
ModeInfo {
name: "compare",
aliases: &[],
title: "Compare",
description: "Compare two branches or commits",
group: Group::History,
tier: Tier::Advanced,
needs_repo: true,
run: |c| unit(compare::run(c)),
},
ModeInfo {
name: "undo",
aliases: &["rescue"],
title: "Undo",
description: "Undo recent actions and recover lost work",
group: Group::Fix,
tier: Tier::Basic,
needs_repo: true,
run: |c| unit(undo::run(c)),
},
ModeInfo {
name: "conflicts",
aliases: &["resolve"],
title: "Conflicts",
description: "Resolve merge conflicts file by file",
group: Group::Fix,
tier: Tier::Basic,
needs_repo: true,
run: |c| unit(conflicts::run(c)),
},
ModeInfo {
name: "ignore",
aliases: &[],
title: "Ignore",
description: "Keep files out of git with .gitignore",
group: Group::Setup,
tier: Tier::Advanced,
needs_repo: true,
run: |c| unit(ignore::run(c)),
},
ModeInfo {
name: "config",
aliases: &[],
title: "Git config",
description: "Your name, email and common git settings",
group: Group::Setup,
tier: Tier::Advanced,
needs_repo: true,
run: |c| unit(gitcfg::run(c)),
},
ModeInfo {
name: "timetravel",
aliases: &[],
title: "Time travel",
description: "Change the dates of existing commits (no rebase)",
group: Group::Fix,
tier: Tier::Advanced,
needs_repo: true,
run: |c| unit(timetravel::run(c)),
},
ModeInfo {
name: "start",
aliases: &[],
title: "Start",
description: "Create a new repository or clone one",
group: Group::Start,
tier: Tier::Basic,
needs_repo: false,
run: |c| unit(start::run(c)),
},
];
#[derive(Clone, Copy)]
pub struct Mode(pub &'static ModeInfo);
impl PartialEq for Mode {
fn eq(&self, other: &Self) -> bool {
self.0.name == other.0.name
}
}
impl Eq for Mode {}
impl std::fmt::Debug for Mode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Mode({})", self.0.name)
}
}
impl Mode {
pub fn parse(value: &str) -> Option<Mode> {
let value = value.trim();
REGISTRY
.iter()
.find(|info| {
info.name.eq_ignore_ascii_case(value)
|| info
.aliases
.iter()
.any(|alias| alias.eq_ignore_ascii_case(value))
})
.map(Mode)
}
pub fn from_config(value: &str) -> Mode {
Mode::parse(value).unwrap_or(Mode(®ISTRY[0]))
}
pub fn names() -> String {
REGISTRY
.iter()
.map(|info| info.name)
.collect::<Vec<_>>()
.join(", ")
}
pub fn all() -> impl Iterator<Item = Mode> {
REGISTRY.iter().map(Mode)
}
pub fn name(&self) -> &'static str {
self.0.name
}
pub fn title(&self) -> &'static str {
self.0.title
}
pub fn description(&self) -> &'static str {
self.0.description
}
pub fn info(&self) -> &'static ModeInfo {
self.0
}
}
pub fn start(mode: Mode, config: &mut Config) -> Result<Vec<String>> {
let explicit = explicit_mode_flag(std::env::args().skip(1));
let mode = if !explicit && mode.info().needs_repo && !repo_state::in_repo() {
Mode(®ISTRY[0])
} else {
mode
};
let _terminal = screen::Guard::enter()?;
run_mode(mode, config)
}
fn explicit_mode_flag(args: impl Iterator<Item = String>) -> bool {
const FLAGS: [&str; 12] = [
"--mode",
"--hub",
"--settings",
"--account",
"--commit",
"--stage",
"--status",
"--sync",
"--log",
"--stash",
"--undo",
"--tag",
];
args.take_while(|arg| arg != "--")
.any(|arg| FLAGS.contains(&arg.as_str()) || arg.starts_with("--mode="))
}
thread_local! {
static OPEN_MODES: std::cell::RefCell<Vec<&'static str>> = const { std::cell::RefCell::new(Vec::new()) };
}
struct OpenGuard;
impl OpenGuard {
fn push(name: &'static str) -> OpenGuard {
OPEN_MODES.with(|stack| stack.borrow_mut().push(name));
OpenGuard
}
}
impl Drop for OpenGuard {
fn drop(&mut self) {
OPEN_MODES.with(|stack| {
stack.borrow_mut().pop();
});
}
}
fn is_open(stack: &[&str], name: &str) -> bool {
stack.contains(&name)
}
fn open_modes() -> Vec<&'static str> {
OPEN_MODES.with(|stack| stack.borrow().clone())
}
fn repo_root(ok: bool, toplevel: &str) -> Option<std::path::PathBuf> {
let toplevel = toplevel.trim_end_matches(['\r', '\n']);
(ok && !toplevel.trim().is_empty()).then(|| std::path::PathBuf::from(toplevel))
}
struct RootDir(Option<std::path::PathBuf>);
impl RootDir {
fn enter() -> RootDir {
let out = crate::git::git_raw(&["rev-parse", "--show-toplevel"], &Default::default());
let root = out
.ok()
.and_then(|out| repo_root(out.ok(), &String::from_utf8_lossy(&out.stdout)));
let (Some(root), Ok(previous)) = (root, std::env::current_dir()) else {
return RootDir(None);
};
if previous == root || std::env::set_current_dir(&root).is_err() {
return RootDir(None);
}
RootDir(Some(previous))
}
}
impl Drop for RootDir {
fn drop(&mut self) {
if let Some(previous) = self.0.take() {
let _ = std::env::set_current_dir(previous);
}
}
}
const MIN_GIT: (u32, u32, u32) = (2, 30, 0);
static VERSION_CHECKED: AtomicBool = AtomicBool::new(false);
pub fn run_mode(mode: Mode, config: &mut Config) -> Result<Vec<String>> {
screen::set_mood(Mood::Idle);
let _open = OpenGuard::push(mode.name());
if !mode.info().needs_repo {
return (mode.info().run)(config);
}
if !repo_state::in_repo() {
not_a_repo(mode)?;
return Ok(Vec::new());
}
if !VERSION_CHECKED.swap(true, Ordering::Relaxed) {
if let Some(problem) = version_problem(crate::git::version().ok()) {
ui::notice("Old git version", &[problem])?;
}
}
let _root = RootDir::enter();
(mode.info().run)(config)
}
pub(crate) fn not_a_repo(mode: Mode) -> Result<()> {
ui::notice(
"Not a git repository",
&[
format!("{} works inside a git repository.", mode.title()),
String::new(),
"cd into a project folder, or".into(),
"Open Start mode (gct --mode start) to create or clone one".into(),
],
)
}
fn version_problem(version: Option<(u32, u32, u32)>) -> Option<String> {
let (major, minor, patch) = MIN_GIT;
match version {
Some(found) if found >= MIN_GIT => None,
Some((a, b, c)) => Some(format!(
"gct needs git {major}.{minor}.{patch} or newer for some actions; you have {a}.{b}.{c}."
)),
None => Some("Could not read the git version; some actions may fail.".into()),
}
}
pub fn open(name: &str, cfg: &mut Config) -> Result<()> {
let Some(mode) = Mode::parse(name) else {
return ui::notice(
"Unknown mode",
&[format!(
"'{}' is not a mode. Valid modes: {}",
name.trim(),
Mode::names()
)],
);
};
if is_open(&open_modes(), mode.name()) {
return ui::notice(
mode.title(),
&[format!(
"{} is already open. Press Esc to go back to it.",
mode.title()
)],
);
}
let result = run_mode(mode, cfg);
show_result(mode, result)
}
pub(crate) fn show_result(mode: Mode, result: Result<Vec<String>>) -> Result<()> {
match result {
Ok(lines) if lines.is_empty() => Ok(()),
Ok(lines) => ui::notice(mode.title(), &lines),
Err(error) if input::is_cancel(&error) => Ok(()),
Err(error) if error.is::<ui::JobPanic>() => Err(error),
Err(error) => {
screen::set_mood(Mood::Error);
ui::notice(
&format!("{} failed", mode.title()),
&[screen::danger(format!("{error:#}"))],
)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn mode(name: &str) -> Mode {
Mode::parse(name).unwrap()
}
#[test]
fn parse_names() {
assert_eq!(Mode::parse("stage"), Some(mode("stage")));
assert_eq!(Mode::parse(" LoG \n").map(|m| m.name()), Some("log"));
assert_eq!(Mode::parse("Account").map(|m| m.name()), Some("account"));
assert_eq!(Mode::parse("rescue").map(|m| m.name()), Some("undo"));
assert_eq!(
Mode::parse(" RESOLVE ").map(|m| m.name()),
Some("conflicts")
);
assert_eq!(Mode::parse("config").map(|m| m.title()), Some("Git config"));
assert_eq!(Mode::parse("nonsense"), None);
assert_eq!(Mode::parse(""), None);
for mode in Mode::all() {
assert_eq!(Mode::parse(mode.name()), Some(mode));
assert_eq!(Mode::parse(&mode.name().to_uppercase()), Some(mode));
assert!(!mode.title().is_empty() && !mode.description().is_empty());
}
}
#[test]
fn names_are_unique() {
let mut names: Vec<&str> = REGISTRY
.iter()
.flat_map(|info| std::iter::once(info.name).chain(info.aliases.iter().copied()))
.collect();
let total = names.len();
names.sort_unstable();
names.dedup();
assert_eq!(names.len(), total);
assert!(Mode::names().starts_with("commit, account, settings, hub"));
assert_eq!(
Mode::names(),
"commit, account, settings, hub, commands, status, guide, stage, branch, sync, stash, \
tag, log, files, compare, undo, conflicts, ignore, config, timetravel, start"
);
assert!(!Mode::names().contains("rescue"));
}
#[test]
fn default_falls_back_to_commit() {
assert_eq!(Mode::from_config(""), mode("commit"));
assert_eq!(Mode::from_config("bogus"), mode("commit"));
assert_eq!(Mode::from_config("Hub"), mode("hub"));
assert_eq!(
Mode::from_config(&Config::default().default_mode),
mode("commit")
);
}
#[test]
fn registry_groups_tiers_and_repo_needs() {
let check = |names: &[&str], f: &dyn Fn(&ModeInfo) -> bool| {
for name in names {
assert!(f(mode(name).info()), "{name}");
}
};
check(&["start", "guide"], &|i| i.group == Group::Start);
check(
&["commit", "status", "stage", "branch", "sync", "stash"],
&|i| i.group == Group::Everyday,
);
check(&["log", "files", "compare"], &|i| i.group == Group::History);
check(&["undo", "conflicts", "timetravel"], &|i| {
i.group == Group::Fix
});
check(&["tag"], &|i| i.group == Group::Release);
check(
&["account", "settings", "hub", "commands", "ignore", "config"],
&|i| i.group == Group::Setup,
);
let basic = [
"commit",
"status",
"guide",
"start",
"stage",
"branch",
"sync",
"log",
"undo",
"conflicts",
"account",
"settings",
"hub",
];
for m in Mode::all() {
let expect = if basic.contains(&m.name()) {
Tier::Basic
} else {
Tier::Advanced
};
assert_eq!(m.info().tier, expect, "{}", m.name());
}
let no_repo = [
"commit", "account", "settings", "hub", "start", "commands", "guide",
];
for m in Mode::all() {
assert_eq!(
m.info().needs_repo,
!no_repo.contains(&m.name()),
"{}",
m.name()
);
}
assert_eq!(REGISTRY.len(), 21);
}
#[test]
fn version_gate() {
assert_eq!(version_problem(Some((2, 30, 0))), None);
assert_eq!(version_problem(Some((3, 0, 0))), None);
assert!(version_problem(Some((2, 29, 9)))
.unwrap()
.contains("2.29.9"));
assert!(version_problem(None).is_some());
}
#[test]
fn repo_root_choice() {
assert_eq!(
repo_root(true, "C:/work/project\n"),
Some(std::path::PathBuf::from("C:/work/project"))
);
assert_eq!(
repo_root(true, "/home/u/my repo\r\n"),
Some("/home/u/my repo".into())
);
assert_eq!(repo_root(true, "/srv/ünï"), Some("/srv/ünï".into()));
assert_eq!(repo_root(false, "/somewhere"), None);
assert_eq!(repo_root(true, ""), None);
assert_eq!(repo_root(true, " \n"), None);
}
#[test]
fn root_dir_of_a_subfolder_is_the_toplevel() {
let repo = crate::testutil::TempRepo::new(1);
repo.write("sub/deeper/x.txt", "x");
let top = crate::git::with_ctx(&repo.path().join("sub/deeper"), repo.env(), || {
let out = crate::git::git_raw(&["rev-parse", "--show-toplevel"], &Default::default())
.unwrap();
repo_root(out.ok(), &String::from_utf8_lossy(&out.stdout))
});
let top = std::fs::canonicalize(top.unwrap()).unwrap();
assert_eq!(top, std::fs::canonicalize(repo.path()).unwrap());
}
#[test]
fn open_stack_blocks_loops_and_pops_on_exit() {
assert!(open_modes().is_empty());
{
let _hub = OpenGuard::push("hub");
let _conflicts = OpenGuard::push("conflicts");
{
let _sync = OpenGuard::push("sync");
assert_eq!(open_modes(), ["hub", "conflicts", "sync"]);
assert!(is_open(&open_modes(), "conflicts"));
assert!(is_open(&open_modes(), "sync"));
assert!(!is_open(&open_modes(), "log"));
}
assert!(!is_open(&open_modes(), "sync"), "popped when sync returned");
let result = std::panic::catch_unwind(|| {
let _log = OpenGuard::push("log");
panic!("mode crashed");
});
assert!(result.is_err());
assert_eq!(open_modes(), ["hub", "conflicts"], "popped on panic too");
}
assert!(open_modes().is_empty());
assert!(!is_open(&[], "hub"));
}
#[test]
fn explicit_mode_flags() {
let args = |list: &[&str]| list.iter().map(|s| s.to_string()).collect::<Vec<_>>();
assert!(!explicit_mode_flag(args(&[]).into_iter()));
assert!(explicit_mode_flag(args(&["--mode", "stage"]).into_iter()));
assert!(explicit_mode_flag(args(&["--mode=log"]).into_iter()));
assert!(explicit_mode_flag(args(&["--stage"]).into_iter()));
assert!(explicit_mode_flag(args(&["--hub"]).into_iter()));
assert!(!explicit_mode_flag(args(&["--", "--stage"]).into_iter()));
assert!(!explicit_mode_flag(args(&["--modes"]).into_iter()));
}
}