mirror of
https://github.com/Dasemu/Grove.git
synced 2026-11-26 23:36:11 +00:00
feat(daemon): move repos deleted on their forge to Purged/
When a fetch fails with a not-found error, the daemon asks the forge: a 404 for a repo owned by the token's account (or an `owners` org), with a working token, still confirmed 10 min later, moves the repo to root/<sync.purged_dir>/<group>/<repo> (default "Purged"), where it is no longer synced. Never deleted; worktree links repaired; skipped while busy or with a git operation in progress. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9340a436d5
commit
d1d1fa29f3
5 files changed
+574
-1
No files matched your search
@@ -155,6 +155,10 @@ pub struct Sync {
|
|||||||
/// Default snapshot push policy; a group can override it.
|
/// Default snapshot push policy; a group can override it.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub snapshots: SnapshotPolicy,
|
pub snapshots: SnapshotPolicy,
|
||||||
|
/// Directory under the root that repos deleted on their forge are moved to (and so stop
|
||||||
|
/// syncing). Empty disables the move.
|
||||||
|
#[serde(default = "default_purged_dir")]
|
||||||
|
pub purged_dir: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for Sync {
|
impl Default for Sync {
|
||||||
@@ -165,6 +169,7 @@ impl Default for Sync {
|
|||||||
ignore_extra: Vec::new(),
|
ignore_extra: Vec::new(),
|
||||||
max_file_mb: default_max_file_mb(),
|
max_file_mb: default_max_file_mb(),
|
||||||
snapshots: SnapshotPolicy::default(),
|
snapshots: SnapshotPolicy::default(),
|
||||||
|
purged_dir: default_purged_dir(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -184,6 +189,9 @@ fn default_debounce() -> u64 {
|
|||||||
fn default_max_file_mb() -> u64 {
|
fn default_max_file_mb() -> u64 {
|
||||||
50
|
50
|
||||||
}
|
}
|
||||||
|
fn default_purged_dir() -> String {
|
||||||
|
"Purged".into()
|
||||||
|
}
|
||||||
fn default_fetch() -> u64 {
|
fn default_fetch() -> u64 {
|
||||||
60
|
60
|
||||||
}
|
}
|
||||||
@@ -275,6 +283,19 @@ impl Config {
|
|||||||
"machine.name {n:?} must be non-empty and use only letters, digits, '-' or '_'"
|
"machine.name {n:?} must be non-empty and use only letters, digits, '-' or '_'"
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
let pd = &self.sync.purged_dir;
|
||||||
|
if !pd.is_empty() {
|
||||||
|
if pd.starts_with('.') || pd.contains(['/', '\\']) {
|
||||||
|
return bad(format!(
|
||||||
|
"sync.purged_dir {pd:?} must be a plain directory name"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if self.groups.iter().any(|g| &g.name == pd) {
|
||||||
|
return bad(format!(
|
||||||
|
"sync.purged_dir {pd:?} is also a group: purged repos would keep syncing"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
for g in &self.groups {
|
for g in &self.groups {
|
||||||
// Group names are directory names under the root.
|
// Group names are directory names under the root.
|
||||||
if g.name.is_empty() || g.name.starts_with('.') || g.name.contains(['/', '\\']) {
|
if g.name.is_empty() || g.name.starts_with('.') || g.name.contains(['/', '\\']) {
|
||||||
@@ -383,6 +404,24 @@ name = "grove-config"
|
|||||||
assert_eq!(c.root_path(), PathBuf::from("/x"));
|
assert_eq!(c.root_path(), PathBuf::from("/x"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn purged_dir_defaults_and_must_not_be_a_group() {
|
||||||
|
let base = "[machine]\nname=\"a\"\n[root]\npath=\"/x\"\n[providers.p]\nkind=\"github\"\n";
|
||||||
|
assert_eq!(Config::parse(base).unwrap().sync.purged_dir, "Purged");
|
||||||
|
let off = format!("{base}[sync]\npurged_dir=\"\"\n");
|
||||||
|
assert_eq!(Config::parse(&off).unwrap().sync.purged_dir, "");
|
||||||
|
for bad in [
|
||||||
|
format!("{base}[sync]\npurged_dir=\"a/b\"\n"),
|
||||||
|
format!("{base}[sync]\npurged_dir=\".x\"\n"),
|
||||||
|
format!("{base}[[groups]]\nname=\"Purged\"\nprimary=\"p\"\n"),
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
matches!(Config::parse(&bad), Err(ConfigError::Invalid(_))),
|
||||||
|
"{bad}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rejects_unsafe_machine_name() {
|
fn rejects_unsafe_machine_name() {
|
||||||
for n in ["", "a/b", "a b", "a..b"] {
|
for n in ["", "a/b", "a b", "a..b"] {
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
use crate::activity::{Activity, now_secs};
|
use crate::activity::{Activity, now_secs};
|
||||||
use crate::discover::{discover, group_of, is_ready, subdirs};
|
use crate::discover::{discover, group_of, is_ready, subdirs};
|
||||||
use crate::ipc;
|
use crate::ipc;
|
||||||
|
use crate::purge;
|
||||||
use crate::visibility::{RealForge, Visibility, snapshot_gate};
|
use crate::visibility::{RealForge, Visibility, snapshot_gate};
|
||||||
use grove_core::config::Config;
|
use grove_core::config::Config;
|
||||||
use grove_core::receive::Received;
|
use grove_core::receive::Received;
|
||||||
@@ -426,6 +427,8 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
|||||||
let mut next_full = Instant::now();
|
let mut next_full = Instant::now();
|
||||||
// When a debounced rediscovery is due (set by the first event of a burst, never pushed back).
|
// When a debounced rediscovery is due (set by the first event of a burst, never pushed back).
|
||||||
let mut rescan_at: Option<Instant> = None;
|
let mut rescan_at: Option<Instant> = None;
|
||||||
|
// Repos whose forge first confirmed their deletion at this time (see `purge`).
|
||||||
|
let mut gone_since: HashMap<PathBuf, (u64, u64)> = HashMap::new();
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
let now = Instant::now();
|
let now = Instant::now();
|
||||||
@@ -515,7 +518,15 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
|||||||
// While backing off after a failure, still snapshot local work (no network needed);
|
// While backing off after a failure, still snapshot local work (no network needed);
|
||||||
// the network is retried at the first pass after the backoff expires.
|
// the network is retried at the first pass after the backoff expires.
|
||||||
let offline = backoff_until.get(&r).is_some_and(|u| *u > now);
|
let offline = backoff_until.get(&r).is_some_and(|u| *u > now);
|
||||||
let failures = pass(&r, &cfg, &st, &mut visibility, offline, &ctx);
|
let failures = pass(
|
||||||
|
&r,
|
||||||
|
&cfg,
|
||||||
|
&st,
|
||||||
|
&mut visibility,
|
||||||
|
offline,
|
||||||
|
&mut gone_since,
|
||||||
|
&ctx,
|
||||||
|
);
|
||||||
if !is_ready(&r) {
|
if !is_ready(&r) {
|
||||||
// It vanished mid-pass: whatever the pass reported is moot.
|
// It vanished mid-pass: whatever the pass reported is moot.
|
||||||
let (found, _) = rescan(&root, &groups, &mut watch, &ctx);
|
let (found, _) = rescan(&root, &groups, &mut watch, &ctx);
|
||||||
@@ -559,6 +570,7 @@ fn pass(
|
|||||||
st: &Settings,
|
st: &Settings,
|
||||||
visibility: &mut Visibility,
|
visibility: &mut Visibility,
|
||||||
offline: bool,
|
offline: bool,
|
||||||
|
gone_since: &mut HashMap<PathBuf, (u64, u64)>,
|
||||||
ctx: &Ctx,
|
ctx: &Ctx,
|
||||||
) -> u32 {
|
) -> u32 {
|
||||||
let name = repo.display().to_string();
|
let name = repo.display().to_string();
|
||||||
@@ -600,6 +612,9 @@ fn pass(
|
|||||||
push_snapshots,
|
push_snapshots,
|
||||||
};
|
};
|
||||||
let result = sync_repo(repo, &opts);
|
let result = sync_repo(repo, &opts);
|
||||||
|
if !offline && purge_if_gone(repo, cfg, st, &result, gone_since, ctx) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
let mut shared = ctx.shared.lock().unwrap();
|
let mut shared = ctx.shared.lock().unwrap();
|
||||||
// The repo may have been dropped by a rediscovery while the pass ran.
|
// The repo may have been dropped by a rediscovery while the pass ran.
|
||||||
let Some(status) = shared.repos.get_mut(repo) else {
|
let Some(status) = shared.repos.get_mut(repo) else {
|
||||||
@@ -693,6 +708,114 @@ fn pass(
|
|||||||
status.failures
|
status.failures
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Moves `repo` out of the synced tree once its forge has kept confirming its deletion for
|
||||||
|
/// `purge::CONFIRM_AFTER_SECS`; returns true when it is gone from its place. A fetch that works,
|
||||||
|
/// or the forge seeing the repo, clears it; so does a gap of more than twice that interval
|
||||||
|
/// between confirmations.
|
||||||
|
fn purge_if_gone(
|
||||||
|
repo: &Path,
|
||||||
|
cfg: &Config,
|
||||||
|
st: &Settings,
|
||||||
|
result: &Result<grove_core::sync::SyncReport, grove_core::git::GitError>,
|
||||||
|
gone_since: &mut HashMap<PathBuf, (u64, u64)>,
|
||||||
|
ctx: &Ctx,
|
||||||
|
) -> bool {
|
||||||
|
let name = repo.display().to_string();
|
||||||
|
let hint = match result {
|
||||||
|
Ok(rep) => rep.fetch_error.as_deref().is_some_and(purge::looks_gone),
|
||||||
|
Err(_) => false,
|
||||||
|
};
|
||||||
|
if !hint || cfg.sync.purged_dir.is_empty() {
|
||||||
|
if matches!(result, Ok(rep) if rep.fetch_error.is_none()) {
|
||||||
|
gone_since.remove(repo);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
match purge::confirmed_gone(cfg, repo, &st.remote, &RealForge) {
|
||||||
|
Ok(true) => {}
|
||||||
|
Ok(false) => {
|
||||||
|
gone_since.remove(repo);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// Cannot tell (network, token): keep whatever was confirmed before.
|
||||||
|
Err(_) => return false,
|
||||||
|
}
|
||||||
|
let now = now_secs();
|
||||||
|
let window = purge::CONFIRM_AFTER_SECS;
|
||||||
|
let entry = gone_since.entry(repo.to_path_buf()).or_insert((now, now));
|
||||||
|
if now.saturating_sub(entry.1) > 2 * window {
|
||||||
|
// Stale: start over.
|
||||||
|
*entry = (now, now);
|
||||||
|
}
|
||||||
|
entry.1 = now;
|
||||||
|
let first = entry.0;
|
||||||
|
if first == now {
|
||||||
|
ctx.activity.log(
|
||||||
|
"purge_pending",
|
||||||
|
Some(&name),
|
||||||
|
format!(
|
||||||
|
"the forge reports the remote repo deleted; moving it to {}/ if that still holds in {} min",
|
||||||
|
cfg.sync.purged_dir,
|
||||||
|
window / 60
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if now.saturating_sub(first) < window {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let Some(dest) = purge::destination(&cfg.root_path(), &cfg.sync.purged_dir, repo, &stamp())
|
||||||
|
else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let gone = |ctx: &Ctx, gone_since: &mut HashMap<PathBuf, (u64, u64)>| {
|
||||||
|
gone_since.remove(repo);
|
||||||
|
ctx.shared.lock().unwrap().repos.remove(repo);
|
||||||
|
};
|
||||||
|
match purge::move_repo(repo, &dest) {
|
||||||
|
Ok(moved) => {
|
||||||
|
gone(ctx, gone_since);
|
||||||
|
let mut msg = format!(
|
||||||
|
"remote repo deleted: moved to {} (no longer synced; files untouched)",
|
||||||
|
dest.display()
|
||||||
|
);
|
||||||
|
if !moved.unrepaired.is_empty() {
|
||||||
|
let list: Vec<String> = moved
|
||||||
|
.unrepaired
|
||||||
|
.iter()
|
||||||
|
.map(|p| p.display().to_string())
|
||||||
|
.collect();
|
||||||
|
msg.push_str(&format!(
|
||||||
|
"; worktrees not found, run `git worktree repair <path>` from {}/.bare once they are back: {}",
|
||||||
|
dest.display(),
|
||||||
|
list.join(", ")
|
||||||
|
));
|
||||||
|
}
|
||||||
|
ctx.activity.log("purged", Some(&name), msg);
|
||||||
|
true
|
||||||
|
}
|
||||||
|
Err(purge::MoveError::Repair(e)) => {
|
||||||
|
gone(ctx, gone_since);
|
||||||
|
ctx.activity.log(
|
||||||
|
"purged",
|
||||||
|
Some(&name),
|
||||||
|
format!(
|
||||||
|
"remote repo deleted: moved to {}, but repairing its worktree links failed ({e}); run `git worktree repair` there",
|
||||||
|
dest.display()
|
||||||
|
),
|
||||||
|
);
|
||||||
|
true
|
||||||
|
}
|
||||||
|
Err(purge::MoveError::NotMoved(e)) => {
|
||||||
|
ctx.activity.log(
|
||||||
|
"purge_failed",
|
||||||
|
Some(&name),
|
||||||
|
format!("not moved to {}: {e}", dest.display()),
|
||||||
|
);
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Records why snapshots are withheld (or that they are pushed again), logging only changes.
|
/// Records why snapshots are withheld (or that they are pushed again), logging only changes.
|
||||||
fn note_snapshot_gate(ctx: &Ctx, repo: &Path, name: &str, withheld: Option<String>) {
|
fn note_snapshot_gate(ctx: &Ctx, repo: &Path, name: &str, withheld: Option<String>) {
|
||||||
let mut shared = ctx.shared.lock().unwrap();
|
let mut shared = ctx.shared.lock().unwrap();
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ pub mod activity;
|
|||||||
pub mod daemon;
|
pub mod daemon;
|
||||||
pub mod discover;
|
pub mod discover;
|
||||||
pub mod ipc;
|
pub mod ipc;
|
||||||
|
pub mod purge;
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
#[path = "../../../test-support/tmp.rs"]
|
#[path = "../../../test-support/tmp.rs"]
|
||||||
mod test_tmp;
|
mod test_tmp;
|
||||||
|
|||||||
@@ -0,0 +1,378 @@
|
|||||||
|
//! Repos deleted on their forge are moved out of the synced tree, never deleted locally.
|
||||||
|
//!
|
||||||
|
//! A fetch error alone never moves anything: the forge must answer 404 for a repo the token's
|
||||||
|
//! account owns (its login, or an organisation named in a group's `owners`) while that token
|
||||||
|
//! works, and must still do so [`CONFIRM_AFTER_SECS`] after the first confirmation. The repo then
|
||||||
|
//! moves to `root/<sync.purged_dir>/<group>/<repo>`, which is not a configured group, so it is no
|
||||||
|
//! longer synced; its worktree links are repaired.
|
||||||
|
|
||||||
|
use crate::visibility::{Forge, Seen, parse_remote, provider_for};
|
||||||
|
use grove_core::busy::BusyGuard;
|
||||||
|
use grove_core::config::Config;
|
||||||
|
use grove_core::git::Git;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
/// How long a remote deletion must keep being confirmed before the repo is moved.
|
||||||
|
pub const CONFIRM_AFTER_SECS: u64 = 600;
|
||||||
|
|
||||||
|
/// Fetch failures that may mean the remote repo is gone (only a hint; see [`confirmed_gone`]).
|
||||||
|
pub fn looks_gone(fetch_error: &str) -> bool {
|
||||||
|
let e = fetch_error.to_ascii_lowercase();
|
||||||
|
[
|
||||||
|
"not found",
|
||||||
|
"does not appear to be a git repository",
|
||||||
|
"does not exist",
|
||||||
|
"error: 404",
|
||||||
|
]
|
||||||
|
.iter()
|
||||||
|
.any(|p| e.contains(p))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True only when the forge serving `remote` answers 404 for a repo owned by the token's own
|
||||||
|
/// account or by an organisation the config names in some group's `owners`, while that token
|
||||||
|
/// works. A repo of someone else (made private, or access revoked) is never reported gone.
|
||||||
|
pub fn confirmed_gone(
|
||||||
|
cfg: &Config,
|
||||||
|
repo: &Path,
|
||||||
|
remote: &str,
|
||||||
|
forge: &dyn Forge,
|
||||||
|
) -> Result<bool, String> {
|
||||||
|
let url = Git::new(repo.join(".bare"))
|
||||||
|
.run(&["remote", "get-url", remote])
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let id = parse_remote(&url).ok_or_else(|| format!("cannot parse remote URL {url:?}"))?;
|
||||||
|
let (pid, pc) = provider_for(cfg, &id)?;
|
||||||
|
// A 404 from a broken or foreign token proves nothing.
|
||||||
|
let login = forge.login(pid, pc)?;
|
||||||
|
let owned = id.owner.eq_ignore_ascii_case(&login)
|
||||||
|
|| cfg.groups.iter().any(|g| {
|
||||||
|
g.owners
|
||||||
|
.get(pid)
|
||||||
|
.is_some_and(|o| o.eq_ignore_ascii_case(&id.owner))
|
||||||
|
});
|
||||||
|
if !owned {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
Ok(forge.seen(pid, pc, &id.owner, &id.name)? == Seen::Absent)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where `repo` (`root/<group>/<name>`) goes: `root/<purged_dir>/<group>/<name>`, with a
|
||||||
|
/// `-<stamp>` suffix when that is taken.
|
||||||
|
pub fn destination(root: &Path, purged_dir: &str, repo: &Path, stamp: &str) -> Option<PathBuf> {
|
||||||
|
let name = repo.file_name()?;
|
||||||
|
let group = repo.parent()?.file_name()?;
|
||||||
|
let dir = root.join(purged_dir).join(group);
|
||||||
|
let first = dir.join(name);
|
||||||
|
if !first.exists() {
|
||||||
|
return Some(first);
|
||||||
|
}
|
||||||
|
Some(dir.join(format!("{}-{stamp}", name.to_string_lossy())))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum MoveError {
|
||||||
|
/// Nothing was moved (busy, an operation in progress, cross-device...).
|
||||||
|
NotMoved(String),
|
||||||
|
/// The repo is at its destination, but some worktree links could not be repaired.
|
||||||
|
Repair(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A finished move: worktrees whose directory was missing (unmounted disk, prunable) could not
|
||||||
|
/// be repaired; `git worktree repair <path>` from the new `.bare` fixes them later.
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
pub struct Moved {
|
||||||
|
pub unrepaired: Vec<PathBuf>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An operation in progress in some worktree (or the repo) that a move would break.
|
||||||
|
fn in_progress(repo: &Path, wts: &[PathBuf]) -> Option<String> {
|
||||||
|
if repo.join(".grove-stage").exists() {
|
||||||
|
return Some("an interrupted grove operation left .grove-stage".into());
|
||||||
|
}
|
||||||
|
for w in wts.iter().filter(|w| w.exists()) {
|
||||||
|
let Ok(gd) = Git::new(w).run(&["rev-parse", "--absolute-git-dir"]) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let gd = PathBuf::from(gd);
|
||||||
|
for f in [
|
||||||
|
"index.lock",
|
||||||
|
"rebase-merge",
|
||||||
|
"rebase-apply",
|
||||||
|
"MERGE_HEAD",
|
||||||
|
"CHERRY_PICK_HEAD",
|
||||||
|
"REVERT_HEAD",
|
||||||
|
"BISECT_LOG",
|
||||||
|
] {
|
||||||
|
if gd.join(f).exists() {
|
||||||
|
return Some(format!("{}: {f} (git operation in progress)", w.display()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves the bare-layout repo to `dest` (same file system) and repairs every worktree link:
|
||||||
|
/// worktrees inside the repo move with it, linked ones elsewhere are pointed at the new `.bare`.
|
||||||
|
/// Holds `.grove-busy` while moving and refuses while a git operation is in progress.
|
||||||
|
pub fn move_repo(repo: &Path, dest: &Path) -> Result<Moved, MoveError> {
|
||||||
|
let not = |m: String| MoveError::NotMoved(m);
|
||||||
|
// git reports worktree paths resolved (symlinks followed): compare against resolved paths.
|
||||||
|
let real_repo = repo
|
||||||
|
.canonicalize()
|
||||||
|
.map_err(|e| not(format!("{}: {e}", repo.display())))?;
|
||||||
|
let bare = real_repo.join(".bare");
|
||||||
|
let list = Git::new(&bare)
|
||||||
|
.run(&["worktree", "list", "--porcelain"])
|
||||||
|
.map_err(|e| not(e.to_string()))?;
|
||||||
|
let wts: Vec<PathBuf> = list
|
||||||
|
.lines()
|
||||||
|
.filter_map(|l| l.strip_prefix("worktree "))
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.filter(|p| *p != bare)
|
||||||
|
.collect();
|
||||||
|
let guard =
|
||||||
|
BusyGuard::acquire(&real_repo).map_err(|e| not(format!("repo busy (.grove-busy): {e}")))?;
|
||||||
|
if let Some(why) = in_progress(&real_repo, &wts) {
|
||||||
|
return Err(not(why));
|
||||||
|
}
|
||||||
|
if let Some(parent) = dest.parent() {
|
||||||
|
std::fs::create_dir_all(parent).map_err(|e| not(format!("{}: {e}", parent.display())))?;
|
||||||
|
}
|
||||||
|
// A rename never copies: across file systems it fails and the repo stays where it was.
|
||||||
|
std::fs::rename(&real_repo, dest)
|
||||||
|
.map_err(|e| not(format!("cannot move to {}: {e}", dest.display())))?;
|
||||||
|
// The marker moved with the repo: the guard's old path is gone, remove the moved one.
|
||||||
|
drop(guard);
|
||||||
|
let _ = std::fs::remove_file(dest.join(".grove-busy"));
|
||||||
|
let real_dest = dest.canonicalize().unwrap_or_else(|_| dest.to_path_buf());
|
||||||
|
let mut moved = Moved::default();
|
||||||
|
let mut repair: Vec<String> = Vec::new();
|
||||||
|
for w in &wts {
|
||||||
|
let now = match w.strip_prefix(&real_repo) {
|
||||||
|
Ok(rel) => real_dest.join(rel),
|
||||||
|
Err(_) => w.clone(),
|
||||||
|
};
|
||||||
|
if now.exists() {
|
||||||
|
repair.push(now.display().to_string());
|
||||||
|
} else {
|
||||||
|
moved.unrepaired.push(now);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !repair.is_empty() {
|
||||||
|
let mut args = vec!["worktree", "repair"];
|
||||||
|
args.extend(repair.iter().map(String::as_str));
|
||||||
|
Git::new(real_dest.join(".bare"))
|
||||||
|
.run(&args)
|
||||||
|
.map_err(|e| MoveError::Repair(e.to_string()))?;
|
||||||
|
}
|
||||||
|
Ok(moved)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::test_tmp as tmp;
|
||||||
|
use grove_core::config::Provider as ProviderCfg;
|
||||||
|
use std::cell::Cell;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_not_found_style_fetch_errors_are_hints() {
|
||||||
|
assert!(looks_gone(
|
||||||
|
"git fetch failed (Some(128)): ERROR: Repository not found."
|
||||||
|
));
|
||||||
|
assert!(looks_gone(
|
||||||
|
"fatal: 'x.git' does not appear to be a git repository"
|
||||||
|
));
|
||||||
|
assert!(!looks_gone(
|
||||||
|
"ssh: connect to host h port 22: Connection timed out"
|
||||||
|
));
|
||||||
|
assert!(!looks_gone("fatal: Authentication failed"));
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Fake {
|
||||||
|
login_ok: bool,
|
||||||
|
seen: Seen,
|
||||||
|
lookups: Cell<u32>,
|
||||||
|
}
|
||||||
|
impl Forge for Fake {
|
||||||
|
fn seen(&self, _: &str, _: &ProviderCfg, _: &str, _: &str) -> Result<Seen, String> {
|
||||||
|
self.lookups.set(self.lookups.get() + 1);
|
||||||
|
Ok(self.seen)
|
||||||
|
}
|
||||||
|
fn login(&self, _: &str, _: &ProviderCfg) -> Result<String, String> {
|
||||||
|
if self.login_ok {
|
||||||
|
Ok("me".into())
|
||||||
|
} else {
|
||||||
|
Err("401".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn git(dir: &Path, args: &[&str]) {
|
||||||
|
Git::new(dir).run(args).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `base/root/G/r` in bare layout with a `main` worktree and a linked one outside the repo.
|
||||||
|
fn bare_repo(base: &Path) -> (PathBuf, PathBuf) {
|
||||||
|
let repo = base.join("root/G/r");
|
||||||
|
std::fs::create_dir_all(&repo).unwrap();
|
||||||
|
let bare = repo.join(".bare");
|
||||||
|
git(
|
||||||
|
base,
|
||||||
|
&["init", "-q", "--bare", "-b", "main", bare.to_str().unwrap()],
|
||||||
|
);
|
||||||
|
git(
|
||||||
|
&bare,
|
||||||
|
&["remote", "add", "origin", "https://git.example.es/me/r.git"],
|
||||||
|
);
|
||||||
|
let main = repo.join("main");
|
||||||
|
git(
|
||||||
|
&bare,
|
||||||
|
&[
|
||||||
|
"worktree",
|
||||||
|
"add",
|
||||||
|
"-q",
|
||||||
|
"--orphan",
|
||||||
|
"-b",
|
||||||
|
"main",
|
||||||
|
main.to_str().unwrap(),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
std::fs::write(main.join("f"), "x").unwrap();
|
||||||
|
git(&main, &["add", "f"]);
|
||||||
|
git(
|
||||||
|
&main,
|
||||||
|
&[
|
||||||
|
"-c",
|
||||||
|
"user.name=t",
|
||||||
|
"-c",
|
||||||
|
"user.email=t@t",
|
||||||
|
"commit",
|
||||||
|
"-qm",
|
||||||
|
"c",
|
||||||
|
],
|
||||||
|
);
|
||||||
|
let ext = base.join("elsewhere");
|
||||||
|
git(
|
||||||
|
&bare,
|
||||||
|
&["worktree", "add", "-q", "-b", "side", ext.to_str().unwrap()],
|
||||||
|
);
|
||||||
|
(repo, ext)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cfg() -> Config {
|
||||||
|
Config::parse(
|
||||||
|
"[machine]\nname=\"m\"\n[root]\npath=\"/x\"\n\
|
||||||
|
[providers.gitea]\nkind=\"gitea\"\nurl=\"https://git.example.es\"\n",
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_404_counts_only_with_a_working_token() {
|
||||||
|
let d = tmp::TempDir::new("purge-confirm");
|
||||||
|
let (repo, _) = bare_repo(d.path());
|
||||||
|
let cfg = cfg();
|
||||||
|
let gone = |login_ok, seen| {
|
||||||
|
let f = Fake {
|
||||||
|
login_ok,
|
||||||
|
seen,
|
||||||
|
lookups: Cell::new(0),
|
||||||
|
};
|
||||||
|
confirmed_gone(&cfg, &repo, "origin", &f)
|
||||||
|
};
|
||||||
|
assert_eq!(gone(true, Seen::Absent), Ok(true));
|
||||||
|
assert_eq!(gone(true, Seen::Private), Ok(false));
|
||||||
|
assert!(gone(false, Seen::Absent).is_err());
|
||||||
|
// Someone else's repo (made private, access revoked) is never "gone".
|
||||||
|
git(
|
||||||
|
&repo.join(".bare"),
|
||||||
|
&[
|
||||||
|
"remote",
|
||||||
|
"set-url",
|
||||||
|
"origin",
|
||||||
|
"https://git.example.es/other/r.git",
|
||||||
|
],
|
||||||
|
);
|
||||||
|
let f = Fake {
|
||||||
|
login_ok: true,
|
||||||
|
seen: Seen::Absent,
|
||||||
|
lookups: Cell::new(0),
|
||||||
|
};
|
||||||
|
assert_eq!(confirmed_gone(&cfg, &repo, "origin", &f), Ok(false));
|
||||||
|
assert_eq!(f.lookups.get(), 0);
|
||||||
|
// ...unless the config names that organisation as an owner.
|
||||||
|
let org = Config::parse(
|
||||||
|
"[machine]\nname=\"m\"\n[root]\npath=\"/x\"\n\
|
||||||
|
[providers.gitea]\nkind=\"gitea\"\nurl=\"https://git.example.es\"\n\
|
||||||
|
[[groups]]\nname=\"G\"\nprimary=\"gitea\"\nowners={gitea=\"Other\"}\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(confirmed_gone(&org, &repo, "origin", &f), Ok(true));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn moving_keeps_every_worktree_working() {
|
||||||
|
let d = tmp::TempDir::new("purge-move");
|
||||||
|
let (repo, ext) = bare_repo(d.path());
|
||||||
|
let root = d.path().join("root");
|
||||||
|
let dest = destination(&root, "Purged", &repo, "1").unwrap();
|
||||||
|
assert_eq!(dest, root.join("Purged/G/r"));
|
||||||
|
move_repo(&repo, &dest).unwrap();
|
||||||
|
assert!(!repo.exists());
|
||||||
|
for wt in [dest.join("main"), ext.clone()] {
|
||||||
|
let st = Git::new(&wt).run(&["status", "--porcelain"]);
|
||||||
|
assert!(st.is_ok(), "{}: {st:?}", wt.display());
|
||||||
|
}
|
||||||
|
let list = Git::new(dest.join(".bare"))
|
||||||
|
.run(&["worktree", "list", "--porcelain"])
|
||||||
|
.unwrap();
|
||||||
|
assert!(list.contains(&dest.join("main").display().to_string()));
|
||||||
|
assert!(!list.contains("prunable"), "{list}");
|
||||||
|
// A second repo of the same name does not overwrite the first.
|
||||||
|
std::fs::create_dir_all(&repo).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
destination(&root, "Purged", &repo, "7").unwrap(),
|
||||||
|
root.join("Purged/G/r-7")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn moving_through_a_symlinked_root_repairs_the_worktrees() {
|
||||||
|
let d = tmp::TempDir::new("purge-symlink");
|
||||||
|
std::fs::create_dir_all(d.path().join("real")).unwrap();
|
||||||
|
std::os::unix::fs::symlink(d.path().join("real"), d.path().join("link")).unwrap();
|
||||||
|
let base = d.path().join("link");
|
||||||
|
let (repo, ext) = bare_repo(&base);
|
||||||
|
let dest = destination(&base.join("root"), "Purged", &repo, "1").unwrap();
|
||||||
|
let moved = move_repo(&repo, &dest).unwrap();
|
||||||
|
assert!(moved.unrepaired.is_empty());
|
||||||
|
for wt in [dest.join("main"), ext] {
|
||||||
|
assert!(Git::new(&wt).run(&["status"]).is_ok(), "{}", wt.display());
|
||||||
|
}
|
||||||
|
assert!(!dest.join(".grove-busy").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_busy_repo_or_a_git_operation_in_progress_is_left_alone() {
|
||||||
|
let d = tmp::TempDir::new("purge-busy");
|
||||||
|
let (repo, _) = bare_repo(d.path());
|
||||||
|
let dest = d.path().join("root/Purged/G/r");
|
||||||
|
std::fs::write(repo.join(".grove-busy"), "1 1\n").unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
move_repo(&repo, &dest),
|
||||||
|
Err(MoveError::NotMoved(_))
|
||||||
|
));
|
||||||
|
std::fs::remove_file(repo.join(".grove-busy")).unwrap();
|
||||||
|
let gd = Git::new(repo.join("main"))
|
||||||
|
.run(&["rev-parse", "--absolute-git-dir"])
|
||||||
|
.unwrap();
|
||||||
|
std::fs::write(Path::new(&gd).join("MERGE_HEAD"), "x").unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
move_repo(&repo, &dest),
|
||||||
|
Err(MoveError::NotMoved(_))
|
||||||
|
));
|
||||||
|
assert!(repo.join(".bare").is_dir() && !dest.exists());
|
||||||
|
assert!(!repo.join(".grove-busy").exists());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -118,6 +118,38 @@ groups are only picked up then).
|
|||||||
**Breaking change:** group names must now be plain directory names (non-empty, no `/`, no leading
|
**Breaking change:** group names must now be plain directory names (non-empty, no `/`, no leading
|
||||||
`.`); a config with other names no longer loads.
|
`.`); a config with other names no longer loads.
|
||||||
|
|
||||||
|
### Repos deleted on the forge
|
||||||
|
|
||||||
|
A managed repo whose remote was deleted is moved out of the synced tree, never deleted locally:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[sync]
|
||||||
|
purged_dir = "Purged" # default; "" disables the move
|
||||||
|
```
|
||||||
|
|
||||||
|
- Trigger: a fetch fails with a "not found"-style error. That is only a hint: the forge serving
|
||||||
|
`origin` must then answer 404 while the same token works (`test_connection`), and still do so
|
||||||
|
`purge::CONFIRM_AFTER_SECS` (10 min) after the first confirmation (a gap of more than twice
|
||||||
|
that starts over). A working fetch, or the forge seeing the repo again, clears it. Network or
|
||||||
|
token errors change nothing.
|
||||||
|
- Only repos owned by the token's account, or by an organisation named in some group's `owners`
|
||||||
|
for that provider, are ever moved: someone else's repo turning private or revoking access looks
|
||||||
|
the same as a deletion. Being removed from one of your own `owners` organisations is still
|
||||||
|
indistinguishable and moves its repos.
|
||||||
|
- Never while busy: the move holds `.grove-busy` and is skipped (`purge_failed`, retried next
|
||||||
|
pass) when `.grove-stage` exists or a worktree has a git operation in progress (`index.lock`,
|
||||||
|
rebase, merge, cherry-pick, revert, bisect).
|
||||||
|
- Action: `root/<group>/<repo>` moves to `root/<purged_dir>/<group>/<repo>` (a `-<stamp>` suffix
|
||||||
|
if taken) by `rename` (same file system only; otherwise it stays and `purge_failed` is logged),
|
||||||
|
then `git worktree repair` fixes the in-repo and linked worktrees (paths compared after
|
||||||
|
resolving symlinks). Worktrees whose directory is missing at that moment are listed in the
|
||||||
|
`purged` entry for a later `git worktree repair`. The directory is not a configured group, so
|
||||||
|
the daemon stops syncing it.
|
||||||
|
- Activity log: `purge_pending` (first confirmation), `purged` (moved, with the destination),
|
||||||
|
`purge_failed` (not moved, with the reason).
|
||||||
|
- `purged_dir` must be a plain directory name and must not also be a group.
|
||||||
|
- The confirmation state is in memory: a daemon restart restarts the 10-minute wait.
|
||||||
|
|
||||||
### Snapshot policy
|
### Snapshot policy
|
||||||
|
|
||||||
WIP snapshots (`refs/sync/<machine>/<branch>`) contain uncommitted work, so on a public repo anyone
|
WIP snapshots (`refs/sync/<machine>/<branch>`) contain uncommitted work, so on a public repo anyone
|
||||||
|
|||||||
Reference in new issue
Block a user