feat(core): migrate plain clones to bare+worktrees with backup and rollback

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-11-16 12:05:56 +01:00
1 parent 5291c3e671
commit b6f868ee76
5 files changed
+790

No files matched your search

+8
View File
@@ -138,6 +138,14 @@ impl Config {
Some(base.join("gitsync/config.toml"))
}
/// Local state directory: `$XDG_STATE_HOME/gitsync` or `~/.local/state/gitsync`.
pub fn state_dir() -> Option<PathBuf> {
let base = std::env::var_os("XDG_STATE_HOME")
.map(PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local/state")))?;
Some(base.join("gitsync"))
}
/// `root.path` with a leading `~` expanded.
pub fn root_path(&self) -> PathBuf {
expand_home(&self.root.path)
+98
View File
@@ -0,0 +1,98 @@
//! Branch name to directory name mapping (section 5 of the plan).
/// Map a branch name to a visible, filesystem-safe directory name that is not in `taken`.
/// `/` becomes `-`; collisions get a short deterministic suffix derived from the branch.
pub fn dir_name(branch: &str, taken: &[&str]) -> String {
let mut base: String = branch
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') {
c
} else {
'-'
}
})
.collect();
base = base.trim_start_matches('.').to_string();
if base.is_empty() {
base = "branch".to_string();
}
if !taken.contains(&base.as_str()) {
return base;
}
let suffixed = format!("{base}-{:06x}", fnv1a(branch) & 0xff_ffff);
if !taken.contains(&suffixed.as_str()) {
return suffixed;
}
(2..)
.map(|n| format!("{suffixed}-{n}"))
.find(|c| !taken.contains(&c.as_str()))
.expect("unbounded range")
}
fn fnv1a(s: &str) -> u32 {
s.bytes().fold(0x811c_9dc5u32, |h, b| {
(h ^ u32::from(b)).wrapping_mul(0x0100_0193)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn flattens_slashes() {
assert_eq!(dir_name("feat/login", &[]), "feat-login");
assert_eq!(dir_name("main", &[]), "main");
}
#[test]
fn collisions_get_a_deterministic_suffix() {
let a = dir_name("feat/x", &["feat-x"]);
assert_ne!(a, "feat-x");
assert!(a.starts_with("feat-x-"));
assert_eq!(a, dir_name("feat/x", &["feat-x"]));
// Two branches mapping to the same base end up different.
let first = dir_name("feat/x", &[]);
let second = dir_name("feat-x", &[first.as_str()]);
assert_ne!(first, second);
}
#[test]
fn reserved_names_are_avoided() {
assert_ne!(dir_name(".bare", &[".bare"]), ".bare");
assert!(!dir_name("..", &[]).starts_with('.'));
assert!(!dir_name("", &[]).is_empty());
}
/// Fuzz-style invariants with a tiny LCG (no extra dependency).
#[test]
fn invariants_hold_for_random_names() {
let alphabet: Vec<char> = "ab/._- é\\:*?\"<>|0Z".chars().collect();
let mut seed = 0x1234_5678_u64;
let mut taken: Vec<String> = vec![".bare".into(), ".gitsync-stage".into()];
for _ in 0..2000 {
let len = {
seed = seed
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
(seed >> 60) as usize
};
let name: String = (0..len)
.map(|_| {
seed = seed
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
alphabet[(seed >> 33) as usize % alphabet.len()]
})
.collect();
let refs: Vec<&str> = taken.iter().map(String::as_str).collect();
let d = dir_name(&name, &refs);
assert!(!d.is_empty());
assert!(!d.contains('/'));
assert!(!d.starts_with('.'));
assert!(!taken.contains(&d), "{name:?} -> {d:?} already taken");
taken.push(d);
}
}
}
+432
View File
@@ -0,0 +1,432 @@
//! Migrate a plain clone to the bare + worktree layout in place (section 5).
//!
//! Safety: a full tar backup and a backup ref are taken first; the observable state
//! (`status --ignored`, stashes, refs) is compared before and after; any failure after
//! the first modification triggers a rollback to the original layout.
use crate::git::{Git, GitError};
use crate::layout::dir_name;
use std::fmt;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::process::Command;
const BARE: &str = ".bare";
const STAGE: &str = ".gitsync-stage";
#[derive(Debug)]
pub enum MigrateError {
/// Pre-flight check failed; nothing was touched.
Refused(String),
Git(GitError),
Io(io::Error),
/// A step failed after the backup was taken.
Failed {
cause: String,
rolled_back: bool,
backup: PathBuf,
},
}
impl fmt::Display for MigrateError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
MigrateError::Refused(m) => write!(f, "refused: {m}"),
MigrateError::Git(e) => write!(f, "{e}"),
MigrateError::Io(e) => write!(f, "io error: {e}"),
MigrateError::Failed {
cause,
rolled_back,
backup,
} => write!(
f,
"migration failed: {cause}; {}; backup at {}",
if *rolled_back {
"original layout restored"
} else {
"ROLLBACK INCOMPLETE, restore from the backup"
},
backup.display()
),
}
}
}
impl std::error::Error for MigrateError {}
impl From<GitError> for MigrateError {
fn from(e: GitError) -> Self {
MigrateError::Git(e)
}
}
impl From<io::Error> for MigrateError {
fn from(e: io::Error) -> Self {
MigrateError::Io(e)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Report {
pub bare_dir: PathBuf,
pub worktree: PathBuf,
pub branch: String,
pub backup_tar: PathBuf,
pub backup_ref: String,
}
/// Steps after which a failure can be injected (tests only).
#[doc(hidden)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Step {
Staged,
GitMoved,
WorktreeAdded,
Filled,
IndexMoved,
Verified,
}
#[derive(Default)]
struct Progress {
staged: bool,
git_moved: bool,
wt_dir: Option<PathBuf>,
wt_meta: Option<PathBuf>,
filled: bool,
index_moved: bool,
}
#[derive(Debug, PartialEq, Eq)]
struct Observed {
status: String,
stash: String,
refs: String,
}
fn observe(git: &Git) -> Result<Observed, GitError> {
let refs = git.run(&["for-each-ref", "--format=%(refname) %(objectname)"])?;
let refs = refs
.lines()
.filter(|l| !l.starts_with("refs/sync-backup/"))
.collect::<Vec<_>>()
.join("\n");
Ok(Observed {
status: git.run(&["status", "--porcelain", "--ignored"])?,
stash: git.run(&["stash", "list", "--format=%H"])?,
refs,
})
}
fn s<E: fmt::Display>(e: E) -> String {
e.to_string()
}
/// Migrate the plain repo whose root is `repo`. `stamp` must be filesystem-safe.
pub fn migrate(
repo: &Path,
machine: &str,
backup_dir: &Path,
stamp: &str,
) -> Result<Report, MigrateError> {
migrate_inner(repo, machine, backup_dir, stamp, None)
}
#[doc(hidden)]
pub fn migrate_failing_after(
repo: &Path,
machine: &str,
backup_dir: &Path,
stamp: &str,
step: Step,
) -> Result<Report, MigrateError> {
migrate_inner(repo, machine, backup_dir, stamp, Some(step))
}
fn refuse<T>(m: impl Into<String>) -> Result<T, MigrateError> {
Err(MigrateError::Refused(m.into()))
}
fn preflight(root: &Path) -> Result<String, MigrateError> {
let dotgit = root.join(".git");
if root.join(BARE).exists() {
return refuse("already migrated (.bare exists)");
}
if root.join(STAGE).exists() {
return refuse(format!(
"{STAGE} exists: a previous migration was interrupted"
));
}
if !dotgit.is_dir() {
return refuse("not a plain clone (.git is not a directory)");
}
let git = Git::new(root);
let top = PathBuf::from(git.run(&["rev-parse", "--show-toplevel"])?).canonicalize()?;
if top != root {
return refuse("path is not the repository root");
}
let Some(branch) = git.probe(&["symbolic-ref", "--short", "-q", "HEAD"])? else {
return refuse("detached HEAD: check out a branch first");
};
if git
.probe(&["rev-parse", "-q", "--verify", "HEAD"])?
.is_none()
{
return refuse("repository has no commits yet");
}
for f in [
"rebase-merge",
"rebase-apply",
"MERGE_HEAD",
"CHERRY_PICK_HEAD",
"REVERT_HEAD",
"BISECT_LOG",
] {
if dotgit.join(f).exists() {
return refuse(format!(
"operation in progress ({f}): finish or abort it first"
));
}
}
if root.join(".gitmodules").exists() || dotgit.join("modules").exists() {
return refuse("submodules are not supported yet");
}
if git
.run(&["worktree", "list", "--porcelain"])?
.matches("worktree ")
.count()
> 1
{
return refuse("repository already has linked worktrees; not supported yet");
}
Ok(branch)
}
fn backup(
root: &Path,
git: &Git,
machine: &str,
backup_dir: &Path,
stamp: &str,
) -> Result<(PathBuf, String), MigrateError> {
fs::create_dir_all(backup_dir)?;
let backup_dir = backup_dir.canonicalize()?;
if backup_dir.starts_with(root) {
return refuse("backup directory must be outside the repository");
}
let name = root
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| "repo".into());
let tar = backup_dir.join(format!("{name}-{stamp}.tar"));
let parent = root
.parent()
.ok_or_else(|| MigrateError::Refused("repo has no parent".into()))?;
let out = Command::new("tar")
.arg("-cf")
.arg(&tar)
.arg("-C")
.arg(parent)
.arg(&name)
.output()?;
if !out.status.success() {
let _ = fs::remove_file(&tar);
return refuse(format!(
"tar backup failed: {}",
String::from_utf8_lossy(&out.stderr)
));
}
let backup_ref = format!("refs/sync-backup/{machine}/{stamp}");
git.run(&["update-ref", &backup_ref, "HEAD"])?;
Ok((tar, backup_ref))
}
fn migrate_inner(
repo: &Path,
machine: &str,
backup_dir: &Path,
stamp: &str,
inject: Option<Step>,
) -> Result<Report, MigrateError> {
let root = repo.canonicalize()?;
let branch = preflight(&root)?;
let git = Git::new(&root);
let before = observe(&git)?;
let (backup_tar, backup_ref) = backup(&root, &git, machine, backup_dir, stamp)?;
let dir = dir_name(&branch, &[BARE, STAGE]);
let mut p = Progress::default();
match run_steps(&root, &branch, &dir, &before, &mut p, inject) {
Ok(worktree) => Ok(Report {
bare_dir: root.join(BARE),
worktree,
branch,
backup_tar,
backup_ref,
}),
Err(cause) => {
let rb = rollback(&root, &p);
let (cause, rolled_back) = match rb {
Ok(()) => (cause, true),
Err(e) => (format!("{cause}; rollback error: {e}"), false),
};
Err(MigrateError::Failed {
cause,
rolled_back,
backup: backup_tar,
})
}
}
}
fn move_entries(from: &Path, to: &Path, skip: &[&str]) -> io::Result<()> {
for entry in fs::read_dir(from)? {
let entry = entry?;
let name = entry.file_name();
if skip.iter().any(|k| name == *k) {
continue;
}
fs::rename(entry.path(), to.join(&name))?;
}
Ok(())
}
fn hook(inject: Option<Step>, at: Step) -> Result<(), String> {
if inject == Some(at) {
Err(format!("injected failure after {at:?}"))
} else {
Ok(())
}
}
fn run_steps(
root: &Path,
branch: &str,
dir: &str,
before: &Observed,
p: &mut Progress,
inject: Option<Step>,
) -> Result<PathBuf, String> {
let stage = root.join(STAGE);
let root_git = Git::new(root);
// 1. Move everything except .git into a staging dir.
fs::create_dir(&stage).map_err(s)?;
p.staged = true;
move_entries(root, &stage, &[".git", STAGE]).map_err(s)?;
hook(inject, Step::Staged)?;
// 2. .git -> .bare, make it bare.
fs::rename(root.join(".git"), root.join(BARE)).map_err(s)?;
p.git_moved = true;
root_git
.run(&["--git-dir", BARE, "config", "core.bare", "true"])
.map_err(s)?;
root_git
.probe(&["--git-dir", BARE, "config", "--unset", "core.worktree"])
.map_err(s)?;
hook(inject, Step::GitMoved)?;
// 3. Register the worktree without checking anything out.
let wt = root.join(dir);
p.wt_dir = Some(wt.clone());
let wt_str = wt.to_string_lossy().into_owned();
root_git
.run(&[
"--git-dir",
BARE,
"worktree",
"add",
"--no-checkout",
&wt_str,
branch,
])
.map_err(s)?;
let pointer = fs::read_to_string(wt.join(".git")).map_err(s)?;
let meta = pointer
.trim()
.strip_prefix("gitdir: ")
.map(PathBuf::from)
.ok_or("unexpected .git file in new worktree")?;
p.wt_meta = Some(meta.clone());
hook(inject, Step::WorktreeAdded)?;
// 4. Put the user's files into the worktree.
p.filled = true;
move_entries(&stage, &wt, &[]).map_err(s)?;
hook(inject, Step::Filled)?;
// 5. Carry over the index so staged changes survive.
let old_index = root.join(BARE).join("index");
if old_index.exists() {
fs::rename(&old_index, meta.join("index")).map_err(s)?;
p.index_moved = true;
}
hook(inject, Step::IndexMoved)?;
// 6. Verify nothing observable changed.
let after = observe(&Git::new(&wt)).map_err(s)?;
if &after != before {
let what = if after.status != before.status {
"status"
} else if after.stash != before.stash {
"stashes"
} else {
"refs"
};
return Err(format!(
"verification failed: {what} differ after migration"
));
}
hook(inject, Step::Verified)?;
fs::remove_dir(&stage).map_err(s)?;
Ok(wt)
}
fn rollback(root: &Path, p: &Progress) -> Result<(), String> {
let stage = root.join(STAGE);
let bare = root.join(BARE);
if p.index_moved
&& let Some(meta) = &p.wt_meta
{
fs::rename(meta.join("index"), bare.join("index")).map_err(s)?;
}
if let Some(wt) = &p.wt_dir
&& wt.exists()
{
if p.filled {
fs::create_dir_all(&stage).map_err(s)?;
move_entries(wt, &stage, &[".git"]).map_err(s)?;
}
// Only delete the worktree dir if user files are no longer in it.
let leftovers = fs::read_dir(wt)
.map_err(s)?
.filter_map(Result::ok)
.any(|e| e.file_name() != ".git");
if leftovers {
return Err(format!(
"{} still holds user files; not deleting",
wt.display()
));
}
fs::remove_dir_all(wt).map_err(s)?;
}
if let Some(meta) = &p.wt_meta
&& meta.exists()
{
fs::remove_dir_all(meta).map_err(s)?;
let _ = fs::remove_dir(bare.join("worktrees"));
}
if p.git_moved {
Git::new(root)
.run(&["--git-dir", BARE, "config", "core.bare", "false"])
.map_err(s)?;
fs::rename(&bare, root.join(".git")).map_err(s)?;
}
if p.staged && stage.exists() {
move_entries(&stage, root, &[]).map_err(s)?;
fs::remove_dir(&stage).map_err(s)?;
}
Ok(())
}
+51
View File
@@ -0,0 +1,51 @@
#![allow(dead_code)]
use gitsync_core::git::Git;
use std::fs;
use std::path::{Path, PathBuf};
pub fn tmpdir(tag: &str) -> PathBuf {
let p = std::env::temp_dir().join(format!(
"gitsync-test-{tag}-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&p).unwrap();
p
}
pub fn init(dir: &Path) -> Git {
fs::create_dir_all(dir).unwrap();
let g = Git::new(dir);
g.run(&["init", "-q", "-b", "main"]).unwrap();
g.run(&["config", "user.email", "t@t"]).unwrap();
g.run(&["config", "user.name", "t"]).unwrap();
g
}
pub fn commit(g: &Git, file: &str, body: &str) {
let path = g.dir().join(file);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, body).unwrap();
g.run(&["add", "."]).unwrap();
g.run(&["commit", "-qm", file]).unwrap();
}
/// A repo with history, a second branch, a stash, staged, modified, untracked and ignored files.
pub fn messy_repo(dir: &Path) -> Git {
let g = init(dir);
commit(&g, ".gitignore", "*.env\n");
commit(&g, "src/a.txt", "one\n");
commit(&g, "b.txt", "b\n");
g.run(&["branch", "other"]).unwrap();
fs::write(dir.join("b.txt"), "b changed for stash\n").unwrap();
g.run(&["stash", "push", "-q"]).unwrap();
fs::write(dir.join("src/a.txt"), "one\nmodified\n").unwrap();
fs::write(dir.join("staged.txt"), "staged\n").unwrap();
g.run(&["add", "staged.txt"]).unwrap();
fs::write(dir.join("untracked.txt"), "u\n").unwrap();
fs::write(dir.join("secret.env"), "s\n").unwrap();
g
}
+201
View File
@@ -0,0 +1,201 @@
mod common;
use common::*;
use gitsync_core::git::Git;
use gitsync_core::migrate::{MigrateError, Step, migrate, migrate_failing_after};
use std::fs;
fn names(dir: &std::path::Path) -> Vec<String> {
let mut v: Vec<String> = fs::read_dir(dir)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.collect();
v.sort();
v
}
#[test]
fn migrates_preserving_all_local_state() {
let base = tmpdir("mig");
let repo = base.join("proj");
let g = messy_repo(&repo);
let status = g.run(&["status", "--porcelain", "--ignored"]).unwrap();
let stash = g.run(&["stash", "list", "--format=%H"]).unwrap();
let branches = g
.run(&["branch", "--format=%(refname) %(objectname)"])
.unwrap();
let r = migrate(&repo, "desktop", &base.join("backups"), "20261116").unwrap();
assert_eq!(names(&repo), vec![".bare", "main"]);
assert_eq!(r.worktree, repo.canonicalize().unwrap().join("main"));
let wt = Git::new(&r.worktree);
assert_eq!(
wt.run(&["status", "--porcelain", "--ignored"]).unwrap(),
status
);
assert_eq!(wt.run(&["stash", "list", "--format=%H"]).unwrap(), stash);
assert_eq!(
wt.run(&["branch", "--format=%(refname) %(objectname)"])
.unwrap(),
branches
);
assert!(
status.contains("A staged.txt"),
"staged state kept: {status}"
);
assert!(r.worktree.join("secret.env").exists(), "ignored file kept");
assert!(r.worktree.join("untracked.txt").exists());
assert_eq!(
fs::read_to_string(r.worktree.join("src/a.txt")).unwrap(),
"one\nmodified\n"
);
// Backup exists and the backup ref points at the old HEAD.
assert!(r.backup_tar.metadata().unwrap().len() > 0);
assert_eq!(
wt.run(&["rev-parse", &r.backup_ref]).unwrap(),
wt.run(&["rev-parse", "HEAD"]).unwrap()
);
// Repo is bare now; the worktree is still fully usable.
assert_eq!(
Git::new(&r.bare_dir)
.run(&["rev-parse", "--is-bare-repository"])
.unwrap(),
"true"
);
commit(&wt, "after.txt", "x\n");
}
#[test]
fn slash_branch_gets_flattened_directory() {
let base = tmpdir("slash");
let repo = base.join("p");
let g = init(&repo);
commit(&g, "a.txt", "1\n");
g.run(&["checkout", "-q", "-b", "feat/login"]).unwrap();
let r = migrate(&repo, "m", &base.join("bk"), "1").unwrap();
assert!(r.worktree.ends_with("feat-login"));
assert_eq!(names(&repo), vec![".bare", "feat-login"]);
}
#[test]
fn every_failure_point_rolls_back_to_the_original_layout() {
for step in [
Step::Staged,
Step::GitMoved,
Step::WorktreeAdded,
Step::Filled,
Step::IndexMoved,
Step::Verified,
] {
let base = tmpdir("rb");
let repo = base.join("proj");
let g = messy_repo(&repo);
let status = g.run(&["status", "--porcelain", "--ignored"]).unwrap();
let stash = g.run(&["stash", "list", "--format=%H"]).unwrap();
let before_names = names(&repo);
let err = migrate_failing_after(&repo, "m", &base.join("bk"), "1", step).unwrap_err();
let MigrateError::Failed {
rolled_back,
backup,
..
} = err
else {
panic!("{step:?}: expected Failed")
};
assert!(rolled_back, "{step:?}: rollback incomplete");
assert!(backup.exists());
assert_eq!(names(&repo), before_names, "{step:?}: layout restored");
let g = Git::new(&repo);
assert_eq!(
g.run(&["rev-parse", "--is-bare-repository"]).unwrap(),
"false",
"{step:?}"
);
assert_eq!(
g.run(&["status", "--porcelain", "--ignored"]).unwrap(),
status,
"{step:?}"
);
assert_eq!(
g.run(&["stash", "list", "--format=%H"]).unwrap(),
stash,
"{step:?}"
);
assert_eq!(
g.run(&["worktree", "list", "--porcelain"])
.unwrap()
.matches("worktree ")
.count(),
1
);
// And a retry succeeds afterwards.
migrate(&repo, "m", &base.join("bk"), "2").unwrap();
}
}
fn refused(r: Result<gitsync_core::migrate::Report, MigrateError>) -> String {
match r {
Err(MigrateError::Refused(m)) => m,
other => panic!("expected Refused, got {other:?}"),
}
}
#[test]
fn refuses_unsafe_situations_without_touching_anything() {
let base = tmpdir("ref");
let bk = base.join("bk");
let detached = base.join("detached");
let g = init(&detached);
commit(&g, "a", "1");
g.run(&["checkout", "-q", "--detach"]).unwrap();
assert!(refused(migrate(&detached, "m", &bk, "1")).contains("detached"));
let unborn = base.join("unborn");
init(&unborn);
assert!(refused(migrate(&unborn, "m", &bk, "1")).contains("no commits"));
let merging = base.join("merging");
let g = init(&merging);
commit(&g, "a", "1");
fs::write(merging.join(".git/MERGE_HEAD"), "x").unwrap();
assert!(refused(migrate(&merging, "m", &bk, "1")).contains("in progress"));
let subm = base.join("subm");
let g = init(&subm);
commit(&g, "a", "1");
fs::write(subm.join(".gitmodules"), "").unwrap();
assert!(refused(migrate(&subm, "m", &bk, "1")).contains("submodule"));
let multi = base.join("multi");
let g = init(&multi);
commit(&g, "a", "1");
g.run(&[
"worktree",
"add",
"-q",
"-b",
"x",
base.join("extra").to_str().unwrap(),
])
.unwrap();
assert!(refused(migrate(&multi, "m", &bk, "1")).contains("linked worktrees"));
let done = base.join("done");
let g = init(&done);
commit(&g, "a", "1");
migrate(&done, "m", &bk, "1").unwrap();
assert!(refused(migrate(&done, "m", &bk, "2")).contains("already migrated"));
let inside = base.join("inside");
let g = init(&inside);
commit(&g, "a", "1");
assert!(refused(migrate(&inside, "m", &inside.join("bk"), "1")).contains("outside"));
assert!(inside.join(".git").is_dir());
// Subdirectory is not a repo root.
fs::create_dir(inside.join("sub")).unwrap();
assert!(refused(migrate(&inside.join("sub"), "m", &bk, "1")).contains("plain clone"));
}