use std::fs::{self, File, OpenOptions};
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use super::{forge, git, source};
#[derive(Clone, Debug)]
pub struct Commit {
pub id: String,
pub subject: String,
}
#[derive(Clone, Debug)]
pub struct Snapshot {
pub root: PathBuf,
pub branch: String,
pub head: String,
pub dirty: usize,
pub branches: Vec<String>,
pub remote_branches: Vec<String>,
pub commits: Vec<Commit>,
pub recovery: Option<Move>,
pub undo: Option<Move>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Move {
pub source: String,
pub destination: String,
pub old: String,
pub base: String,
pub backup: String,
pub count: usize,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Action {
Track { reference: String, expected: String },
Switch { branch: String, expected: String },
Create { branch: String, expected: String },
Move(Move),
Undo(Move),
Publish { movement: Move, remote: String, expected: String, desired: String, destination_exists: bool },
}
fn head(root: &Path) -> Result<String, String> {
git::commit_id(root, "HEAD").ok_or("No commits yet".into())
}
fn branch(root: &Path) -> Result<String, String> {
git::line(root, &["symbolic-ref", "--quiet", "--short", "HEAD"])
.map_err(|_| "Detached HEAD: switch to a branch first".into())
}
fn state_dir(root: &Path) -> Result<PathBuf, String> {
git::line(root, &["rev-parse", "--path-format=absolute", "--git-common-dir"])
.map(|p| PathBuf::from(p).join("rustimal"))
}
fn lock(root: &Path) -> Result<File, String> {
let dir = state_dir(root)?;
fs::create_dir_all(&dir).map_err(|e| format!("Recovery storage: {e}"))?;
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(dir.join("operation.lock"))
.map_err(|e| format!("Git operation lock: {e}"))?;
file.try_lock().map_err(|_| "Another rustimal Git action is running".to_string())?;
Ok(file)
}
fn clean(root: &Path) -> Result<(), String> {
if !git::output(root, &["status", "--porcelain=v1", "--untracked-files=normal", "--ignore-submodules=none"])?
.is_empty()
{
return Err("Commit or stash your changes first".into());
}
for marker in
["MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "rebase-merge", "rebase-apply", "sequencer", "BISECT_LOG"]
{
let path = git::line(root, &["rev-parse", "--path-format=absolute", "--git-path", marker])?;
if Path::new(&path).exists() {
return Err("Finish or abort the current Git operation first".into());
}
}
Ok(())
}
fn valid_branch(root: &Path, name: &str) -> Result<(), String> {
if name.is_empty() || name.starts_with('-') || name == "HEAD" || name.chars().any(char::is_control) {
return Err("Choose a valid branch name".into());
}
git::output(root, &["check-ref-format", &format!("refs/heads/{name}")]).map(|_| ())
}
fn pinned(root: &Path, expected: &str) -> Result<(), String> {
if head(root)? != expected {
return Err("HEAD changed. Refresh and try again".into());
}
clean(root)
}
fn validate_move(root: &Path, m: &Move) -> Result<(), String> {
valid_branch(root, &m.source)?;
valid_branch(root, &m.destination)?;
let oid = |s: &str| matches!(s.len(), 40 | 64) && s.bytes().all(|b| b.is_ascii_hexdigit());
if m.source == m.destination
|| !oid(&m.old)
|| !oid(&m.base)
|| !m.backup.starts_with("refs/rustimal/undo/")
|| m.backup.contains("..")
{
return Err("Invalid recovery record".into());
}
git::output(root, &["check-ref-format", &m.backup])?;
Ok(())
}
pub fn snapshot(cwd: &Path) -> Result<Snapshot, String> {
let root = source::repository(cwd)?;
let branch = branch(&root).unwrap_or_else(|_| "(detached)".into());
let head = head(&root).unwrap_or_default();
let dirty = git::output(&root, &["status", "--porcelain=v1"])?.lines().count();
let branches =
git::output(&root, &["for-each-ref", "--sort=-committerdate", "--format=%(refname:strip=2)", "refs/heads/"])?
.lines()
.map(str::to_string)
.collect();
let commits = git::output(&root, &["log", "--first-parent", "-n", "100", "--format=%H%x1f%s", "HEAD", "--"])
.unwrap_or_default()
.lines()
.filter_map(|l| l.split_once('\x1f'))
.map(|(id, subject)| Commit { id: id.into(), subject: subject.into() })
.collect();
let remote_branches = git::output(
&root,
&["for-each-ref", "--sort=-committerdate", "--format=%(refname:strip=2)%1f%(symref)", "refs/remotes/"],
)?
.lines()
.filter_map(|line| line.split_once('\x1f'))
.filter(|(_, symref)| symref.is_empty())
.map(|(name, _)| name.to_string())
.collect();
let recoveries = matching_recoveries(&root, &branch).unwrap_or_default();
let recovery = recoveries.first().cloned();
let undo = recoveries.iter().find(|m| m.base == head).cloned();
Ok(Snapshot { root, branch, head, dirty, branches, remote_branches, commits, recovery, undo })
}
fn matching_recoveries(root: &Path, source: &str) -> Option<Vec<Move>> {
let current = head(root).ok()?;
let mut files: Vec<_> = fs::read_dir(state_dir(root).ok()?)
.ok()?
.filter_map(Result::ok)
.filter(|e| e.path().extension().is_some_and(|e| e == "json"))
.collect();
files.sort_by_key(|e| std::cmp::Reverse(e.file_name()));
let eligible: Vec<_> = files
.into_iter()
.take(100)
.filter_map(|e| {
let m: Move = serde_json::from_slice(&fs::read(e.path()).ok()?).ok()?;
if m.source != source && source != "(detached)" {
return None;
}
let source_id = git::commit_id(root, &format!("refs/heads/{}", m.source));
let matches = if source == "(detached)" {
current == m.base && source_id.as_deref().is_some_and(|id| id == m.base || id == m.old)
} else {
source_id.as_deref() == Some(¤t)
&& (current == m.base || (current == m.old && e.path().with_extension("done").exists()))
};
((m.source == source || source == "(detached)")
&& matches
&& validate_move(root, &m).is_ok()
&& git::commit_id(root, &m.backup).as_deref() == Some(&m.old))
.then_some(m)
})
.collect();
if source == "(detached)" && eligible.len() != 1 { None } else { Some(eligible) }
}
fn completed(root: &Path, m: &Move) -> Result<(), String> {
let name = m.backup.rsplit('/').next().ok_or("Invalid recovery name")?;
let file = File::create(state_dir(root)?.join(format!("{name}.done")))
.map_err(|e| format!("History updated, but recovery marker failed: {e}"))?;
file.sync_all().map_err(|e| format!("History updated, but recovery marker failed: {e}"))
}
fn rewind(root: &Path, m: &Move, undo: bool) -> Result<(), String> {
let (expected, target) = if undo { (&m.base, &m.old) } else { (&m.old, &m.base) };
let source_ref = format!("refs/heads/{}", m.source);
let current = branch(root).ok();
if current.as_deref().is_some_and(|b| b != m.source) {
return Err("Branch changed. Refresh first".into());
}
if !undo && current.is_none() {
return Err("Branch changed. Refresh first".into());
}
if git::commit_id(root, &source_ref).as_deref() != Some(expected) {
if undo && current.is_none() && git::commit_id(root, &source_ref).as_deref() == Some(&m.old) {
git::output(root, &["switch", "--no-guess", "--no-overwrite-ignore", "--", &m.source])?;
return Ok(());
}
return Err("Source branch changed since the preview".into());
}
git::output(root, &["switch", "--detach", "--no-overwrite-ignore", target])?;
if branch(root).is_ok() || head(root)? != *target {
return Err("HEAD changed during checkout. Recovery refs kept".into());
}
clean(root)?;
let worktrees = git::output(root, &["worktree", "list", "--porcelain", "-z"])?;
if worktrees.split('\0').any(|part| part == format!("branch {source_ref}")) {
return Err("Source branch is now checked out in another worktree. Recovery refs kept".into());
}
git::output(root, &["update-ref", "-m", "rustimal recovery", &source_ref, target, expected])
.map_err(|e| format!("{e}. Detached at {}. Recovery: {}", &target[..8], m.backup))?;
if branch(root).is_ok() || head(root)? != *target {
return Err("HEAD changed. Branch updated; recovery refs kept".into());
}
git::output(root, &["switch", "--no-guess", "--no-overwrite-ignore", "--", &m.source])?;
Ok(())
}
pub fn prepare_move(snapshot: &Snapshot, oldest: usize, destination: &str) -> Result<Move, String> {
let root = &snapshot.root;
pinned(root, &snapshot.head)?;
if branch(root)? != snapshot.branch {
return Err("Branch changed. Refresh first".into());
}
valid_branch(root, destination)?;
if git::commit_id(root, &format!("refs/heads/{destination}")).is_some() {
return Err("That branch already exists".into());
}
let last = snapshot.commits.get(oldest).ok_or("Select commits first")?;
let range = git::output(root, &["rev-list", "--parents", &format!("{}^..{}", last.id, snapshot.head), "--"])?;
let rows: Vec<Vec<&str>> = range.lines().map(|l| l.split_whitespace().collect()).collect();
if rows.len() != oldest + 1 || rows.iter().any(|r| r.len() != 2) {
return Err("Select a linear block of latest commits; merges are not supported".into());
}
let base = git::commit_id(root, &format!("{}^", last.id)).ok_or("Cannot move the root commit")?;
let id = SystemTime::now().duration_since(UNIX_EPOCH).map_err(|e| e.to_string())?.as_nanos();
Ok(Move {
source: snapshot.branch.clone(),
destination: destination.into(),
old: snapshot.head.clone(),
base,
backup: format!("refs/rustimal/undo/{id:030}-{}", std::process::id()),
count: oldest + 1,
})
}
pub fn execute(root: &Path, action: &Action) -> Result<String, String> {
let _lock = lock(root)?;
match action {
Action::Track { reference, expected } => {
pinned(root, expected)?;
if !reference.starts_with("refs/remotes/") || git::commit_id(root, reference).is_none() {
return Err("Remote branch is missing. Fetch first".into());
}
git::output(root, &["check-ref-format", reference])?;
git::output(root, &["switch", "--no-guess", "--no-overwrite-ignore", "--track", "--", reference])?;
Ok(format!("On {}", branch(root)?))
}
Action::Switch { branch: target, expected } | Action::Create { branch: target, expected } => {
pinned(root, expected)?;
valid_branch(root, target)?;
if matches!(action, Action::Create { .. }) {
git::output(root, &["switch", "--no-guess", "--no-overwrite-ignore", "-c", target])?;
} else {
git::output(root, &["switch", "--no-guess", "--no-overwrite-ignore", "--", target])?;
}
Ok(format!("On {target}"))
}
Action::Move(m) => {
validate_move(root, m)?;
pinned(root, &m.old)?;
if branch(root)? != m.source {
return Err("Branch changed. Refresh first".into());
}
let s = snapshot(root)?;
let checked = prepare_move(&s, m.count.checked_sub(1).ok_or("Invalid commit count")?, &m.destination)?;
if checked.old != m.old || checked.base != m.base {
return Err("History changed. Refresh first".into());
}
let name = m.backup.rsplit('/').next().ok_or("Invalid recovery name")?;
let bytes = serde_json::to_vec(m).map_err(|e| e.to_string())?;
use std::io::Write;
let mut record = OpenOptions::new()
.write(true)
.create_new(true)
.open(state_dir(root)?.join(format!("{name}.json")))
.map_err(|e| format!("Could not save recovery: {e}"))?;
record
.write_all(&bytes)
.and_then(|_| record.sync_all())
.map_err(|e| format!("Could not save recovery: {e}"))?;
git::output(root, &["update-ref", &m.backup, &m.old, ""])?;
git::output(root, &["branch", "--no-track", &m.destination, &m.old])?;
if let Err(e) = rewind(root, m, false) {
return Err(format!("{e}. Commits are safe on {} and {}", m.destination, m.backup));
}
completed(root, m)?;
Ok(format!("Moved {} commits to {}. Undo: u", m.count, m.destination))
}
Action::Undo(m) => {
validate_move(root, m)?;
pinned(root, &m.base)?;
if branch(root).ok().as_deref().is_some_and(|b| b != m.source)
|| git::commit_id(root, &m.backup).as_deref() != Some(&m.old)
{
return Err("Recovery no longer matches this branch".into());
}
rewind(root, m, true)?;
completed(root, m)?;
Ok(format!("Restored {}. {} kept", m.source, m.destination))
}
Action::Publish { movement: m, remote, expected, desired, destination_exists } => {
validate_move(root, m)?;
pinned(root, desired)?;
if branch(root)? != m.source
|| git::commit_id(root, &m.backup).as_deref() != Some(&m.old)
|| !((expected == &m.old && desired == &m.base) || (expected == &m.base && desired == &m.old))
{
return Err("Publication no longer matches this recovery".into());
}
let (configured, _) = forge::remote(root)?;
let url = git::line(root, &["remote", "get-url", "--push", &configured])?;
if remote != &url {
return Err("Remote changed. Preview again".into());
}
if git::commit_id(root, &format!("refs/heads/{}", m.destination)).as_deref() != Some(&m.old) {
return Err("Destination branch changed".into());
}
let source_ref = format!("refs/heads/{}", m.source);
let destination_ref = format!("refs/heads/{}", m.destination);
let live = git::output(root, &["ls-remote", "--refs", "--", remote, &source_ref, &destination_ref])?;
let remote_id = |r: &str| {
live.lines().filter_map(|l| l.split_once('\t')).find(|(_, name)| *name == r).map(|(id, _)| id)
};
if remote_id(&source_ref) != Some(expected)
|| remote_id(&destination_ref) != if *destination_exists { Some(m.old.as_str()) } else { None }
{
return Err("Remote changed since the preview. Preview again".into());
}
let source_lease = format!("--force-with-lease={source_ref}:{expected}");
let dest_lease =
format!("--force-with-lease={destination_ref}:{}", if *destination_exists { &m.old } else { "" });
git::output(
root,
&[
"push",
"--porcelain",
"--atomic",
"--no-follow-tags",
"--recurse-submodules=no",
&source_lease,
&dest_lease,
"--",
remote,
&format!("{desired}:{source_ref}"),
&format!("{}:{destination_ref}", m.old),
],
)?;
Ok(format!("Published {} and {}", m.source, m.destination))
}
}
}
pub fn fetch(root: &Path) -> Result<(), String> {
let _lock = lock(root)?;
let (remote, _) = forge::remote(root)?;
git::output(root, &["fetch", "--prune", "--", &remote]).map(|_| ())
}
pub fn prepare_publish(root: &Path, m: &Move) -> Result<Action, String> {
validate_move(root, m)?;
clean(root)?;
let desired = head(root)?;
let expected = if desired == m.base {
&m.old
} else if desired == m.old {
&m.base
} else {
return Err("Branch changed since the move".into());
};
let (name, _) = forge::remote(root)?;
let remote = git::line(root, &["remote", "get-url", "--push", &name])?;
let source_ref = format!("refs/heads/{}", m.source);
let destination_ref = format!("refs/heads/{}", m.destination);
let refs = git::output(root, &["ls-remote", "--refs", "--", &remote, &source_ref, &destination_ref])?;
let find = |r: &str| refs.lines().filter_map(|l| l.split_once('\t')).find(|(_, name)| *name == r).map(|(id, _)| id);
if find(&source_ref) != Some(expected) {
return Err("Remote branch changed or is missing. Fetch and inspect it first".into());
}
if find(&destination_ref).is_some_and(|id| id != m.old) {
return Err("The remote destination branch already has other commits".into());
}
Ok(Action::Publish {
movement: m.clone(),
remote,
expected: expected.clone(),
desired,
destination_exists: find(&destination_ref).is_some(),
})
}
pub fn remote_label(remote: &str) -> String {
forge::parse_remote(remote)
.map(|at| format!("{}/{}", at.host, at.path))
.unwrap_or_else(|| if Path::new(remote).is_absolute() { remote.into() } else { "Configured remote".into() })
}
#[cfg(test)]
mod tests {
use super::*;
use crate::review::git::testing::{commit, init, run};
use crate::review::testutil::Scratch;
fn repo(name: &str) -> Scratch {
let s = Scratch::new(name);
init(&s.0);
for n in 0..4 {
fs::write(s.0.join("file"), format!("{n}\n")).unwrap();
commit(&s.0, &format!("commit {n}"));
}
s
}
#[test]
fn moving_and_undoing_preserves_commits_and_the_working_tree() {
let s = repo("git-move");
let before = snapshot(&s.0).unwrap();
let m = prepare_move(&before, 1, "feature/fix").unwrap();
execute(&s.0, &Action::Move(m.clone())).unwrap();
assert_eq!(head(&s.0).unwrap(), m.base);
assert_eq!(fs::read_to_string(s.0.join("file")).unwrap(), "1\n");
assert_eq!(git::commit_id(&s.0, "refs/heads/feature/fix"), Some(before.head.clone()));
assert_eq!(git::commit_id(&s.0, &m.backup), Some(before.head.clone()));
assert_eq!(snapshot(&s.0).unwrap().recovery, Some(m.clone()));
execute(&s.0, &Action::Undo(m.clone())).unwrap();
assert_eq!(head(&s.0).unwrap(), before.head);
assert_eq!(fs::read_to_string(s.0.join("file")).unwrap(), "3\n");
assert!(git::commit_id(&s.0, "refs/heads/feature/fix").is_some());
assert!(git::output(&s.0, &["status", "--porcelain"]).unwrap().is_empty());
assert!(execute(&s.0, &Action::Undo(m)).is_err());
}
#[test]
fn dirty_stale_merged_and_invalid_moves_leave_history_alone() {
let s = repo("git-guards");
let before = snapshot(&s.0).unwrap();
let m = prepare_move(&before, 0, "feature").unwrap();
fs::write(s.0.join("untracked"), "keep me").unwrap();
assert!(execute(&s.0, &Action::Move(m.clone())).unwrap_err().contains("stash"));
assert_eq!(head(&s.0).unwrap(), before.head);
assert!(git::commit_id(&s.0, "refs/heads/feature").is_none());
commit(&s.0, "new work");
assert!(execute(&s.0, &Action::Move(m)).unwrap_err().contains("HEAD changed"));
for name in ["--force", "a..b", "HEAD", "x\ny", ""] {
assert!(prepare_move(&snapshot(&s.0).unwrap(), 0, name).is_err(), "{name}");
}
assert!(prepare_move(&snapshot(&s.0).unwrap(), 4, "root").is_err());
run(&s.0, &["switch", "-c", "other", "HEAD~2"]);
fs::write(s.0.join("other"), "branch").unwrap();
commit(&s.0, "other");
run(&s.0, &["switch", "main"]);
run(&s.0, &["merge", "--no-ff", "other", "-m", "merge"]);
assert!(prepare_move(&snapshot(&s.0).unwrap(), 0, "merged").is_err());
}
#[test]
fn checkout_create_and_operation_locks() {
let s = repo("git-switch");
let before = snapshot(&s.0).unwrap();
execute(&s.0, &Action::Create { branch: "feature".into(), expected: before.head.clone() }).unwrap();
assert_eq!(branch(&s.0).unwrap(), "feature");
execute(&s.0, &Action::Switch { branch: "main".into(), expected: before.head.clone() }).unwrap();
let _lock = lock(&s.0).unwrap();
assert!(
execute(&s.0, &Action::Switch { branch: "feature".into(), expected: before.head })
.unwrap_err()
.contains("running")
);
}
#[test]
fn failed_later_move_does_not_hide_an_earlier_undo() {
let s = repo("git-failed-recovery");
fs::write(s.0.join("data"), "tracked").unwrap();
commit(&s.0, "track data");
fs::remove_file(s.0.join("data")).unwrap();
fs::write(s.0.join(".gitignore"), "data\n").unwrap();
commit(&s.0, "ignore data");
fs::write(s.0.join("extra"), "extra").unwrap();
commit(&s.0, "extra");
let first = prepare_move(&snapshot(&s.0).unwrap(), 0, "first").unwrap();
execute(&s.0, &Action::Move(first.clone())).unwrap();
fs::write(s.0.join("data"), "USER CONTENT").unwrap();
let later = prepare_move(&snapshot(&s.0).unwrap(), 0, "later").unwrap();
assert!(execute(&s.0, &Action::Move(later)).is_err());
assert_eq!(snapshot(&s.0).unwrap().recovery, Some(first.clone()));
execute(&s.0, &Action::Undo(first)).unwrap();
assert_eq!(fs::read_to_string(s.0.join("data")).unwrap(), "USER CONTENT");
}
#[test]
fn consecutive_moves_can_be_undone_in_order() {
let s = repo("git-chain-undo");
let original = head(&s.0).unwrap();
let first = prepare_move(&snapshot(&s.0).unwrap(), 0, "first").unwrap();
execute(&s.0, &Action::Move(first.clone())).unwrap();
let second = prepare_move(&snapshot(&s.0).unwrap(), 0, "second").unwrap();
execute(&s.0, &Action::Move(second.clone())).unwrap();
execute(&s.0, &Action::Undo(snapshot(&s.0).unwrap().undo.unwrap())).unwrap();
let after = snapshot(&s.0).unwrap();
assert_eq!(after.recovery, Some(second));
assert_eq!(after.undo, Some(first));
execute(&s.0, &Action::Undo(after.undo.unwrap())).unwrap();
assert_eq!(head(&s.0).unwrap(), original);
}
#[test]
fn fetch_and_checkout_remote_tracking_branch() {
let s = repo("git-tracking");
let remote = Scratch::new("git-tracking-bare");
run(&remote.0, &["init", "--bare", "--quiet"]);
run(&s.0, &["remote", "add", "origin", remote.0.to_str().unwrap()]);
run(&s.0, &["push", "--quiet", "origin", "HEAD:refs/heads/feature/settings"]);
fetch(&s.0).unwrap();
let s0 = snapshot(&s.0).unwrap();
assert!(s0.remote_branches.contains(&"origin/feature/settings".into()));
execute(&s.0, &Action::Track { reference: "refs/remotes/origin/feature/settings".into(), expected: s0.head })
.unwrap();
assert_eq!(branch(&s.0).unwrap(), "feature/settings");
assert_eq!(git::line(&s.0, &["rev-parse", "--abbrev-ref", "@{upstream}"]).unwrap(), "origin/feature/settings");
}
#[test]
fn ignored_files_are_not_overwritten_by_move_or_checkout() {
let s = repo("git-ignored");
fs::write(s.0.join("data"), "tracked").unwrap();
commit(&s.0, "track data");
fs::remove_file(s.0.join("data")).unwrap();
fs::write(s.0.join(".gitignore"), "data\n").unwrap();
commit(&s.0, "ignore data");
fs::write(s.0.join("data"), "USER CONTENT").unwrap();
let before = snapshot(&s.0).unwrap();
assert_eq!(before.dirty, 0);
let m = prepare_move(&before, 0, "saved").unwrap();
assert!(execute(&s.0, &Action::Move(m)).is_err());
assert_eq!(fs::read_to_string(s.0.join("data")).unwrap(), "USER CONTENT");
assert_eq!(head(&s.0).unwrap(), before.head);
}
#[test]
fn interrupted_detached_move_can_be_recovered_without_rewriting_new_work() {
let s = repo("git-interrupted");
let m = prepare_move(&snapshot(&s.0).unwrap(), 0, "saved").unwrap();
execute(&s.0, &Action::Move(m.clone())).unwrap();
run(&s.0, &["switch", "--detach", &m.base]);
assert_eq!(snapshot(&s.0).unwrap().recovery, Some(m.clone()));
execute(&s.0, &Action::Undo(m.clone())).unwrap();
assert_eq!(branch(&s.0).unwrap(), "main");
assert_eq!(head(&s.0).unwrap(), m.old);
fs::write(s.0.join("new"), "keep").unwrap();
commit(&s.0, "later work");
let later = head(&s.0).unwrap();
run(&s.0, &["switch", "--detach", &m.base]);
assert!(execute(&s.0, &Action::Undo(m)).is_err());
assert_eq!(git::commit_id(&s.0, "refs/heads/main"), Some(later));
}
#[test]
fn atomic_publication_leases_and_remote_undo() {
let s = repo("git-publish");
let remote = Scratch::new("git-bare");
run(&remote.0, &["init", "--bare", "--quiet"]);
run(&s.0, &["remote", "add", "origin", remote.0.to_str().unwrap()]);
run(&s.0, &["push", "--quiet", "origin", "main"]);
let m = prepare_move(&snapshot(&s.0).unwrap(), 0, "rescued").unwrap();
execute(&s.0, &Action::Move(m.clone())).unwrap();
let push = prepare_publish(&s.0, &m).unwrap();
run(&remote.0, &["update-ref", "refs/heads/main", &m.base]);
assert!(execute(&s.0, &push).is_err());
assert!(git::commit_id(&remote.0, "refs/heads/rescued").is_none());
run(&remote.0, &["update-ref", "refs/heads/main", &m.old]);
execute(&s.0, &push).unwrap();
assert_eq!(git::commit_id(&remote.0, "refs/heads/main"), Some(m.base.clone()));
assert_eq!(git::commit_id(&remote.0, "refs/heads/rescued"), Some(m.old.clone()));
execute(&s.0, &Action::Undo(m.clone())).unwrap();
execute(&s.0, &prepare_publish(&s.0, &m).unwrap()).unwrap();
assert_eq!(git::commit_id(&remote.0, "refs/heads/main"), Some(m.old));
}
}