mirror of
https://github.com/Dasemu/Grove.git
synced 2026-11-26 07:16: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}"));
|
||||
|
||||
@@ -35,6 +35,13 @@ fn new_repo_pushes_and_a_fresh_machine_clones_it_into_the_bare_layout() {
|
||||
let b = base.join("B/g/proj");
|
||||
let made = clone_bare_layout(url, &b, &[]).unwrap();
|
||||
assert_eq!(made.len(), 1);
|
||||
assert_eq!(
|
||||
Git::new(b.join("main"))
|
||||
.run(&["rev-parse", "--abbrev-ref", "@{upstream}"])
|
||||
.unwrap(),
|
||||
"origin/main",
|
||||
"cloned worktrees must track their remote branch"
|
||||
);
|
||||
assert!(b.join("main/.git").exists() && b.join(".bare").is_dir());
|
||||
assert_eq!(
|
||||
Git::new(b.join("main"))
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
mod common;
|
||||
use common::*;
|
||||
use grove_core::git::Git;
|
||||
use grove_core::inspect::state;
|
||||
use grove_core::registry::{clone_bare_layout, init_bare_layout, push_initial};
|
||||
use grove_core::resolve::{Choice, resolve};
|
||||
use grove_core::state::State;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Two machines on the bare layout, both committed on main: diverged on B.
|
||||
fn diverged() -> (PathBuf, PathBuf, PathBuf) {
|
||||
let base = tmpdir("resolve");
|
||||
let remote = base.join("r.git");
|
||||
Git::new(&base)
|
||||
.run(&[
|
||||
"init",
|
||||
"-q",
|
||||
"--bare",
|
||||
"-b",
|
||||
"main",
|
||||
remote.to_str().unwrap(),
|
||||
])
|
||||
.unwrap();
|
||||
let url = remote.to_str().unwrap().to_string();
|
||||
let a = base.join("A");
|
||||
init_bare_layout(&a, &url).unwrap();
|
||||
push_initial(&a, &[]).unwrap();
|
||||
let b = base.join("B");
|
||||
clone_bare_layout(&url, &b, &[]).unwrap();
|
||||
for (root, who) in [(&a, "a"), (&b, "b")] {
|
||||
let g = Git::new(root.join("main"));
|
||||
g.run(&["config", "user.email", "t@t"]).unwrap();
|
||||
g.run(&["config", "user.name", "t"]).unwrap();
|
||||
let _ = who;
|
||||
}
|
||||
// A commits and pushes; B commits locally and fetches.
|
||||
let ga = Git::new(a.join("main"));
|
||||
fs::write(a.join("main/f.txt"), "from A\n").unwrap();
|
||||
ga.run(&["add", "-A"]).unwrap();
|
||||
ga.run(&["commit", "-qm", "a"]).unwrap();
|
||||
ga.run(&["push", "-q"]).unwrap();
|
||||
let gb = Git::new(b.join("main"));
|
||||
fs::write(b.join("main/g.txt"), "from B\n").unwrap();
|
||||
gb.run(&["add", "-A"]).unwrap();
|
||||
gb.run(&["commit", "-qm", "b"]).unwrap();
|
||||
gb.run(&["fetch", "-q"]).unwrap();
|
||||
assert_eq!(state(&b.join("main")), State::Diverged);
|
||||
(base, a, b)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn take_remote_discards_local_commits_but_keeps_a_backup_ref() {
|
||||
let (_base, _a, b) = diverged();
|
||||
let wt = b.join("main");
|
||||
let msg = resolve(&wt, "B", "s1", &Choice::TakeRemote).unwrap();
|
||||
assert!(msg.contains("backup"));
|
||||
let g = Git::new(&wt);
|
||||
assert_eq!(state(&wt), State::Synced);
|
||||
assert!(wt.join("f.txt").exists() && !wt.join("g.txt").exists());
|
||||
let backup = g
|
||||
.run(&["rev-parse", "refs/sync-backup/B/s1/resolve-local/main"])
|
||||
.unwrap();
|
||||
assert!(g.run(&["show", &format!("{backup}:g.txt")]).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_as_branch_keeps_the_local_work_in_its_own_worktree() {
|
||||
let (_base, _a, b) = diverged();
|
||||
let wt = b.join("main");
|
||||
resolve(&wt, "B", "s1", &Choice::SaveAsBranch("b-work".into())).unwrap();
|
||||
assert_eq!(state(&wt), State::Synced);
|
||||
assert!(!wt.join("g.txt").exists());
|
||||
assert_eq!(
|
||||
fs::read_to_string(b.join("b-work/g.txt")).unwrap(),
|
||||
"from B\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keep_local_force_pushes_with_lease_and_backs_up_the_remote_tip() {
|
||||
let (_base, a, b) = diverged();
|
||||
let wt = b.join("main");
|
||||
resolve(&wt, "B", "s1", &Choice::KeepLocal).unwrap();
|
||||
assert_eq!(state(&wt), State::Synced);
|
||||
let ga = Git::new(a.join("main"));
|
||||
ga.run(&["fetch", "-q"]).unwrap();
|
||||
let remote_tree = ga.run(&["ls-tree", "--name-only", "origin/main"]).unwrap();
|
||||
assert!(remote_tree.contains("g.txt") && !remote_tree.contains("f.txt"));
|
||||
let g = Git::new(&wt);
|
||||
assert!(
|
||||
g.run(&["rev-parse", "refs/sync-backup/B/s1/resolve-remote/main"])
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_when_not_diverged_or_when_the_worktree_is_dirty() {
|
||||
let (_base, _a, b) = diverged();
|
||||
let wt = b.join("main");
|
||||
fs::write(wt.join("wip.txt"), "x\n").unwrap();
|
||||
let e = resolve(&wt, "B", "s", &Choice::TakeRemote)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(e.contains("uncommitted"), "{e}");
|
||||
assert!(wt.join("wip.txt").exists() && wt.join("g.txt").exists());
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
//! Own test binary: the limit is process-wide.
|
||||
mod common;
|
||||
use common::*;
|
||||
use grove_core::git::Git;
|
||||
use grove_core::snapshot::{Outcome, set_max_file_bytes, take};
|
||||
use std::fs;
|
||||
|
||||
#[test]
|
||||
fn oversized_changes_are_left_out_but_small_ones_and_head_content_stay() {
|
||||
let base = tmpdir("size");
|
||||
let g = init(&base.join("p"));
|
||||
commit(&g, "tracked.bin", "old\n");
|
||||
set_max_file_bytes(1000);
|
||||
let p = base.join("p");
|
||||
fs::write(p.join("small.txt"), "ok\n").unwrap();
|
||||
fs::write(p.join("big.bin"), vec![b'x'; 5000]).unwrap(); // untracked, too big
|
||||
fs::write(p.join("tracked.bin"), vec![b'y'; 5000]).unwrap(); // tracked, modified, too big
|
||||
let Outcome::Created(s) = take(&p, "A", "t").unwrap() else {
|
||||
panic!("expected a snapshot")
|
||||
};
|
||||
let mut skipped = s.skipped.clone();
|
||||
skipped.sort();
|
||||
assert_eq!(skipped, ["big.bin", "tracked.bin"]);
|
||||
let show = |f: &str| Git::new(&p).run(&["show", &format!("{}:{f}", s.commit)]);
|
||||
assert_eq!(show("small.txt").unwrap(), "ok");
|
||||
assert!(
|
||||
show("big.bin").is_err(),
|
||||
"big untracked file must not be in the snapshot"
|
||||
);
|
||||
assert_eq!(
|
||||
show("tracked.bin").unwrap(),
|
||||
"old",
|
||||
"tracked file keeps its HEAD content"
|
||||
);
|
||||
// The user's real index and files are untouched.
|
||||
assert_eq!(fs::read(p.join("big.bin")).unwrap().len(), 5000);
|
||||
assert!(
|
||||
Git::new(&p)
|
||||
.run(&["status", "--porcelain"])
|
||||
.unwrap()
|
||||
.contains("big.bin")
|
||||
);
|
||||
}
|
||||
@@ -379,8 +379,14 @@ fn pass(
|
||||
let branch = w.branch.clone().unwrap_or_else(|| "(detached)".into());
|
||||
let state = format!("{:?}", w.state).to_lowercase();
|
||||
if let Some(kind) = w.snapshot {
|
||||
ctx.activity
|
||||
.log("snapshot", Some(&name), format!("{branch}: {kind}"));
|
||||
let mut msg = format!("{branch}: {kind}");
|
||||
if !w.skipped.is_empty() {
|
||||
msg.push_str(&format!(
|
||||
" (left out, over the size limit: {})",
|
||||
w.skipped.join(", ")
|
||||
));
|
||||
}
|
||||
ctx.activity.log("snapshot", Some(&name), msg);
|
||||
}
|
||||
match &w.received {
|
||||
Some(Received::FastForwarded { .. }) => {
|
||||
|
||||
@@ -22,6 +22,7 @@ fn main() -> Result<()> {
|
||||
.or_else(Config::default_path)
|
||||
.context("cannot determine config path")?;
|
||||
let cfg = Config::load(&path)?;
|
||||
grove_core::snapshot::set_max_file_bytes(cfg.sync.max_file_mb * 1024 * 1024);
|
||||
let st = Settings::standard();
|
||||
eprintln!(
|
||||
"groved: machine {:?}, root {}, socket {}",
|
||||
|
||||
@@ -5,7 +5,9 @@ use grove_core::git::Git;
|
||||
use grove_core::inspect::{state, worktrees};
|
||||
use grove_core::migrate::migrate;
|
||||
use grove_core::receive::{Applied, Archived, Received};
|
||||
use grove_core::resolve::{Choice, resolve};
|
||||
use grove_core::snapshot::{Outcome, take};
|
||||
use grove_core::state::State;
|
||||
use grove_core::sync::{Options, SyncReport, git_dir_for, sync_repo};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
@@ -28,6 +30,26 @@ enum Cmd {
|
||||
Status {
|
||||
#[arg(default_value = ".")]
|
||||
path: PathBuf,
|
||||
/// Also say what the next sync pass would do (no network, nothing changed)
|
||||
#[arg(long)]
|
||||
plan: bool,
|
||||
},
|
||||
/// Resolve a diverged worktree (an explicit choice; backups are always written)
|
||||
Resolve {
|
||||
/// The worktree directory
|
||||
path: PathBuf,
|
||||
/// Discard local commits, move to the remote tip
|
||||
#[arg(long, group = "how")]
|
||||
take_remote: bool,
|
||||
/// Overwrite the remote branch with the local one
|
||||
#[arg(long, group = "how")]
|
||||
keep_local: bool,
|
||||
/// Keep local commits on a new branch (own worktree), then take the remote tip
|
||||
#[arg(long, value_name = "BRANCH", group = "how")]
|
||||
save_as: Option<String>,
|
||||
/// Open both sides in your difftool and change nothing
|
||||
#[arg(long, group = "how")]
|
||||
compare: bool,
|
||||
},
|
||||
/// Take a snapshot of the worktree at PATH into refs/sync/<machine>/<branch>
|
||||
Snapshot {
|
||||
@@ -207,11 +229,47 @@ fn main() -> Result<()> {
|
||||
let cli = Cli::parse();
|
||||
match &cli.cmd {
|
||||
Cmd::Daemon { action } => daemon(action),
|
||||
Cmd::Status { path } => status(path),
|
||||
Cmd::Status { path, plan } => status(path, *plan),
|
||||
Cmd::Resolve {
|
||||
path,
|
||||
take_remote,
|
||||
keep_local,
|
||||
save_as,
|
||||
compare,
|
||||
} => {
|
||||
let cfg = load_config(&cli.config)?;
|
||||
let choice = match (take_remote, keep_local, save_as, compare) {
|
||||
(true, ..) => Choice::TakeRemote,
|
||||
(_, true, ..) => Choice::KeepLocal,
|
||||
(_, _, Some(b), _) => Choice::SaveAsBranch(b.clone()),
|
||||
(.., true) => {
|
||||
let ok = std::process::Command::new("git")
|
||||
.current_dir(path)
|
||||
.args(["difftool", "-d", "HEAD", "@{upstream}"])
|
||||
.status()?
|
||||
.success();
|
||||
if !ok {
|
||||
bail!("git difftool failed (is a difftool configured?)");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
_ => bail!(
|
||||
"choose one of --take-remote, --keep-local, --save-as <branch>, --compare"
|
||||
),
|
||||
};
|
||||
println!("{}", resolve(path, &cfg.machine.name, &stamp(), &choice)?);
|
||||
Ok(())
|
||||
}
|
||||
Cmd::Snapshot { path } => {
|
||||
let cfg = load_config(&cli.config)?;
|
||||
grove_core::snapshot::set_max_file_bytes(cfg.sync.max_file_mb * 1024 * 1024);
|
||||
match take(path, &cfg.machine.name, &stamp())? {
|
||||
Outcome::Created(s) => println!("created {} {}", s.refname, s.commit),
|
||||
Outcome::Created(s) => {
|
||||
println!("created {} {}", s.refname, s.commit);
|
||||
for f in &s.skipped {
|
||||
println!("left out (over the size limit): {f}");
|
||||
}
|
||||
}
|
||||
Outcome::Unchanged(c) => println!("unchanged {c}"),
|
||||
}
|
||||
Ok(())
|
||||
@@ -234,6 +292,7 @@ fn main() -> Result<()> {
|
||||
}
|
||||
Cmd::Sync { path, offline } => {
|
||||
let cfg = load_config(&cli.config)?;
|
||||
grove_core::snapshot::set_max_file_bytes(cfg.sync.max_file_mb * 1024 * 1024);
|
||||
let rep = sync_repo(
|
||||
path,
|
||||
&Options {
|
||||
@@ -324,15 +383,29 @@ fn main() -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
fn status(path: &Path) -> Result<()> {
|
||||
fn plan_for(s: &State) -> &'static str {
|
||||
match s {
|
||||
State::Synced => "nothing to do",
|
||||
State::Dirty => "snapshot the working changes and push the snapshot ref",
|
||||
State::Ahead => "nothing automatic: push your commits yourself",
|
||||
State::Behind => "fast-forward to the remote tip",
|
||||
State::BehindDirty => {
|
||||
"keep your edits; adopt the remote tip only if the content is identical"
|
||||
}
|
||||
State::Diverged => "nothing automatic: run `grove resolve` to choose",
|
||||
State::Error(_) => "retry; see the error",
|
||||
}
|
||||
}
|
||||
|
||||
fn status(path: &Path, plan: bool) -> Result<()> {
|
||||
for wt in worktrees(&git_dir_for(path))? {
|
||||
let branch = wt.branch.as_deref().unwrap_or("(detached)");
|
||||
println!(
|
||||
"{:<24} {:?} {}",
|
||||
branch,
|
||||
state(&wt.path),
|
||||
wt.path.display()
|
||||
);
|
||||
let st = state(&wt.path);
|
||||
print!("{:<24} {:?} {}", branch, st, wt.path.display());
|
||||
if plan {
|
||||
print!("\n next: {}", plan_for(&st));
|
||||
}
|
||||
println!();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -362,6 +435,9 @@ fn print_report(rep: &SyncReport) -> Result<()> {
|
||||
if let Some(s) = w.snapshot {
|
||||
notes.push(format!("snapshot {s}"));
|
||||
}
|
||||
if !w.skipped.is_empty() {
|
||||
notes.push(format!("left out (too large): {}", w.skipped.join(", ")));
|
||||
}
|
||||
match &w.received {
|
||||
Some(Received::FastForwarded { .. }) => notes.push("fast-forwarded".into()),
|
||||
Some(Received::Declined(why)) => notes.push(format!("not fast-forwarded: {why}")),
|
||||
|
||||
Reference in new issue
Block a user