mirror of
https://github.com/Dasemu/Grove.git
synced 2026-11-26 23:36:11 +00:00
feat: resolve diverged worktrees, status --plan, snapshot size limit
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b86342b1d0
commit
398b959ffe
13 files changed
+443
-17
No files matched your search
@@ -72,6 +72,9 @@ pub struct Sync {
|
||||
pub fetch_interval_s: u64,
|
||||
#[serde(default)]
|
||||
pub ignore_extra: Vec<String>,
|
||||
/// Changed files larger than this many MiB are not snapshotted (0 = no limit).
|
||||
#[serde(default = "default_max_file_mb")]
|
||||
pub max_file_mb: u64,
|
||||
}
|
||||
|
||||
impl Default for Sync {
|
||||
@@ -80,6 +83,7 @@ impl Default for Sync {
|
||||
snapshot_debounce_ms: default_debounce(),
|
||||
fetch_interval_s: default_fetch(),
|
||||
ignore_extra: Vec::new(),
|
||||
max_file_mb: default_max_file_mb(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -96,6 +100,9 @@ fn yes() -> bool {
|
||||
fn default_debounce() -> u64 {
|
||||
2000
|
||||
}
|
||||
fn default_max_file_mb() -> u64 {
|
||||
50
|
||||
}
|
||||
fn default_fetch() -> u64 {
|
||||
60
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ pub mod layout;
|
||||
pub mod migrate;
|
||||
pub mod receive;
|
||||
pub mod registry;
|
||||
pub mod resolve;
|
||||
pub mod snapshot;
|
||||
pub mod state;
|
||||
pub mod sync;
|
||||
@@ -15,13 +15,13 @@ pub const REMOTE_SYNC: &str = "refs/sync-remote";
|
||||
|
||||
/// Backup refs live in `refs/sync-backup/<machine>/<stamp>/<kind>`; each kind has its own
|
||||
/// sub-namespace so refs of different operations in one pass can never collide (D/F conflict).
|
||||
fn backup_ref(machine: &str, stamp: &str, kind: &str) -> String {
|
||||
pub(crate) fn backup_ref(machine: &str, stamp: &str, kind: &str) -> String {
|
||||
format!("refs/sync-backup/{machine}/{stamp}/{kind}")
|
||||
}
|
||||
|
||||
/// Paths the incoming change would add that already exist locally as *ignored* files.
|
||||
/// `git status` does not report those, but a merge/read-tree would silently overwrite them.
|
||||
fn ignored_conflicts(g: &Git, target: &str) -> Result<Vec<String>, GitError> {
|
||||
pub(crate) fn ignored_conflicts(g: &Git, target: &str) -> Result<Vec<String>, GitError> {
|
||||
let added = g.run(&[
|
||||
"diff",
|
||||
"--no-renames",
|
||||
|
||||
@@ -67,6 +67,18 @@ pub fn clone_bare_layout(
|
||||
f = f.with_env(k, v);
|
||||
}
|
||||
f.run(&["fetch", "-q", "--prune", "origin"])?;
|
||||
// `clone --bare` creates local branches without upstream config; worktrees made from them
|
||||
// would then never be classified as ahead/behind.
|
||||
let b = Git::new(&bare);
|
||||
let heads = b.run(&["for-each-ref", "--format=%(refname:short)", "refs/heads"])?;
|
||||
for br in heads.lines() {
|
||||
let up = format!("origin/{br}");
|
||||
if b.probe(&["rev-parse", "-q", "--verify", &format!("refs/remotes/{up}")])?
|
||||
.is_some()
|
||||
{
|
||||
b.run(&["branch", "-q", &format!("--set-upstream-to={up}"), br])?;
|
||||
}
|
||||
}
|
||||
materialize(dir, "origin")
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
//! Resolution of a `Diverged` worktree. Always an explicit choice by the user; every action
|
||||
//! writes a backup ref first so nothing is ever lost.
|
||||
|
||||
use crate::git::{Git, GitError};
|
||||
use crate::inspect::facts;
|
||||
use crate::layout::dir_name;
|
||||
use crate::receive::{backup_ref, ignored_conflicts};
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Choice {
|
||||
/// Discard the local commits and move to the remote tip.
|
||||
TakeRemote,
|
||||
/// Overwrite the remote branch with the local one (force-with-lease on the observed tip).
|
||||
KeepLocal,
|
||||
/// Keep the local commits on a new branch (own worktree), then move this one to the remote tip.
|
||||
SaveAsBranch(String),
|
||||
}
|
||||
|
||||
fn fail<T>(msg: impl Into<String>) -> Result<T, GitError> {
|
||||
Err(GitError::Other(msg.into()))
|
||||
}
|
||||
|
||||
/// Applies `choice` to the diverged worktree. Returns a one-line description of what happened.
|
||||
pub fn resolve(
|
||||
worktree: &Path,
|
||||
machine: &str,
|
||||
stamp: &str,
|
||||
choice: &Choice,
|
||||
) -> Result<String, GitError> {
|
||||
let g = Git::new(worktree);
|
||||
let f = facts(worktree)?;
|
||||
if !(f.ahead && f.behind) {
|
||||
return fail("worktree is not diverged: nothing to resolve");
|
||||
}
|
||||
let branch = g
|
||||
.probe(&["symbolic-ref", "--short", "-q", "HEAD"])?
|
||||
.ok_or_else(|| GitError::Other("detached HEAD".into()))?;
|
||||
let upstream = g.run(&["rev-parse", "@{upstream}"])?;
|
||||
let head = g.run(&["rev-parse", "HEAD"])?;
|
||||
match choice {
|
||||
Choice::KeepLocal => {
|
||||
g.run(&[
|
||||
"update-ref",
|
||||
&backup_ref(machine, stamp, &format!("resolve-remote/{branch}")),
|
||||
&upstream,
|
||||
])?;
|
||||
let remote = g.run(&["config", "--get", &format!("branch.{branch}.remote")])?;
|
||||
g.run(&[
|
||||
"push",
|
||||
"-q",
|
||||
&format!("--force-with-lease={branch}:{upstream}"),
|
||||
&remote,
|
||||
&format!("HEAD:refs/heads/{branch}"),
|
||||
])?;
|
||||
Ok(format!(
|
||||
"remote {branch} overwritten with local (old tip kept at backup ref)"
|
||||
))
|
||||
}
|
||||
Choice::TakeRemote | Choice::SaveAsBranch(_) => {
|
||||
if f.dirty {
|
||||
return fail("worktree has uncommitted changes: commit or stash them first");
|
||||
}
|
||||
let clash = ignored_conflicts(&g, &upstream)?;
|
||||
if !clash.is_empty() {
|
||||
return fail(format!(
|
||||
"would overwrite ignored local files: {}",
|
||||
clash.join(", ")
|
||||
));
|
||||
}
|
||||
g.run(&[
|
||||
"update-ref",
|
||||
&backup_ref(machine, stamp, &format!("resolve-local/{branch}")),
|
||||
&head,
|
||||
])?;
|
||||
let mut msg =
|
||||
format!("{branch} moved to the remote tip (local tip kept at backup ref)");
|
||||
if let Choice::SaveAsBranch(name) = choice {
|
||||
if g.probe(&["rev-parse", "-q", "--verify", &format!("refs/heads/{name}")])?
|
||||
.is_some()
|
||||
{
|
||||
return fail(format!("branch {name:?} already exists"));
|
||||
}
|
||||
let root = worktree
|
||||
.parent()
|
||||
.ok_or_else(|| GitError::Other("worktree has no parent dir".into()))?;
|
||||
if !root.join(".bare").is_dir() {
|
||||
return fail("saving as a branch needs the bare + worktrees layout");
|
||||
}
|
||||
let taken: Vec<String> = std::fs::read_dir(root)?
|
||||
.filter_map(Result::ok)
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
let refs: Vec<&str> = taken.iter().map(String::as_str).collect();
|
||||
let dest = root.join(dir_name(name, &refs));
|
||||
g.run(&["branch", name, &head])?;
|
||||
g.run(&["worktree", "add", "-q", &dest.to_string_lossy(), name])?;
|
||||
msg = format!(
|
||||
"local commits saved on branch {name} ({}); {msg}",
|
||||
dest.display()
|
||||
);
|
||||
}
|
||||
g.run(&["reset", "-q", "--hard", &upstream])?;
|
||||
Ok(msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
use crate::git::{Git, GitError};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -10,6 +11,16 @@ pub struct Snapshot {
|
||||
pub commit: String,
|
||||
pub tree: String,
|
||||
pub refname: String,
|
||||
/// Changed files left out because they exceed the size limit.
|
||||
pub skipped: Vec<String>,
|
||||
}
|
||||
|
||||
static MAX_FILE_BYTES: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Process-wide limit: changed files larger than this are left out of snapshots (0 = no limit).
|
||||
/// Set once at startup from `sync.max_file_mb`.
|
||||
pub fn set_max_file_bytes(n: u64) {
|
||||
MAX_FILE_BYTES.store(n, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -43,7 +54,7 @@ fn temp_index_path() -> PathBuf {
|
||||
/// built in a temporary copy of the index so the real index is never modified. The returned
|
||||
/// guard keeps the temporary index alive; `Git` has it set as `GIT_INDEX_FILE` and the author
|
||||
/// identity forced.
|
||||
fn stage(git: &Git) -> Result<(TempIndex, Git, String), GitError> {
|
||||
fn stage(git: &Git) -> Result<(TempIndex, Git, String, Vec<String>), GitError> {
|
||||
let gitdir = PathBuf::from(git.run(&["rev-parse", "--absolute-git-dir"])?);
|
||||
let tmp = TempIndex(temp_index_path());
|
||||
let real_index = gitdir.join("index");
|
||||
@@ -58,8 +69,49 @@ fn stage(git: &Git) -> Result<(TempIndex, Git, String), GitError> {
|
||||
.with_env("GIT_COMMITTER_NAME", "grove")
|
||||
.with_env("GIT_COMMITTER_EMAIL", "grove@localhost");
|
||||
snap.run(&["add", "-A"])?;
|
||||
let skipped = drop_oversized(&snap, git.dir())?;
|
||||
let tree = snap.run(&["write-tree"])?;
|
||||
Ok((tmp, snap, tree))
|
||||
Ok((tmp, snap, tree, skipped))
|
||||
}
|
||||
|
||||
/// Reverts oversized changed files in the temporary index to their HEAD version (or removes them
|
||||
/// when HEAD has none). Returns their paths.
|
||||
fn drop_oversized(snap: &Git, worktree: &Path) -> Result<Vec<String>, GitError> {
|
||||
let limit = MAX_FILE_BYTES.load(Ordering::Relaxed);
|
||||
if limit == 0 {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let has_head = snap
|
||||
.probe(&["rev-parse", "-q", "--verify", "HEAD"])?
|
||||
.is_some();
|
||||
let changed = if has_head {
|
||||
snap.run(&[
|
||||
"diff",
|
||||
"--cached",
|
||||
"--name-only",
|
||||
"-z",
|
||||
"--no-renames",
|
||||
"HEAD",
|
||||
])?
|
||||
} else {
|
||||
snap.run(&["ls-files", "-z"])?
|
||||
};
|
||||
let mut skipped = Vec::new();
|
||||
for rel in changed.split('\0').filter(|p| !p.is_empty()) {
|
||||
let big = std::fs::symlink_metadata(worktree.join(rel))
|
||||
.map(|m| m.is_file() && m.len() > limit)
|
||||
.unwrap_or(false);
|
||||
if !big {
|
||||
continue;
|
||||
}
|
||||
if has_head {
|
||||
snap.run(&["reset", "-q", "HEAD", "--", rel])?;
|
||||
} else {
|
||||
snap.run(&["rm", "--cached", "-q", "--ignore-unmatch", "--", rel])?;
|
||||
}
|
||||
skipped.push(rel.to_string());
|
||||
}
|
||||
Ok(skipped)
|
||||
}
|
||||
|
||||
/// The tree a snapshot of `worktree` would have, without creating any object besides the tree.
|
||||
@@ -75,7 +127,7 @@ pub fn take(worktree: &Path, machine: &str, message_stamp: &str) -> Result<Outco
|
||||
.probe(&["symbolic-ref", "--short", "-q", "HEAD"])?
|
||||
.ok_or_else(|| GitError::Other("detached HEAD: cannot snapshot".into()))?;
|
||||
let refname = ref_name(machine, &branch);
|
||||
let (_tmp, snap, tree) = stage(&git)?;
|
||||
let (_tmp, snap, tree, skipped) = stage(&git)?;
|
||||
|
||||
let prev = snap.probe(&["rev-parse", "-q", "--verify", &refname])?;
|
||||
if let Some(p) = &prev {
|
||||
@@ -101,5 +153,6 @@ pub fn take(worktree: &Path, machine: &str, message_stamp: &str) -> Result<Outco
|
||||
commit,
|
||||
tree,
|
||||
refname,
|
||||
skipped,
|
||||
}))
|
||||
}
|
||||
@@ -31,6 +31,8 @@ pub struct WorktreeReport {
|
||||
pub applied: Option<(String, Applied)>,
|
||||
pub state: State,
|
||||
pub errors: Vec<String>,
|
||||
/// Large files left out of the snapshot (see `sync.max_file_mb`).
|
||||
pub skipped: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
@@ -81,6 +83,7 @@ pub fn sync_repo(path: &Path, o: &Options) -> Result<SyncReport, GitError> {
|
||||
applied: None,
|
||||
state: State::Synced,
|
||||
errors: Vec::new(),
|
||||
skipped: Vec::new(),
|
||||
};
|
||||
if let Some(branch) = &wt.branch {
|
||||
sync_worktree(&mut r, branch, o, rep.fetch_error.is_none());
|
||||
@@ -109,7 +112,10 @@ fn sync_worktree(r: &mut WorktreeReport, branch: &str, o: &Options, fetched: boo
|
||||
// A clean worktree still refreshes an existing snapshot so a stale WIP never lingers.
|
||||
if dirty || has_ref {
|
||||
match take(&path, &o.machine, &o.stamp) {
|
||||
Ok(Outcome::Created(_)) => r.snapshot = Some("created"),
|
||||
Ok(Outcome::Created(s)) => {
|
||||
r.snapshot = Some("created");
|
||||
r.skipped = s.skipped;
|
||||
}
|
||||
Ok(Outcome::Unchanged(_)) => r.snapshot = Some("unchanged"),
|
||||
Err(e) => {
|
||||
r.errors.push(format!("snapshot: {e}"));
|
||||
|
||||
Reference in new issue
Block a user