use crate::{
git::{self, Opts},
input,
model::Config,
policy::{self, Op, Verdict},
repo_state::{self, Head},
safety, screen, ui,
};
use anyhow::{bail, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResetMode {
Soft,
Mixed,
Keep,
Hard,
}
impl ResetMode {
fn flag(self) -> &'static str {
match self {
ResetMode::Soft => "--soft",
ResetMode::Mixed => "--mixed",
ResetMode::Keep => "--keep",
ResetMode::Hard => "--hard",
}
}
fn effect(self) -> &'static str {
match self {
ResetMode::Soft => "Your files are untouched; the undone changes stay staged.",
ResetMode::Mixed => "Your files are untouched; the undone changes become unstaged.",
ResetMode::Keep => {
"Your uncommitted changes are kept; git refuses (and changes nothing) if one would be overwritten."
}
ResetMode::Hard => {
"Tracked files are overwritten. gct saves uncommitted tracked changes as a WIP backup first, and refuses if an untracked file would be overwritten."
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UndoAction {
Reset {
target: String,
mode: ResetMode,
},
DeleteRoot,
Switch {
to: String,
detach: bool,
},
Unknown,
}
fn is_oid(s: &str) -> bool {
(s.len() == 40 || s.len() == 64) && s.bytes().all(|b| b.is_ascii_hexdigit())
}
pub fn classify(subject: &str) -> UndoAction {
let s = subject.trim();
let reset = |mode| UndoAction::Reset {
target: "HEAD@{1}".into(),
mode,
};
if s.starts_with("commit (initial):") {
return UndoAction::DeleteRoot;
}
if s.starts_with("commit:") || s.starts_with("commit (amend):") {
return reset(ResetMode::Soft);
}
if s.starts_with("reset: moving to") {
return reset(ResetMode::Keep);
}
if let Some(rest) = s.strip_prefix("checkout: moving from ") {
return match rest.split_once(" to ") {
Some((from, _)) if !from.trim().is_empty() => UndoAction::Switch {
to: from.trim().into(),
detach: is_oid(from.trim()),
},
_ => UndoAction::Unknown,
};
}
if let Some((_, after)) = s.split_once("(finish): returning to ") {
let branch = after
.trim()
.strip_prefix("refs/heads/")
.unwrap_or(after.trim());
if branch.is_empty() || branch.contains(char::is_whitespace) {
return UndoAction::Unknown;
}
return UndoAction::Reset {
target: format!("{branch}@{{1}}"),
mode: ResetMode::Keep,
};
}
let keep = [
"merge ",
"merge:",
"pull",
"cherry-pick",
"revert",
"commit (merge)",
"commit (cherry-pick)",
];
if keep.iter().any(|p| s.starts_with(p)) && !s.contains("(start)") && !s.contains("(pick)") {
return reset(ResetMode::Keep);
}
UndoAction::Unknown
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReflogEntry {
pub oid: String,
pub selector: String,
pub subject: String,
pub when: String,
}
pub const REFLOG_FORMAT: &str = "--format=%H%x1f%gd%x1f%gs%x1f%cr";
pub fn parse_reflog(text: &str) -> Vec<ReflogEntry> {
text.lines()
.filter_map(|line| {
let mut parts = line.trim_end_matches('\r').splitn(4, '\u{1f}');
let oid = parts.next()?.trim();
if oid.is_empty() {
return None;
}
Some(ReflogEntry {
oid: oid.into(),
selector: parts.next().unwrap_or("").into(),
subject: parts.next().unwrap_or("").into(),
when: parts.next().unwrap_or("").into(),
})
})
.collect()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Symptom {
WrongBranch,
UndoCommitKeep,
Amend,
Detached,
MergeMess,
LostCommits,
PushedSecret,
}
const SYMPTOMS: [(Symptom, &str); 7] = [
(
Symptom::WrongBranch,
"I committed to the wrong branch (not pushed)",
),
(
Symptom::UndoCommitKeep,
"Undo my last commit but keep my changes",
),
(
Symptom::Amend,
"I forgot a file / want a new message for my last commit",
),
(Symptom::Detached, "I'm on a detached HEAD"),
(Symptom::MergeMess, "I merged or pulled and it's a mess"),
(Symptom::LostCommits, "I lost commits / reset by mistake"),
(
Symptom::PushedSecret,
"I pushed a secret (password, key, token)",
),
];
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PlanParams {
pub branch: String,
pub count: usize,
pub root: bool,
pub files: Vec<String>,
pub message: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlanStep {
pub explain: String,
pub argv: Vec<String>,
pub destructive: bool,
}
fn step(explain: &str, argv: &[&str], destructive: bool) -> PlanStep {
PlanStep {
explain: explain.into(),
argv: argv.iter().map(|a| a.to_string()).collect(),
destructive,
}
}
pub fn plan_for(symptom: Symptom, p: &PlanParams) -> Vec<PlanStep> {
match symptom {
Symptom::WrongBranch => {
let back = format!("HEAD~{}", p.count);
vec![
step(&format!("Create branch '{}' at your current commit, so the commits are kept there.", p.branch), &["branch", &p.branch], false),
step(&format!("Move this branch back {} commit(s), keeping your uncommitted changes.", p.count), &["reset", "--keep", &back], true),
step(&format!("Switch to '{}' where the commits now live.", p.branch), &["switch", &p.branch], false),
]
}
Symptom::UndoCommitKeep if p.root => vec![step(
"Remove the first commit; its files stay staged.",
&["update-ref", "-d", "HEAD"],
true,
)],
Symptom::UndoCommitKeep => vec![step(
"Undo the last commit; its changes stay staged.",
&["reset", "--soft", "HEAD~1"],
true,
)],
Symptom::Amend => {
let mut steps = Vec::new();
if !p.files.is_empty() {
let mut argv = vec!["add".to_string(), "--".to_string()];
argv.extend(p.files.iter().cloned());
steps.push(PlanStep {
explain: format!("Stage the forgotten file(s): {}.", p.files.join(", ")),
argv,
destructive: false,
});
}
let mut argv: Vec<String> = vec!["commit".into(), "--amend".into()];
match &p.message {
Some(m) => argv.extend(["-m".to_string(), m.clone()]),
None => argv.push("--no-edit".into()),
}
steps.push(PlanStep {
explain: "Replace the last commit with a fixed one.".into(),
argv,
destructive: true,
});
steps
}
Symptom::Detached => vec![step(
&format!("Create branch '{}' here and switch to it, so these commits are not lost.", p.branch),
&["switch", "-c", &p.branch],
false,
)],
Symptom::MergeMess => vec![step(
"Go back to where you were before the merge/pull (ORIG_HEAD), keeping uncommitted changes.",
&["reset", "--keep", "ORIG_HEAD"],
true,
)],
Symptom::LostCommits => vec![step(
"Open the reflog: every place HEAD has been. Pick the entry before the mistake and reset or branch there.",
&[],
false,
)],
Symptom::PushedSecret => vec![
step("Rotate the secret FIRST (revoke the key, change the password). Once pushed, assume it is leaked; rewriting history does not un-leak it.", &[], false),
step("Remove the secret from the file and commit that change as a new commit.", &[], false),
step("Add the file to .gitignore (Ignore mode) and load the secret from an environment variable instead.", &[], false),
],
}
}
fn cmdline(argv: &[String]) -> String {
let mut out = String::from("git");
for a in argv {
out.push(' ');
if a.is_empty() || a.contains(char::is_whitespace) {
out.push_str(&format!("\"{a}\""));
} else {
out.push_str(a);
}
}
out
}
pub fn render_plan(steps: &[PlanStep]) -> Vec<String> {
let mut lines = Vec::new();
for (i, s) in steps.iter().enumerate() {
lines.push(format!("{}. {}", i + 1, s.explain));
if !s.argv.is_empty() {
lines.push(format!(" $ {}", cmdline(&s.argv)));
lines.push(if s.destructive {
" Can I undo this? Yes: gct saves a backup ref first (Undo & Rescue > Restore from a gct backup).".into()
} else {
" Can I undo this? Yes, nothing is lost by this step.".into()
});
}
}
lines
}
fn rank(v: &Verdict) -> u8 {
match v {
Verdict::Allow => 0,
Verdict::Confirm => 1,
Verdict::Danger => 2,
Verdict::Typed(_) => 3,
Verdict::Deny(_) => 4,
}
}
fn stricter(a: Verdict, b: Verdict) -> Verdict {
if rank(&b) > rank(&a) {
b
} else {
a
}
}
fn reset_verdict(cfg: &Config, mode: ResetMode, branch: &str, published: bool) -> Verdict {
let rewrite = policy::check(cfg, &Op::RewriteHistory { branch, published });
if mode == ResetMode::Hard {
stricter(rewrite, policy::check(cfg, &Op::ResetHard))
} else {
rewrite
}
}
pub fn older_than(when: &str, now: chrono::NaiveDateTime, days: i64) -> bool {
chrono::NaiveDateTime::parse_from_str(when, "%Y-%m-%d %H:%M:%S")
.is_ok_and(|t| now.signed_duration_since(t) > chrono::Duration::days(days))
}
fn name_ok(name: &str) -> bool {
!name.is_empty() && !name.starts_with('-') && !name.contains(char::is_whitespace)
}
fn short(oid: &str) -> &str {
oid.get(..7).unwrap_or(oid)
}
pub fn any_published(total: usize, unpushed: usize) -> bool {
unpushed < total
}
pub fn colliding_paths(
untracked: &[String],
target_files: &[String],
ignore_case: bool,
) -> Vec<String> {
let norm = |s: &str| {
if ignore_case {
s.to_lowercase()
} else {
s.to_string()
}
};
let set: std::collections::HashSet<String> = target_files.iter().map(|t| norm(t)).collect();
let dirs: std::collections::HashSet<String> = set
.iter()
.flat_map(|t| t.match_indices('/').map(move |(i, _)| t[..i].to_string()))
.collect();
untracked
.iter()
.filter(|u| {
let u = norm(u);
if dirs.contains(&u) {
return true;
}
let mut prefix = u.as_str();
loop {
if set.contains(prefix) {
return true;
}
match prefix.rfind('/') {
Some(i) => prefix = &prefix[..i],
None => return false,
}
}
})
.cloned()
.collect()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RestoreKind {
Head,
Stash,
Tag,
Branch,
}
pub fn restore_kind(label: &str) -> RestoreKind {
let base = match label.rsplit_once('-') {
Some((b, n)) if !b.is_empty() && !n.is_empty() && n.bytes().all(|c| c.is_ascii_digit()) => {
b
}
_ => label,
};
match base {
"stash-drop" | "stash-clear" | "wip" => RestoreKind::Stash,
"branch-delete" => RestoreKind::Branch,
b if b.starts_with("tag-delete") => RestoreKind::Tag,
_ => RestoreKind::Head,
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Outcome {
pub backup: Option<String>,
pub wip: Option<String>,
pub commands: Vec<String>,
}
impl Outcome {
fn lines(&self) -> Vec<String> {
let mut out: Vec<String> = self.commands.iter().map(|c| format!("$ {c}")).collect();
out.push(String::new());
if let Some(b) = &self.backup {
out.push(screen::success(format!(
"Backup of the previous state: {b}"
)));
out.push(screen::muted(
"Undo the undo: Undo & Rescue > Restore from a gct backup.",
));
}
if let Some(w) = &self.wip {
out.push(screen::success(format!(
"Uncommitted changes saved as: {w}"
)));
out.push(screen::muted(
"Bring them back: Restore from a gct backup > the 'wip' entry.",
));
}
out
}
}
fn ok(args: &[&str]) -> Result<String> {
git::git_ok(args, &Opts::default())
}
fn succeeds(args: &[&str]) -> bool {
git::git_raw(args, &Opts::default()).is_ok_and(|o| o.ok())
}
fn resolve(rev: &str) -> Result<String> {
let out = git::git_raw(
&[
"rev-parse",
"--verify",
"--quiet",
&format!("{rev}^{{commit}}"),
],
&Opts::default(),
)?;
let oid = out.text().trim().to_string();
if !out.ok() || oid.is_empty() {
bail!("'{rev}' does not point to a commit");
}
Ok(oid)
}
fn backup_head(label: &str) -> Result<Option<String>> {
if !succeeds(&["rev-parse", "--verify", "--quiet", "HEAD"]) {
return Ok(None);
}
safety::backup(label, "HEAD").map(Some)
}
fn z_list(args: &[&str]) -> Result<Vec<String>> {
let out = git::git_raw(args, &Opts::default())?;
if !out.ok() {
bail!("git {} failed: {}", args.join(" "), out.stderr.trim());
}
Ok(out
.text()
.split('\0')
.filter(|s| !s.is_empty())
.map(String::from)
.collect())
}
fn untracked_collisions(oid: &str) -> Result<Vec<String>> {
let untracked = z_list(&["ls-files", "--others", "--exclude-standard", "-z"])?;
if untracked.is_empty() {
return Ok(Vec::new());
}
let target = z_list(&["ls-tree", "-r", "-z", "--name-only", oid])?;
let ignore_case =
ok(&["config", "--bool", "core.ignorecase"]).is_ok_and(|v| v.trim() == "true");
Ok(colliding_paths(&untracked, &target, ignore_case))
}
fn prepare_hard(oid: &str) -> Result<Option<String>> {
if !ok(&["ls-files", "-u"])?.trim().is_empty() {
bail!(
"there are unresolved conflicts (a merge, rebase or cherry-pick is in progress) and gct cannot snapshot them, \
so it refuses reset --hard. Finish or abort the operation in Conflicts mode first, or use --keep."
);
}
let colliding = untracked_collisions(oid)?;
if !colliding.is_empty() {
let mut list = colliding
.iter()
.take(10)
.cloned()
.collect::<Vec<_>>()
.join(", ");
if colliding.len() > 10 {
list.push_str(&format!(" (+{} more)", colliding.len() - 10));
}
bail!(
"reset --hard would overwrite {} untracked file(s) that also exist in the target: {list}. \
Move, rename or commit them first, or use --keep (git refuses instead of overwriting).",
colliding.len()
);
}
let dirty = tree_dirty()?;
let sha = match ok(&["stash", "create"]) {
Ok(sha) => sha.trim().to_string(),
Err(e) => bail!("could not save your uncommitted changes as a WIP backup ({e}); refusing reset --hard. Use --keep, or commit them first."),
};
match (sha.is_empty(), dirty) {
(false, _) => Ok(Some(safety::backup("wip", &sha)?)),
(true, true) => bail!("could not save your uncommitted changes as a WIP backup; refusing reset --hard. Use --keep, or commit them first."),
(true, false) => Ok(None),
}
}
fn current_branch() -> String {
git::current_branch()
.ok()
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "HEAD".into())
}
fn head_published() -> bool {
safety::is_published("HEAD").unwrap_or(false)
}
fn tree_dirty() -> Result<bool> {
Ok(!ok(&["status", "--porcelain", "--untracked-files=no"])?
.trim()
.is_empty())
}
fn rev_count(args: &[&str]) -> Result<usize> {
let text = ok(args)?;
text.trim()
.parse()
.map_err(|_| anyhow::anyhow!("unexpected rev-list output: {text}"))
}
pub fn rewinds_published(target: Option<&str>) -> Result<bool> {
if !succeeds(&["rev-parse", "--verify", "--quiet", "HEAD"])
|| ok(&["remote"])?.trim().is_empty()
{
return Ok(false);
}
let exclude = target
.and_then(|t| resolve(t).ok())
.map(|oid| format!("^{oid}"));
let mut args = vec!["rev-list", "--count", "HEAD"];
if let Some(x) = &exclude {
args.push(x);
}
let total = rev_count(&args)?;
args.extend(["--not", "--remotes"]);
Ok(any_published(total, rev_count(&args)?))
}
fn detached_orphans() -> Result<Vec<String>> {
if succeeds(&["symbolic-ref", "-q", "HEAD"])
|| !succeeds(&["rev-parse", "--verify", "--quiet", "HEAD"])
{
return Ok(Vec::new());
}
let text = ok(&[
"rev-list",
"HEAD",
"--not",
"--branches",
"--tags",
"--remotes",
])?;
Ok(text
.lines()
.map(str::trim)
.filter(|l| !l.is_empty())
.map(String::from)
.collect())
}
fn newest_head_subject() -> String {
git::git_raw(&["reflog", "-n1", "--format=%gs"], &Opts::default())
.ok()
.filter(|o| o.ok())
.map(|o| o.text().trim().to_string())
.unwrap_or_default()
}
pub fn reset_to(target: &str, mode: ResetMode, label: &str) -> Result<Outcome> {
let oid = resolve(target)?;
let wip = if mode == ResetMode::Hard {
prepare_hard(&oid)?
} else {
None
};
let mut outcome = Outcome {
backup: backup_head(label)?,
wip,
..Outcome::default()
};
ok(&["reset", "-q", mode.flag(), &oid])?;
outcome
.commands
.push(format!("git reset {} {target}", mode.flag()));
Ok(outcome)
}
pub fn undo_root() -> Result<Outcome> {
resolve("HEAD")?;
if succeeds(&["rev-parse", "--verify", "--quiet", "HEAD~1"]) {
bail!("the last commit has a parent; it is not the first commit");
}
let backup = backup_head("undo-initial-commit")?;
ok(&["update-ref", "-d", "HEAD"])?;
Ok(Outcome {
backup,
commands: vec!["git update-ref -d HEAD".into()],
..Outcome::default()
})
}
pub fn undo_last(action: &UndoAction) -> Result<Outcome> {
match action {
UndoAction::Reset { target, mode } => reset_to(target, *mode, "undo"),
UndoAction::DeleteRoot => undo_root(),
UndoAction::Switch { to, detach } => {
if to.starts_with('-') {
bail!("'{to}' is not a branch or commit");
}
let backup = if detached_orphans()?.is_empty() {
None
} else {
Some(safety::backup("detached", "HEAD")?)
};
let mut argv = vec!["switch"];
if *detach {
argv.push("--detach");
}
argv.push(to);
ok(&argv)?;
Ok(Outcome {
backup,
commands: vec![format!("git {}", argv.join(" "))],
..Outcome::default()
})
}
UndoAction::Unknown => bail!("gct does not know how to undo this action"),
}
}
pub fn execute_plan(label: &str, steps: &[PlanStep]) -> Result<Outcome> {
let mut outcome = Outcome::default();
if steps.iter().any(|s| s.destructive) {
outcome.backup = backup_head(label)?;
}
for s in steps.iter().filter(|s| !s.argv.is_empty()) {
let args: Vec<&str> = s.argv.iter().map(String::as_str).collect();
ok(&args)?;
outcome.commands.push(cmdline(&s.argv));
}
Ok(outcome)
}
fn check_new_branch(name: &str) -> Result<()> {
if !name_ok(name) || !succeeds(&["check-ref-format", "--branch", name]) {
bail!("'{name}' is not a valid branch name");
}
if succeeds(&[
"rev-parse",
"--verify",
"--quiet",
&format!("refs/heads/{name}"),
]) {
bail!("a branch named '{name}' already exists");
}
Ok(())
}
pub fn fix_wrong_branch(name: &str, count: usize) -> Result<Outcome> {
check_new_branch(name)?;
if count == 0 {
bail!("nothing to move (0 commits)");
}
resolve(&format!("HEAD~{count}"))
.map_err(|_| anyhow::anyhow!("this branch has fewer than {} commits to keep", count + 1))?;
if safety::is_published(&format!("HEAD~{}", count - 1)).unwrap_or(false) {
bail!("those commits are already pushed; moving them would rewrite shared history");
}
let params = PlanParams {
branch: name.into(),
count,
..PlanParams::default()
};
execute_plan("wrong-branch", &plan_for(Symptom::WrongBranch, ¶ms))
}
pub fn amend_last(files: &[String], message: Option<String>) -> Result<Outcome> {
resolve("HEAD")?;
if head_published() {
bail!("the last commit is already pushed; amend would rewrite shared history. Revert it instead (Log mode).");
}
let params = PlanParams {
files: files.to_vec(),
message,
..PlanParams::default()
};
execute_plan("amend", &plan_for(Symptom::Amend, ¶ms))
}
pub fn restore_backup(refname: &str, mode: ResetMode) -> Result<Outcome> {
reset_to(refname, mode, "before-restore")
}
fn backup_oid(refname: &str) -> Result<String> {
if !refname.starts_with("refs/gct/backup/") {
bail!("{refname} is not a gct backup");
}
let out = git::git_raw(
&["rev-parse", "--verify", "--quiet", refname],
&Opts::default(),
)?;
let oid = out.text().trim().to_string();
if !out.ok() || oid.is_empty() {
bail!("backup {refname} no longer exists");
}
Ok(oid)
}
pub fn restore_stash(refname: &str, apply: bool) -> Result<Outcome> {
let oid = backup_oid(refname)?;
if !succeeds(&["rev-parse", "--verify", "--quiet", &format!("{oid}^2")]) {
bail!("backup {refname} is not a stash (it has no index parent); restore it as a branch instead");
}
let command = if apply {
ok(&["stash", "apply", &oid])?;
format!("git stash apply {}", short(&oid))
} else {
let message = format!(
"gct restored {}",
refname.trim_start_matches("refs/gct/backup/")
);
ok(&["stash", "store", "-m", &message, &oid])?;
format!("git stash store -m \"{message}\" {}", short(&oid))
};
Ok(Outcome {
commands: vec![command],
..Outcome::default()
})
}
pub fn tag_name_hint(refname: &str) -> Option<String> {
ok(&["for-each-ref", "--format=%(tag)", refname])
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
}
pub fn restore_tag(refname: &str, name: &str) -> Result<Outcome> {
let oid = backup_oid(refname)?;
let full = format!("refs/tags/{name}");
if !name_ok(name) || !succeeds(&["check-ref-format", &full]) {
bail!("'{name}' is not a valid tag name");
}
if succeeds(&["rev-parse", "--verify", "--quiet", &full]) {
bail!("a tag named '{name}' already exists");
}
ok(&["update-ref", "-m", "gct restore tag", &full, &oid, ""])?;
Ok(Outcome {
commands: vec![format!("git update-ref {full} {}", short(&oid))],
..Outcome::default()
})
}
pub fn restore_branch(refname: &str, name: &str) -> Result<Outcome> {
let oid = backup_oid(refname)?;
resolve(&oid)?;
check_new_branch(name)?;
ok(&["branch", name, &oid])?;
Ok(Outcome {
commands: vec![format!("git branch {name} {}", short(&oid))],
..Outcome::default()
})
}
const MENU: [&str; 5] = [
"Undo my last git action",
"I made a mistake (guided fix)",
"Browse the reflog",
"Restore from a gct backup",
"Manage gct backups",
];
pub fn run(config: &mut Config) -> Result<()> {
loop {
let context = ui::explain(
config,
&[
"Something went wrong? Pick what you want to fix.",
"gct saves a backup before every change here, so you can always undo the undo.",
],
);
match ui::choose("Undo & Rescue", &context, &MENU)? {
Some(0) => undo_last_flow(config)?,
Some(1) => wizard(config)?,
Some(2) => reflog_browser(config)?,
Some(3) => backups_browser(config, true)?,
Some(4) => backups_browser(config, false)?,
_ => return Ok(()),
}
}
}
fn report(cfg: &Config, title: &str, result: Result<Outcome>, explain: &[&str]) -> Result<()> {
match result {
Ok(outcome) => {
let mut lines = outcome.lines();
lines.extend(ui::explain(cfg, explain));
ui::notice(title, &lines)
}
Err(e) if input::is_cancel(&e) => Err(e),
Err(e) => ui::notice(
&format!("{title}: failed"),
&[
screen::danger(e.to_string()),
String::new(),
screen::muted(
"Nothing was lost: a backup ref (if made) is listed under Manage gct backups.",
),
],
),
}
}
fn pick_mode(title: &str, target: &str, suggested: ResetMode) -> Result<Option<ResetMode>> {
if !matches!(suggested, ResetMode::Keep | ResetMode::Hard) || !tree_dirty().unwrap_or(true) {
return Ok(Some(suggested));
}
let context = vec![screen::warning("You have uncommitted changes.")];
let keep =
format!("Keep them: git reset --keep {target} (refuses if they would be overwritten)");
let hard = format!("Discard them: git reset --hard {target} (WIP snapshot first)");
Ok(match ui::choose(title, &context, &[&keep, &hard])? {
Some(0) => Some(ResetMode::Keep),
Some(1) => Some(ResetMode::Hard),
_ => None,
})
}
fn move_verdict(cfg: &Config, mode: ResetMode, target: Option<&str>) -> Verdict {
reset_verdict(
cfg,
mode,
¤t_branch(),
rewinds_published(target).unwrap_or(true),
)
}
fn gate_reset(
cfg: &Config,
mode: ResetMode,
target: Option<&str>,
what: &str,
command: &str,
) -> Result<bool> {
ui::gate(cfg, &move_verdict(cfg, mode, target), what, command)
}
fn undo_last_flow(cfg: &mut Config) -> Result<()> {
if let Some(op) = repo_state::load()?.op {
let context = vec![
screen::warning(format!("A {op:?} is in progress.")),
"Undoing now could mix up its half-finished state. Finish or abort it first in Conflicts mode.".into(),
];
if ui::choose(
"Undo last action",
&context,
&["Open Conflicts mode", "Back"],
)? == Some(0)
{
crate::modes::open("conflicts", cfg)?;
}
return Ok(());
}
let subject = newest_head_subject();
if subject.is_empty() {
return ui::notice(
"Nothing to undo",
&["This repository has no history yet. Make a commit first.".into()],
);
}
let mut action = classify(&subject);
if action == UndoAction::Unknown {
let context = vec![
format!("Last action: {subject}"),
"gct does not recognise it. You can reset to the previous entry (HEAD@{1}).".into(),
];
let opts = [
"git reset --keep HEAD@{1} (keep local changes)",
"git reset --soft HEAD@{1}",
"git reset --mixed HEAD@{1}",
"git reset --hard HEAD@{1} (WIP snapshot first)",
];
let modes = [
ResetMode::Keep,
ResetMode::Soft,
ResetMode::Mixed,
ResetMode::Hard,
];
let Some(i) = ui::choose("Undo last action", &context, &opts)? else {
return Ok(());
};
action = UndoAction::Reset {
target: "HEAD@{1}".into(),
mode: modes[i.min(3)],
};
}
if let UndoAction::Reset { target, mode } = &action {
let Some(m) = pick_mode("Undo last action", target, *mode)? else {
return Ok(());
};
action = UndoAction::Reset {
target: target.clone(),
mode: m,
};
}
let mut orphan_warning = None;
let (command, meaning, verdict) = match &action {
UndoAction::Reset { target, mode } => (
format!("git reset {} {target}", mode.flag()),
mode.effect().to_string(),
move_verdict(cfg, *mode, Some(target)),
),
UndoAction::DeleteRoot => (
"git update-ref -d HEAD".into(),
"Removes your first commit; its files stay staged so you can commit again.".into(),
move_verdict(cfg, ResetMode::Soft, None),
),
UndoAction::Switch { to, detach } => {
let orphans = detached_orphans().unwrap_or_default();
if !orphans.is_empty() {
orphan_warning = Some(screen::warning(format!(
"! {} commit(s) here are on no branch. gct saves them as backup refs/gct/backup/<time>-detached before switching.",
orphans.len()
)));
}
(
format!("git switch {}{to}", if *detach { "--detach " } else { "" }),
format!("Go back to {to}. Your uncommitted changes come along (git refuses if they conflict)."),
policy::check(cfg, &Op::Plain),
)
}
UndoAction::Unknown => return Ok(()),
};
let mut lines = vec![
format!("Last action: {subject}"),
String::new(),
format!("$ {command}"),
meaning,
"Can I undo the undo? Yes: gct saves a backup ref of HEAD first (shown afterwards).".into(),
];
lines.extend(orphan_warning);
lines.extend(ui::explain(cfg, &["The reflog is git's diary of where HEAD has been; HEAD@{1} is the step before the last one."]));
if verdict == Verdict::Allow && !ui::confirm_action(cfg, &lines.join("\n"), &command)? {
return Ok(());
}
if !ui::gate(cfg, &verdict, &lines.join("\n"), &command)? {
return Ok(());
}
let result = ui::git_job("Undoing...", || undo_last(&action));
report(
cfg,
"Undone",
result,
&["Your project is back to how it was before that action."],
)
}
fn wizard(cfg: &mut Config) -> Result<()> {
let labels: Vec<&str> = SYMPTOMS.iter().map(|(_, l)| *l).collect();
let context = ui::explain(
cfg,
&["Pick what happened. gct shows the plan before anything runs."],
);
let Some(i) = ui::choose("I made a mistake", &context, &labels)? else {
return Ok(());
};
match SYMPTOMS[i].0 {
Symptom::WrongBranch => wrong_branch(cfg),
Symptom::UndoCommitKeep => undo_commit_keep(cfg),
Symptom::Amend => amend_flow(cfg),
Symptom::Detached => detached_flow(cfg),
Symptom::MergeMess => merge_mess(cfg),
Symptom::LostCommits => reflog_browser(cfg),
Symptom::PushedSecret => ui::notice(
"I pushed a secret",
&render_plan(&plan_for(Symptom::PushedSecret, &PlanParams::default())),
),
}
}
fn approve_plan(
cfg: &Config,
title: &str,
intro: &[String],
steps: &[PlanStep],
reset: Option<(ResetMode, Option<&str>)>,
) -> Result<bool> {
let mut lines = intro.to_vec();
lines.extend(render_plan(steps));
let command = steps
.iter()
.filter(|s| !s.argv.is_empty())
.map(|s| cmdline(&s.argv))
.collect::<Vec<_>>()
.join(" && ");
let what = format!("{title}\n{}", lines.join("\n"));
match reset {
Some((m, target)) => gate_reset(cfg, m, target, &what, &command),
None => ui::confirm_action(cfg, &what, &command),
}
}
fn ask_branch_name(prompt: &str) -> Result<Option<String>> {
loop {
let Some(name) = ui::ask(prompt, "")? else {
return Ok(None);
};
let name = name.trim().to_string();
match check_new_branch(&name) {
Ok(()) => return Ok(Some(name)),
Err(e) => ui::notice("Branch name", &[e.to_string()])?,
}
}
}
fn wrong_branch(cfg: &Config) -> Result<()> {
let counted = git::git_raw(&["rev-list", "--count", "@{u}..HEAD"], &Opts::default())
.ok()
.filter(|o| o.ok())
.and_then(|o| o.text().trim().parse::<usize>().ok());
let count = match counted {
Some(n) if n > 0 => n,
_ => {
let Some(text) = ui::ask(
"How many of your last commits belong on another branch?",
"1",
)?
else {
return Ok(());
};
match text.trim().parse::<usize>() {
Ok(n) if n > 0 => n,
_ => {
return ui::notice(
"Wrong branch",
&["Please enter a number like 1 or 2.".into()],
)
}
}
}
};
if safety::is_published(&format!("HEAD~{}", count - 1)).unwrap_or(false) {
return ui::notice(
"Wrong branch",
&[
screen::danger("Those commits are already pushed."),
"Moving them would rewrite shared history; gct will not do that here.".into(),
],
);
}
let log = ok(&["log", "--oneline", "-n", &count.to_string()]).unwrap_or_default();
let Some(name) = ask_branch_name("Name of the branch the commits should go to:")? else {
return Ok(());
};
let steps = plan_for(
Symptom::WrongBranch,
&PlanParams {
branch: name.clone(),
count,
..PlanParams::default()
},
);
let mut intro = vec![format!("These {count} commit(s) move to '{name}':")];
intro.extend(log.lines().map(|l| format!(" {l}")));
intro.push(String::new());
let back = format!("HEAD~{count}");
if !approve_plan(
cfg,
"Move commits to a new branch",
&intro,
&steps,
Some((ResetMode::Keep, Some(&back))),
)? {
return Ok(());
}
let result = ui::git_job("Moving commits...", || fix_wrong_branch(&name, count));
report(
cfg,
"Commits moved",
result,
&["You are now on the new branch; the old branch is back where it was before."],
)
}
fn undo_commit_keep(cfg: &Config) -> Result<()> {
if resolve("HEAD").is_err() {
return ui::notice("Undo last commit", &["There is no commit yet.".into()]);
}
let root = !succeeds(&["rev-parse", "--verify", "--quiet", "HEAD~1"]);
let steps = plan_for(
Symptom::UndoCommitKeep,
&PlanParams {
root,
..PlanParams::default()
},
);
let last = ok(&["log", "-1", "--format=%h %s"]).unwrap_or_default();
let target = (!root).then_some("HEAD~1");
if !approve_plan(
cfg,
"Undo last commit",
&[format!("Last commit: {last}"), String::new()],
&steps,
Some((ResetMode::Soft, target)),
)? {
return Ok(());
}
let result = ui::git_job("Undoing commit...", || execute_plan("undo-commit", &steps));
report(
cfg,
"Commit undone",
result,
&["Your changes are staged again; edit them and commit when ready."],
)
}
fn amend_flow(cfg: &mut Config) -> Result<()> {
if resolve("HEAD").is_err() {
return ui::notice("Fix last commit", &["There is no commit yet.".into()]);
}
if head_published() {
let context = vec![
screen::danger("Blocked: your last commit is already pushed."),
"Changing it would rewrite history other people may have.".into(),
"Instead, make a new commit with the fix, or revert the commit in Log mode.".into(),
];
if ui::choose("Fix last commit", &context, &["Open Log mode", "Back"])? == Some(0) {
crate::modes::open("log", cfg)?;
}
return Ok(());
}
let state = repo_state::load()?;
let candidates: Vec<String> = state
.entries
.iter()
.filter(|e| !e.staged() || e.unstaged())
.map(|e| e.path.clone())
.collect();
let mut files = Vec::new();
if !candidates.is_empty() {
let mut checked = vec![false; candidates.len()];
if !ui::check_list(
"Files to add to the last commit (none is fine)",
&candidates,
&mut checked,
)? {
return Ok(());
}
files = candidates
.iter()
.zip(&checked)
.filter(|(_, c)| **c)
.map(|(f, _)| f.clone())
.collect();
}
let subject = ok(&["log", "-1", "--format=%s"]).unwrap_or_default();
let Some(answer) = ui::ask("Commit message (keep it to leave unchanged):", &subject)? else {
return Ok(());
};
let message = (answer.trim() != subject.trim() && !answer.trim().is_empty())
.then(|| answer.trim().to_string());
if files.is_empty()
&& message.is_none()
&& !ok(&["diff", "--cached", "--name-only"]).is_ok_and(|s| !s.is_empty())
{
return ui::notice(
"Fix last commit",
&["Nothing to change: no files picked and the message is the same.".into()],
);
}
let steps = plan_for(
Symptom::Amend,
&PlanParams {
files: files.clone(),
message: message.clone(),
..PlanParams::default()
},
);
let parent = succeeds(&["rev-parse", "--verify", "--quiet", "HEAD~1"]).then_some("HEAD~1");
if !approve_plan(
cfg,
"Fix last commit",
&[],
&steps,
Some((ResetMode::Soft, parent)),
)? {
return Ok(());
}
let result = ui::git_job("Amending...", || amend_last(&files, message));
report(
cfg,
"Commit fixed",
result,
&["The old version of the commit is kept in the backup ref."],
)
}
fn detached_flow(cfg: &Config) -> Result<()> {
let state = repo_state::load()?;
if let Head::Branch { name, .. } | Head::Unborn { name } = &state.branch.head {
return ui::notice(
"Detached HEAD",
&[format!(
"You are on branch '{name}'; HEAD is not detached. Nothing to fix."
)],
);
}
let orphans = ok(&[
"log",
"--oneline",
"-n",
"50",
"HEAD",
"--not",
"--branches",
])
.unwrap_or_default();
let mut intro =
vec!["Commits that are on no branch (they would be lost if you switch away):".to_string()];
if orphans.trim().is_empty() {
intro.push(" (none: every commit here is already on a branch)".into());
}
intro.extend(orphans.lines().map(|l| format!(" {l}")));
intro.push(String::new());
ui::notice("Detached HEAD", &intro)?;
let Some(name) = ask_branch_name("Name for the new branch here:")? else {
return Ok(());
};
let steps = plan_for(
Symptom::Detached,
&PlanParams {
branch: name,
..PlanParams::default()
},
);
if !approve_plan(cfg, "Save detached HEAD", &intro, &steps, None)? {
return Ok(());
}
let result = ui::git_job("Creating branch...", || execute_plan("detached", &steps));
report(
cfg,
"Branch created",
result,
&["You are on a normal branch again."],
)
}
fn merge_mess(cfg: &mut Config) -> Result<()> {
if repo_state::load()?.op.is_some() {
ui::notice("Merge in progress", &["A merge/rebase/cherry-pick is still in progress. Opening Conflicts mode, where you can finish or abort it.".into()])?;
return crate::modes::open("conflicts", cfg);
}
let Ok(orig) = resolve("ORIG_HEAD") else {
return ui::notice(
"Merge or pull",
&[
"git has no record (ORIG_HEAD) of where you were before. Try Browse the reflog."
.into(),
],
);
};
let info = ok(&["log", "-1", "--format=%h %s (%cr)", &orig]).unwrap_or_default();
let steps = plan_for(Symptom::MergeMess, &PlanParams::default());
let intro = vec![
format!("Before the merge/pull you were at: {info}"),
String::new(),
];
let Some(mode) = pick_mode("Merge or pull", "ORIG_HEAD", ResetMode::Keep)? else {
return Ok(());
};
if !approve_plan(
cfg,
"Undo merge or pull",
&intro,
&steps,
Some((mode, Some(orig.as_str()))),
)? {
return Ok(());
}
let result = ui::git_job("Resetting...", || reset_to("ORIG_HEAD", mode, "undo-merge"));
report(
cfg,
"Merge undone",
result,
&["Your branch is back where it was before the merge or pull."],
)
}
fn reflog_browser(cfg: &mut Config) -> Result<()> {
let keys = [
ui::Key {
key: 'v',
label: "view",
},
ui::Key {
key: 'k',
label: "reset --keep",
},
ui::Key {
key: 'h',
label: "reset --hard",
},
ui::Key {
key: 'b',
label: "new branch",
},
ui::Key {
key: 'r',
label: "refresh",
},
];
let mut index = 0usize;
loop {
let raw = git::git_raw(&["reflog", REFLOG_FORMAT, "-n", "300"], &Opts::default())?;
let entries = if raw.ok() {
parse_reflog(&raw.text())
} else {
Vec::new()
};
if entries.is_empty() {
return ui::notice(
"Reflog",
&["The reflog is empty: make a commit first.".into()],
);
}
let rows: Vec<String> = entries
.iter()
.map(|e| {
format!(
"{:<10} {} {} {}",
e.selector,
screen::accent(short(&e.oid)),
e.subject,
screen::muted(&e.when)
)
})
.collect();
let mut header = vec![screen::muted(
"Every place HEAD has been, newest first. Enter for actions.",
)];
header.extend(ui::explain(
cfg,
&["Find the line just before your mistake and reset or branch there."],
));
let (action, i) = match ui::action_list("Reflog", &header, &rows, &keys, &mut index)? {
ui::Choice::Back => return Ok(()),
ui::Choice::Open(i) => {
let opts = [
"Show this commit",
"Reset --soft here",
"Reset --mixed here",
"Reset --keep here",
"Reset --hard here",
"New branch here",
];
let Some(o) = ui::choose(&rows[i.min(rows.len() - 1)], &[], &opts)? else {
continue;
};
(['v', 'o', 'm', 'k', 'h', 'b'][o.min(5)], i)
}
ui::Choice::Action(c, i) => (c, i),
};
let Some(entry) = entries.get(i) else {
continue;
};
let mode = match action {
'r' => continue,
'v' => {
let text = ok(&["show", "--stat", "--format=fuller", &entry.oid])
.unwrap_or_else(|e| e.to_string());
ui::pager(
&entry.selector,
&text.lines().map(String::from).collect::<Vec<_>>(),
"",
)?;
continue;
}
'b' => {
crate::modes::branch::create_at(cfg, &entry.oid)?;
continue;
}
'o' => ResetMode::Soft,
'm' => ResetMode::Mixed,
'k' => ResetMode::Keep,
_ => ResetMode::Hard,
};
let command = format!("git reset {} {}", mode.flag(), short(&entry.oid));
let mut what = vec![
format!(
"Move the current branch to {} ({}).",
entry.selector, entry.subject
),
mode.effect().into(),
];
what.push("Can I undo this? Yes: gct saves a backup ref of HEAD first.".into());
if gate_reset(cfg, mode, Some(&entry.oid), &what.join("\n"), &command)? {
let oid = entry.oid.clone();
let result = ui::git_job("Resetting...", || reset_to(&oid, mode, "reflog-reset"));
report(
cfg,
"Reset done",
result,
&["Your branch now points at the commit you picked."],
)?;
}
}
}
fn backup_subjects() -> Vec<(String, String)> {
ok(&[
"for-each-ref",
"--format=%(refname)%1f%(contents:subject)",
"refs/gct/backup/",
])
.unwrap_or_default()
.lines()
.filter_map(|l| {
l.split_once('\u{1f}')
.map(|(a, b)| (a.to_string(), b.to_string()))
})
.collect()
}
fn backups_browser(cfg: &Config, restore: bool) -> Result<()> {
let keys = [
ui::Key {
key: 'v',
label: "view",
},
ui::Key {
key: 'x',
label: "restore",
},
ui::Key {
key: 'b',
label: "as branch",
},
ui::Key {
key: 'd',
label: "delete",
},
ui::Key {
key: 'p',
label: "prune >30 days",
},
];
let title = if restore {
"Restore from a gct backup"
} else {
"gct backups"
};
let mut index = 0usize;
loop {
let list = safety::backups()?;
if list.is_empty() {
return ui::notice(
title,
&[
"No gct backups yet. gct makes one before every reset, amend or restore."
.into(),
],
);
}
let subjects = backup_subjects();
let rows: Vec<String> = list
.iter()
.map(|b| {
let subject = subjects
.iter()
.find(|(r, _)| *r == b.refname)
.map_or("", |(_, s)| s.as_str());
format!(
"{} {:<22} {} {}",
screen::muted(&b.when),
b.label,
screen::accent(short(&b.oid)),
subject
)
})
.collect();
let header = ui::explain(
cfg,
&["A backup is a saved pointer to your work before gct changed history."],
);
let (action, i) = match ui::action_list(title, &header, &rows, &keys, &mut index)? {
ui::Choice::Back => return Ok(()),
ui::Choice::Open(i) => {
let opts = [
"Restore it (branch, tag or stash, as it was backed up)",
"Restore as a new branch",
"Show its commits",
"Delete this backup",
"Prune backups older than 30 days",
];
let Some(o) = ui::choose(&rows[i.min(rows.len() - 1)], &[], &opts)? else {
continue;
};
(['x', 'b', 'v', 'd', 'p'][o.min(4)], i)
}
ui::Choice::Action(c, i) => (c, i),
};
if action == 'p' {
prune(cfg, &list)?;
continue;
}
let Some(b) = list.get(i) else { continue };
match action {
'v' => {
let text = ok(&["log", "--oneline", "-n", "30", &b.refname])
.unwrap_or_else(|e| e.to_string());
ui::pager(
&b.refname,
&text.lines().map(String::from).collect::<Vec<_>>(),
"",
)?;
}
'x' => restore_flow(cfg, b)?,
'b' => {
let Some(name) = ask_branch_name("New branch name for this backup:")? else {
continue;
};
let argv = vec!["branch".to_string(), name, b.refname.clone()];
if ui::confirm_action(cfg, "Create a branch from the backup", &cmdline(&argv))? {
let steps = [PlanStep {
explain: String::new(),
argv,
destructive: false,
}];
let result =
ui::git_job("Creating branch...", || execute_plan("branch", &steps));
report(cfg, "Branch created", result, &[])?;
}
}
'd' => {
let command = format!("git update-ref -d {}", b.refname);
if ui::gate(
cfg,
&policy::check(
cfg,
&Op::DeleteBranch {
branch: &b.refname,
merged: false,
},
),
"Delete this backup? Its commits may be lost forever.",
&command,
)? {
match safety::delete_backup(&b.refname) {
Ok(()) => ui::notice("Backup deleted", &[format!("$ {command}")])?,
Err(e) => ui::notice("Delete failed", &[screen::danger(e.to_string())])?,
}
}
}
_ => {}
}
}
}
fn restore_flow(cfg: &Config, b: &safety::Backup) -> Result<()> {
let refname = b.refname.clone();
match restore_kind(&b.label) {
RestoreKind::Head => {
let Some(mode) = pick_mode("Restore backup", &b.refname, ResetMode::Keep)? else {
return Ok(());
};
let command = format!("git reset {} {}", mode.flag(), b.refname);
let what = format!(
"Move the current branch ({}) to backup {} ({}).\n{}\nCan I undo this? Yes: gct backs up HEAD as 'before-restore' first.",
current_branch(),
b.label,
b.when,
mode.effect()
);
if gate_reset(cfg, mode, Some(&b.refname), &what, &command)? {
let result = ui::git_job("Restoring...", || restore_backup(&refname, mode));
report(
cfg,
"Backup restored",
result,
&["Your branch is back at the saved state."],
)?;
}
}
RestoreKind::Stash => {
let store = format!(
"Put it back on the stash list: git stash store {}",
short(&b.oid)
);
let apply = format!(
"Apply it to your files now: git stash apply {}",
short(&b.oid)
);
let context = vec![format!(
"Backup {} ({}) holds stashed changes.",
b.label, b.when
)];
let Some(i) = ui::choose("Restore stash backup", &context, &[&store, &apply])? else {
return Ok(());
};
let apply = i == 1;
let command = if apply {
format!("git stash apply {}", short(&b.oid))
} else {
format!("git stash store {}", short(&b.oid))
};
if ui::confirm_action(cfg, "Restore the stashed changes", &command)? {
let result = ui::git_job("Restoring...", || restore_stash(&refname, apply));
report(
cfg,
"Stash restored",
result,
&["Your stashed changes are back (see Stash mode)."],
)?;
}
}
RestoreKind::Tag => {
let hint = tag_name_hint(&b.refname).unwrap_or_default();
let Some(name) = ui::ask("Name of the tag to recreate:", &hint)? else {
return Ok(());
};
let name = name.trim().to_string();
let command = format!("git update-ref refs/tags/{name} {}", short(&b.oid));
if ui::confirm_action(
cfg,
&format!("Recreate tag '{name}' from backup {}", b.label),
&command,
)? {
let result = ui::git_job("Restoring...", || restore_tag(&refname, &name));
report(
cfg,
"Tag restored",
result,
&["The tag points at the same commit as before it was deleted."],
)?;
}
}
RestoreKind::Branch => {
let Some(name) = ask_branch_name("Name of the deleted branch to recreate:")? else {
return Ok(());
};
let command = format!("git branch {name} {}", short(&b.oid));
if ui::confirm_action(
cfg,
&format!("Recreate branch '{name}' from backup {}", b.label),
&command,
)? {
let result = ui::git_job("Restoring...", || restore_branch(&refname, &name));
report(
cfg,
"Branch restored",
result,
&["The branch is back where it was when it was deleted."],
)?;
}
}
}
Ok(())
}
fn prune(cfg: &Config, list: &[safety::Backup]) -> Result<()> {
let now = chrono::Local::now().naive_local();
let old: Vec<&safety::Backup> = list
.iter()
.filter(|b| older_than(&b.when, now, 30))
.collect();
if old.is_empty() {
return ui::notice(
"Prune backups",
&["No backup is older than 30 days.".into()],
);
}
let rows: Vec<String> = old
.iter()
.map(|b| format!("{} {} {}", b.when, b.label, short(&b.oid)))
.collect();
let mut checked = vec![true; rows.len()];
if !ui::check_list(
"Delete these backups older than 30 days?",
&rows,
&mut checked,
)? {
return Ok(());
}
let chosen: Vec<&&safety::Backup> = old
.iter()
.zip(&checked)
.filter(|(_, c)| **c)
.map(|(b, _)| b)
.collect();
if chosen.is_empty()
|| !ui::gate(
cfg,
&policy::check(cfg, &Op::DropStash),
&format!("Delete {} backup(s)?", chosen.len()),
"git update-ref -d refs/gct/backup/...",
)?
{
return Ok(());
}
let mut lines = Vec::new();
for b in chosen {
match safety::delete_backup(&b.refname) {
Ok(()) => lines.push(format!("deleted {}", b.refname)),
Err(e) => lines.push(screen::danger(format!("{}: {e}", b.refname))),
}
}
ui::notice("Prune backups", &lines)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testutil::TempRepo;
fn rs(target: &str, mode: ResetMode) -> UndoAction {
UndoAction::Reset {
target: target.into(),
mode,
}
}
#[test]
fn classify_table() {
let oid = "a".repeat(40);
let detached = format!("checkout: moving from {oid} to main");
let cases: Vec<(&str, UndoAction)> = vec![
("commit (initial): first", UndoAction::DeleteRoot),
("commit: add parser", rs("HEAD@{1}", ResetMode::Soft)),
(
"commit (amend): add parser",
rs("HEAD@{1}", ResetMode::Soft),
),
("reset: moving to HEAD~2", rs("HEAD@{1}", ResetMode::Keep)),
(
"checkout: moving from main to feature/x",
UndoAction::Switch {
to: "main".into(),
detach: false,
},
),
(
&detached,
UndoAction::Switch {
to: oid.clone(),
detach: true,
},
),
(
"merge feature: Fast-forward",
rs("HEAD@{1}", ResetMode::Keep),
),
(
"merge origin/main: Merge made by the 'ort' strategy.",
rs("HEAD@{1}", ResetMode::Keep),
),
(
"commit (merge): Merge branch 'x'",
rs("HEAD@{1}", ResetMode::Keep),
),
("pull: Fast-forward", rs("HEAD@{1}", ResetMode::Keep)),
(
"pull --rebase (finish): returning to refs/heads/dev",
rs("dev@{1}", ResetMode::Keep),
),
(
"rebase (finish): returning to refs/heads/main",
rs("main@{1}", ResetMode::Keep),
),
(
"rebase -i (finish): returning to refs/heads/feat/ü",
rs("feat/ü@{1}", ResetMode::Keep),
),
("rebase (pick): commit 3", UndoAction::Unknown),
("cherry-pick: fix typo", rs("HEAD@{1}", ResetMode::Keep)),
("revert: Revert \"x\"", rs("HEAD@{1}", ResetMode::Keep)),
("branch: Created from HEAD", UndoAction::Unknown),
("", UndoAction::Unknown),
("checkout: moving from", UndoAction::Unknown),
];
for (subject, expected) in cases {
assert_eq!(classify(subject), expected, "{subject}");
}
}
#[test]
fn parses_reflog() {
let text = "abc\u{1f}HEAD@{0}\u{1f}commit: héllo wörld\u{1f}2 minutes ago\r\n\
def\u{1f}HEAD@{1}\u{1f}checkout: moving from a to b\u{1f}1 day ago\n\n";
let e = parse_reflog(text);
assert_eq!(e.len(), 2);
assert_eq!(
e[0],
ReflogEntry {
oid: "abc".into(),
selector: "HEAD@{0}".into(),
subject: "commit: héllo wörld".into(),
when: "2 minutes ago".into()
}
);
assert_eq!(e[1].when, "1 day ago");
assert!(parse_reflog("").is_empty());
assert_eq!(parse_reflog("x\u{1f}HEAD@{0}")[0].subject, "");
}
#[test]
fn plans_per_symptom() {
let argv = |steps: &[PlanStep]| steps.iter().map(|s| s.argv.join(" ")).collect::<Vec<_>>();
let p = PlanParams {
branch: "feat".into(),
count: 2,
..PlanParams::default()
};
let wrong = plan_for(Symptom::WrongBranch, &p);
assert_eq!(
argv(&wrong),
["branch feat", "reset --keep HEAD~2", "switch feat"]
);
assert_eq!(
wrong.iter().map(|s| s.destructive).collect::<Vec<_>>(),
[false, true, false]
);
assert_eq!(
argv(&plan_for(Symptom::UndoCommitKeep, &PlanParams::default())),
["reset --soft HEAD~1"]
);
assert_eq!(
argv(&plan_for(
Symptom::UndoCommitKeep,
&PlanParams {
root: true,
..PlanParams::default()
}
)),
["update-ref -d HEAD"]
);
assert_eq!(
argv(&plan_for(Symptom::Amend, &PlanParams::default())),
["commit --amend --no-edit"]
);
let amend = PlanParams {
files: vec!["a b.txt".into(), "C:\\x\\y.rs".into()],
message: Some("new msg".into()),
..PlanParams::default()
};
let steps = plan_for(Symptom::Amend, &amend);
assert_eq!(steps[0].argv, ["add", "--", "a b.txt", "C:\\x\\y.rs"]);
assert_eq!(steps[1].argv, ["commit", "--amend", "-m", "new msg"]);
assert_eq!(cmdline(&steps[1].argv), "git commit --amend -m \"new msg\"");
assert_eq!(
argv(&plan_for(
Symptom::Detached,
&PlanParams {
branch: "save".into(),
..PlanParams::default()
}
)),
["switch -c save"]
);
assert_eq!(
argv(&plan_for(Symptom::MergeMess, &PlanParams::default())),
["reset --keep ORIG_HEAD"]
);
assert!(plan_for(Symptom::LostCommits, &PlanParams::default())
.iter()
.all(|s| s.argv.is_empty()));
let secret = plan_for(Symptom::PushedSecret, &PlanParams::default());
assert!(
secret.iter().all(|s| s.argv.is_empty()) && secret[0].explain.starts_with("Rotate")
);
let text = render_plan(&wrong).join("\n");
assert!(
text.contains("1. Create branch 'feat'")
&& text.contains("$ git reset --keep HEAD~2")
&& text.contains("Can I undo this?")
);
}
#[test]
fn verdicts_names_and_ages() {
let cfg = Config {
confirm_destructive: true,
..Config::default()
};
assert_eq!(
reset_verdict(&cfg, ResetMode::Soft, "feat", false),
Verdict::Danger
);
assert_eq!(
reset_verdict(&cfg, ResetMode::Hard, "main", true),
Verdict::Typed("main".into())
);
let off = Config {
confirm_destructive: false,
..Config::default()
};
assert_eq!(
reset_verdict(&off, ResetMode::Keep, "feat", false),
Verdict::Allow
);
assert_eq!(stricter(Verdict::Danger, Verdict::Confirm), Verdict::Danger);
assert!(!name_ok("-x") && !name_ok("") && !name_ok("a b") && name_ok("feat/x"));
let now = chrono::NaiveDateTime::parse_from_str("2026-03-01 12:00:00", "%Y-%m-%d %H:%M:%S")
.unwrap();
assert!(older_than("2026-01-01 00:00:00", now, 30));
assert!(!older_than("2026-02-20 00:00:00", now, 30));
assert!(!older_than("", now, 30));
assert_eq!(short("abcdef123456"), "abcdef1");
assert_eq!(short("ab"), "ab");
}
#[test]
fn undo_last_commit_soft_keeps_changes_staged() {
let repo = TempRepo::new(2);
repo.run(|| {
let subject = newest_head_subject();
let action = classify(&subject);
assert_eq!(action, rs("HEAD@{1}", ResetMode::Soft), "{subject}");
let out = undo_last(&action).unwrap();
assert!(out
.backup
.as_deref()
.is_some_and(|b| b.starts_with("refs/gct/backup/")));
assert_eq!(ok(&["log", "-1", "--format=%s"]).unwrap(), "commit 1");
assert_eq!(ok(&["diff", "--cached", "--name-only"]).unwrap(), "f2.txt");
});
}
#[test]
fn keep_refuses_to_overwrite_local_change() {
let repo = TempRepo::new(2);
repo.write("f2.txt", "local edit\n");
repo.run(|| {
let head = resolve("HEAD").unwrap();
assert!(reset_to("HEAD~1", ResetMode::Keep, "test").is_err());
assert_eq!(resolve("HEAD").unwrap(), head);
});
assert_eq!(
std::fs::read_to_string(repo.path().join("f2.txt")).unwrap(),
"local edit\n"
);
}
#[test]
fn hard_reset_snapshots_wip_and_restore_brings_commits_back() {
let repo = TempRepo::new(3);
repo.write("f1.txt", "wip\n");
repo.write("new.txt", "untracked\n");
repo.run(|| {
let tip = resolve("HEAD").unwrap();
let out = reset_to("HEAD~2", ResetMode::Hard, "oops").unwrap();
let wip = out.wip.unwrap();
assert_eq!(
restore_kind(
&safety::backups()
.unwrap()
.iter()
.find(|b| b.refname == wip)
.unwrap()
.label
),
RestoreKind::Stash
);
assert_eq!(ok(&["rev-list", "--count", "HEAD"]).unwrap(), "1");
let backup = out.backup.unwrap();
let restored = restore_backup(&backup, ResetMode::Keep).unwrap();
assert_eq!(resolve("HEAD").unwrap(), tip);
assert!(restored.backup.unwrap().ends_with("before-restore"));
restore_stash(&wip, true).unwrap();
});
assert_eq!(
std::fs::read_to_string(repo.path().join("new.txt")).unwrap(),
"untracked\n"
);
assert_eq!(
std::fs::read_to_string(repo.path().join("f1.txt")).unwrap(),
"wip\n"
);
}
#[test]
fn restore_kind_table() {
let cases = [
("stash-drop", RestoreKind::Stash),
("stash-drop-2", RestoreKind::Stash),
("stash-clear", RestoreKind::Stash),
("wip", RestoreKind::Stash),
("wip-3", RestoreKind::Stash),
("tag-delete", RestoreKind::Tag),
("tag-delete-remote", RestoreKind::Tag),
("tag-delete-remote-2", RestoreKind::Tag),
("branch-delete", RestoreKind::Branch),
("branch-delete-12", RestoreKind::Branch),
("timetravel", RestoreKind::Head),
("abort", RestoreKind::Head),
("undo", RestoreKind::Head),
("before-restore", RestoreKind::Head),
("detached", RestoreKind::Head),
("2", RestoreKind::Head),
("", RestoreKind::Head),
("wipe", RestoreKind::Head),
];
for (label, kind) in cases {
assert_eq!(restore_kind(label), kind, "{label}");
}
}
#[test]
fn collisions_and_published_math() {
let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
let target = s(&["a.txt", "dir/b.txt", "file", "Docs/Read Me.md"]);
let untracked = s(&[
"a.txt",
"dir/c.txt",
"file/inner.txt",
"docs/read me.md",
"other.txt",
"ü.txt",
]);
assert_eq!(
colliding_paths(&untracked, &target, false),
["a.txt", "file/inner.txt"]
);
assert_eq!(
colliding_paths(&untracked, &target, true),
["a.txt", "file/inner.txt", "docs/read me.md"]
);
assert!(colliding_paths(&[], &target, true).is_empty());
assert!(colliding_paths(&untracked, &[], false).is_empty());
let table: [(&str, &str, bool, bool); 14] = [
("a", "a/b.txt", false, true), ("a/b.txt", "a", false, true), ("x/y", "x/y/z/w.txt", false, true), ("x", "x/y/z/w.txt", false, true),
("x/y/z", "x/y/z/w.txt", false, true),
("x/y/q", "x/y/z/w.txt", false, false), ("x/y/z/w.txt/deep", "x/y/z/w.txt", false, true),
("A", "a/b.txt", false, false),
("A", "a/b.txt", true, true), ("A/B.TXT/c", "a/b.txt", true, true),
("ab", "a/b.txt", false, false), ("ü", "ü/ö.txt", false, true), ("Ü", "ü/ö.txt", true, true),
("ü/ä.txt", "ü/ö.txt", true, false),
];
for (u, t, ic, want) in table {
let got = !colliding_paths(&s(&[u]), &s(&[t]), ic).is_empty();
assert_eq!(
got, want,
"untracked {u:?} vs target {t:?} (ignore_case {ic})"
);
}
let repo = TempRepo::new(1);
repo.write("a/b.txt", "b\n");
repo.git(&["add", "."]);
repo.git(&["commit", "-q", "-m", "add a/b"]);
let old = repo.git(&["rev-parse", "HEAD"]);
repo.git(&["rm", "-q", "-r", "a"]);
repo.git(&["commit", "-q", "-m", "drop a"]);
repo.write("a", "precious\n");
assert_eq!(repo.run(|| untracked_collisions(&old).unwrap()), ["a"]);
assert!(repo.run(|| prepare_hard(&old)).is_err());
assert!(any_published(3, 2));
assert!(!any_published(3, 3));
assert!(!any_published(0, 0));
}
#[test]
fn hard_reset_refuses_to_overwrite_untracked_and_undo_of_reset_keeps() {
let repo = TempRepo::new(3);
let tip = repo.git(&["rev-parse", "HEAD"]);
repo.git(&["reset", "-q", "--hard", "HEAD~2"]);
repo.write("f3.txt", "precious\n");
repo.run(|| {
let action = classify(&newest_head_subject());
assert_eq!(action, rs("HEAD@{1}", ResetMode::Keep));
assert!(
undo_last(&action).is_err(),
"--keep must refuse to overwrite an untracked file"
);
let err = reset_to(&tip, ResetMode::Hard, "x")
.unwrap_err()
.to_string();
assert!(err.contains("untracked") && err.contains("f3.txt"), "{err}");
let backup = safety::backup("timetravel", &tip).unwrap();
assert!(restore_backup(&backup, ResetMode::Hard).is_err());
assert_eq!(ok(&["rev-list", "--count", "HEAD"]).unwrap(), "1");
});
assert_eq!(
std::fs::read_to_string(repo.path().join("f3.txt")).unwrap(),
"precious\n"
);
}
#[test]
fn hard_reset_refuses_mid_merge() {
let repo = TempRepo::new(2);
repo.git(&["checkout", "-q", "-b", "side"]);
repo.write("f1.txt", "side\n");
repo.git(&["commit", "-q", "-am", "side"]);
repo.git(&["checkout", "-q", "main"]);
repo.write("f1.txt", "main\n");
repo.git(&["commit", "-q", "-am", "main"]);
repo.run(|| {
assert!(
!git::git_raw(&["merge", "side"], &Opts::default())
.unwrap()
.ok(),
"the merge must conflict"
);
let head = resolve("HEAD").unwrap();
let err = reset_to("HEAD~1", ResetMode::Hard, "x")
.unwrap_err()
.to_string();
assert!(err.contains("Conflicts mode"), "{err}");
assert_eq!(resolve("HEAD").unwrap(), head);
assert!(safety::backups().unwrap().is_empty());
assert!(repo_state::load().unwrap().op.is_some());
});
}
#[test]
fn published_check_covers_every_dropped_commit() {
let repo = TempRepo::new(2);
repo.git(&["commit", "-q", "--allow-empty", "-m", "local 1"]);
assert!(
!repo.run(|| rewinds_published(Some("HEAD~2")).unwrap()),
"no remote: nothing is published"
);
let repo = TempRepo::new(2).with_remote();
repo.git(&["commit", "-q", "--allow-empty", "-m", "local 1"]);
repo.git(&["commit", "-q", "--allow-empty", "-m", "local 2"]);
repo.run(|| {
assert!(!head_published());
assert!(!rewinds_published(Some("HEAD~2")).unwrap());
assert!(
rewinds_published(Some("HEAD~3")).unwrap(),
"HEAD~2 is pushed and would be dropped"
);
assert!(rewinds_published(None).unwrap());
assert!(!rewinds_published(Some("HEAD")).unwrap());
let cfg = Config {
confirm_destructive: true,
..Config::default()
};
assert_eq!(
move_verdict(&cfg, ResetMode::Keep, Some("HEAD~3")),
Verdict::Typed("main".into())
);
});
}
#[test]
fn restores_stash_tag_and_branch_backups() {
let repo = TempRepo::new(2);
repo.write("f1.txt", "stashed\n");
repo.git(&["tag", "-a", "v1", "-m", "release"]);
repo.git(&["branch", "gone", "HEAD~1"]);
repo.run(|| {
let sha = ok(&["stash", "create"]).unwrap();
let stash = safety::backup("stash-drop", &sha).unwrap();
ok(&["checkout", "--", "f1.txt"]).unwrap();
restore_stash(&stash, false).unwrap();
assert_eq!(ok(&["stash", "list", "--format=%H"]).unwrap(), sha);
let head = safety::backup("abort", "HEAD").unwrap();
assert!(
restore_stash(&head, false).is_err(),
"a plain commit is not a stash"
);
let tag_obj = ok(&["rev-parse", "refs/tags/v1"]).unwrap();
let tag = safety::backup("tag-delete", "refs/tags/v1").unwrap();
ok(&["tag", "-d", "v1"]).unwrap();
assert_eq!(tag_name_hint(&tag).as_deref(), Some("v1"));
assert!(restore_tag(&tag, "-x").is_err());
restore_tag(&tag, "v1").unwrap();
assert_eq!(ok(&["rev-parse", "refs/tags/v1"]).unwrap(), tag_obj);
assert!(restore_tag(&tag, "v1").is_err(), "existing tag is refused");
let gone = ok(&["rev-parse", "gone"]).unwrap();
let branch = safety::backup("branch-delete", "refs/heads/gone").unwrap();
ok(&["branch", "-D", "gone"]).unwrap();
assert_eq!(tag_name_hint(&branch), None);
restore_branch(&branch, "gone").unwrap();
assert_eq!(ok(&["rev-parse", "gone"]).unwrap(), gone);
assert!(restore_branch(&branch, "gone").is_err());
assert!(
restore_branch("refs/heads/main", "x").is_err(),
"only gct backups"
);
});
}
#[test]
fn switching_away_from_detached_head_backs_up_orphans() {
let repo = TempRepo::new(2);
repo.git(&["checkout", "-q", "--detach"]);
repo.git(&["commit", "-q", "--allow-empty", "-m", "orphan"]);
let orphan = repo.git(&["rev-parse", "HEAD"]);
repo.run(|| {
assert_eq!(detached_orphans().unwrap(), [orphan.as_str()]);
let out = undo_last(&UndoAction::Switch {
to: "main".into(),
detach: false,
})
.unwrap();
let backup = out.backup.unwrap();
assert!(backup.ends_with("-detached"), "{backup}");
assert_eq!(resolve(&backup).unwrap(), orphan);
assert_eq!(current_branch(), "main");
assert!(detached_orphans().unwrap().is_empty());
let out = undo_last(&UndoAction::Switch {
to: resolve("HEAD~1").unwrap(),
detach: true,
})
.unwrap();
assert!(
out.backup.is_none(),
"nothing orphaned when leaving a branch"
);
});
}
#[test]
fn root_commit_undo_uses_update_ref() {
let repo = TempRepo::new(1);
repo.run(|| {
assert_eq!(classify(&newest_head_subject()), UndoAction::DeleteRoot);
let out = undo_last(&UndoAction::DeleteRoot).unwrap();
assert_eq!(out.commands, ["git update-ref -d HEAD"]);
assert!(resolve("HEAD").is_err());
assert_eq!(ok(&["diff", "--cached", "--name-only"]).unwrap(), "f1.txt");
assert_eq!(safety::backups().unwrap().len(), 1);
});
let repo = TempRepo::new(2);
repo.run(|| assert!(undo_root().is_err()));
}
#[test]
fn wrong_branch_moves_two_commits() {
let repo = TempRepo::new(4);
repo.run(|| {
let tip = resolve("HEAD").unwrap();
let base = resolve("HEAD~2").unwrap();
assert!(fix_wrong_branch("-bad", 2).is_err());
fix_wrong_branch("feature", 2).unwrap();
assert_eq!(current_branch(), "feature");
assert_eq!(resolve("feature").unwrap(), tip);
assert_eq!(resolve("main").unwrap(), base);
assert!(fix_wrong_branch("feature", 1).is_err());
});
}
#[test]
fn published_commit_blocks_amend_and_wrong_branch() {
let repo = TempRepo::new(2).with_remote();
repo.write("forgot.txt", "x\n");
repo.run(|| {
let head = resolve("HEAD").unwrap();
let err = amend_last(&["forgot.txt".into()], None).unwrap_err();
assert!(err.to_string().contains("already pushed"));
assert!(fix_wrong_branch("moved", 1).is_err());
assert_eq!(resolve("HEAD").unwrap(), head);
});
repo.git(&["add", "forgot.txt"]);
repo.git(&["commit", "-q", "-m", "local"]);
repo.write("more.txt", "y\n");
repo.run(|| {
let out = amend_last(&["more.txt".into()], Some("local fixed".into())).unwrap();
assert!(out.backup.is_some());
assert_eq!(ok(&["log", "-1", "--format=%s"]).unwrap(), "local fixed");
assert_eq!(ok(&["rev-list", "--count", "HEAD"]).unwrap(), "3");
});
}
}