mirror of
https://github.com/Dasemu/Grove.git
synced 2026-11-27 07:46:13 +00:00
Compare commits
26
Commits
e6030f780d
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8c902e85b7 | ||
|
|
80ff449f74 | ||
|
|
7ed5675a00 | ||
|
|
933ad65cf0 | ||
|
|
51450ffa5e | ||
|
|
380fff5395 | ||
|
|
d73f0c9463 | ||
|
|
0f83e9d30b | ||
|
|
f16438fa02 | ||
|
|
6e5bee1a95 | ||
|
|
a1646bccb7 | ||
|
|
c7899bcdc0 | ||
|
|
2772635ff9 | ||
|
|
425980e27f | ||
|
|
206130df98 | ||
|
|
e9ac627863 | ||
|
|
d281c91c30 | ||
|
|
8cb87d9a37 | ||
|
|
ca8a2986dc | ||
|
|
a5c7cc307b | ||
|
|
d1d1fa29f3 | ||
|
|
9340a436d5 | ||
|
|
4c355b28ef | ||
|
|
d414862dec | ||
|
|
5f33bb9327 | ||
|
|
41e7c785af |
No files matched your search
@@ -4,7 +4,8 @@
|
|||||||
Linux tool that keeps chosen git repos continuously in sync across machines, including
|
Linux tool that keeps chosen git repos continuously in sync across machines, including
|
||||||
uncommitted work, via snapshot refs (`refs/sync/<machine>/<branch>`) on a primary remote.
|
uncommitted work, via snapshot refs (`refs/sync/<machine>/<branch>`) on a primary remote.
|
||||||
Rust workspace: `grove-core`, `grove` (CLI), `grove-daemon` (`groved`), `grove-providers` (Gitea/Forgejo/GitHub),
|
Rust workspace: `grove-core`, `grove` (CLI), `grove-daemon` (`groved`), `grove-providers` (Gitea/Forgejo/GitHub),
|
||||||
`grove-gui` (native Slint desktop app with a ksni tray, `docs/phase7.md`). Phases 0-7 are implemented; the real two-PC run is still pending.
|
`grove-gui` (native Slint desktop app with a ksni tray, `docs/phase7.md`). Phases 0-7 are implemented; the real two-PC run passed (`docs/two-pc-run.md`).
|
||||||
|
Worktrees merged through a PR on the forge are pruned by the daemon (`docs/prune-merged.md`).
|
||||||
Do not start new work before the previous results are written to `docs/`.
|
Do not start new work before the previous results are written to `docs/`.
|
||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
@@ -17,7 +18,7 @@ Do not start new work before the previous results are written to `docs/`.
|
|||||||
- Throwaway e2e on a local Forgejo: `spikes/phase4-e2e.sh`
|
- Throwaway e2e on a local Forgejo: `spikes/phase4-e2e.sh`
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
See `docs/` (`phase0-spike.md` ... `phase7.md`, `DECISIONS.md`). Git is the storage layer; shell out to
|
See `docs/` (`phase0-spike.md` ... `phase7.md`, `two-pc-run.md`, `prune-merged.md`, `DECISIONS.md`). Git is the storage layer; shell out to
|
||||||
system `git`; snapshots use a temp `GIT_INDEX_FILE` + `commit-tree`, never touching the
|
system `git`; snapshots use a temp `GIT_INDEX_FILE` + `commit-tree`, never touching the
|
||||||
user's branch or index.
|
user's branch or index.
|
||||||
|
|
||||||
@@ -28,8 +29,8 @@ user's branch or index.
|
|||||||
- The daemon manages only bare-layout repos at `root/<group>/<repo>` and pushes WIP snapshots only to private repos by default (`sync.snapshots`, per-group override); see `docs/phase6.md`.
|
- The daemon manages only bare-layout repos at `root/<group>/<repo>` and pushes WIP snapshots only to private repos by default (`sync.snapshots`, per-group override); see `docs/phase6.md`.
|
||||||
|
|
||||||
## Workflow quirks
|
## Workflow quirks
|
||||||
- Remote: Gitea `git.zenvairo.es`, owner `dasemu` (section `Darío`), CLI `tea`. SSH (port 22)
|
- Remote: public GitHub `Dasemu/Grove` over SSH, CLI `gh`; PRs target `development` there.
|
||||||
is unreachable from the dev machine; use HTTPS with `git -c credential.helper='!tea login helper'`.
|
`git.zenvairo.es/dasemu/Grove` is a read-only pull mirror of it (never push to it).
|
||||||
- In zsh, aliases like `g`/`gg` shadow shell functions; use unusual function names in scripts.
|
- In zsh, aliases like `g`/`gg` shadow shell functions; use unusual function names in scripts.
|
||||||
- Throwaway repos created on the real Gitea for tests must be deleted afterwards.
|
- Throwaway repos created on the real Gitea for tests must be deleted afterwards.
|
||||||
|
|
||||||
|
|||||||
@@ -155,6 +155,35 @@ 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,
|
||||||
|
/// Remove worktrees whose branch was merged through a pull request on the forge (when they
|
||||||
|
/// hold no local work).
|
||||||
|
#[serde(default = "yes")]
|
||||||
|
pub prune_merged: bool,
|
||||||
|
/// Ignored files/directories (matched by name) that may be deleted with a pruned worktree:
|
||||||
|
/// regenerable build output and dependency caches. Any other ignored file keeps it.
|
||||||
|
#[serde(default = "default_disposable")]
|
||||||
|
pub prune_disposable: Vec<String>,
|
||||||
|
/// Extra branches never pruned, on top of the built-in long-lived ones
|
||||||
|
/// (`prune::default_protected`) and the default branch. See [`Sync::protected_branches`].
|
||||||
|
#[serde(default)]
|
||||||
|
pub prune_protected: Vec<String>,
|
||||||
|
/// How many repos the daemon syncs at the same time (1 to 32). A repo never has two
|
||||||
|
/// passes at once.
|
||||||
|
#[serde(default = "default_workers")]
|
||||||
|
pub workers: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Sync {
|
||||||
|
/// Branches never pruned: the built-in long-lived ones plus `prune_protected`.
|
||||||
|
pub fn protected_branches(&self) -> Vec<String> {
|
||||||
|
let mut all = crate::prune::default_protected();
|
||||||
|
all.extend(self.prune_protected.iter().cloned());
|
||||||
|
all
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for Sync {
|
impl Default for Sync {
|
||||||
@@ -165,6 +194,11 @@ 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(),
|
||||||
|
prune_merged: true,
|
||||||
|
prune_disposable: default_disposable(),
|
||||||
|
prune_protected: Vec::new(),
|
||||||
|
workers: default_workers(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -178,12 +212,45 @@ pub struct ConfigRepo {
|
|||||||
fn yes() -> bool {
|
fn yes() -> bool {
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
fn default_workers() -> usize {
|
||||||
|
4
|
||||||
|
}
|
||||||
fn default_debounce() -> u64 {
|
fn default_debounce() -> u64 {
|
||||||
2000
|
2000
|
||||||
}
|
}
|
||||||
fn default_max_file_mb() -> u64 {
|
fn default_max_file_mb() -> u64 {
|
||||||
50
|
50
|
||||||
}
|
}
|
||||||
|
fn default_purged_dir() -> String {
|
||||||
|
"Purged".into()
|
||||||
|
}
|
||||||
|
fn default_disposable() -> Vec<String> {
|
||||||
|
[
|
||||||
|
"target",
|
||||||
|
"node_modules",
|
||||||
|
".venv",
|
||||||
|
"venv",
|
||||||
|
"__pycache__",
|
||||||
|
".pytest_cache",
|
||||||
|
".mypy_cache",
|
||||||
|
".ruff_cache",
|
||||||
|
".tox",
|
||||||
|
".gradle",
|
||||||
|
".next",
|
||||||
|
".nuxt",
|
||||||
|
".svelte-kit",
|
||||||
|
".turbo",
|
||||||
|
".parcel-cache",
|
||||||
|
"dist",
|
||||||
|
"build",
|
||||||
|
"out",
|
||||||
|
"coverage",
|
||||||
|
".cache",
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.map(String::from)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
fn default_fetch() -> u64 {
|
fn default_fetch() -> u64 {
|
||||||
60
|
60
|
||||||
}
|
}
|
||||||
@@ -275,6 +342,35 @@ 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"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !(1..=32).contains(&self.sync.workers) {
|
||||||
|
return bad(format!(
|
||||||
|
"sync.workers = {} must be between 1 and 32",
|
||||||
|
self.sync.workers
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if let Some(d) = self
|
||||||
|
.sync
|
||||||
|
.prune_disposable
|
||||||
|
.iter()
|
||||||
|
.find(|d| d.is_empty() || *d == "." || *d == ".." || d.contains(['/', '\\']))
|
||||||
|
{
|
||||||
|
return bad(format!(
|
||||||
|
"sync.prune_disposable entry {d:?} must be a plain file or directory name"
|
||||||
|
));
|
||||||
|
}
|
||||||
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 +479,49 @@ name = "grove-config"
|
|||||||
assert_eq!(c.root_path(), PathBuf::from("/x"));
|
assert_eq!(c.root_path(), PathBuf::from("/x"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn prune_merged_defaults_on_and_disposable_names_are_plain() {
|
||||||
|
let base = "[machine]\nname=\"m\"\n[root]\npath=\"/x\"\n";
|
||||||
|
let c = Config::parse(base).unwrap();
|
||||||
|
assert!(c.sync.prune_merged);
|
||||||
|
assert!(c.sync.prune_disposable.iter().any(|d| d == "target"));
|
||||||
|
assert!(
|
||||||
|
c.sync
|
||||||
|
.protected_branches()
|
||||||
|
.iter()
|
||||||
|
.any(|b| b == "development")
|
||||||
|
);
|
||||||
|
let own = format!("{base}[sync]\nprune_merged=false\nprune_disposable=[\"out\"]\n");
|
||||||
|
let c = Config::parse(&own).unwrap();
|
||||||
|
assert!(!c.sync.prune_merged);
|
||||||
|
assert_eq!(c.sync.prune_disposable, vec!["out".to_string()]);
|
||||||
|
let t = format!("{base}[sync]\nprune_protected=[\"release\"]\n");
|
||||||
|
let p = Config::parse(&t).unwrap().sync.protected_branches();
|
||||||
|
assert!(p.iter().any(|b| b == "release") && p.iter().any(|b| b == "main"));
|
||||||
|
for bad in ["\"\"", "\"a/b\"", "\"..\""] {
|
||||||
|
let t = format!("{base}[sync]\nprune_disposable=[{bad}]\n");
|
||||||
|
assert!(Config::parse(&t).is_err(), "{bad}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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"] {
|
||||||
|
|||||||
@@ -4,7 +4,74 @@ use std::ffi::OsStr;
|
|||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::io;
|
use std::io;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::process::Command;
|
use std::process::{Command, Output, Stdio};
|
||||||
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
/// Wall-clock limit for one git invocation in seconds; 0 (the default) means none.
|
||||||
|
static TIMEOUT_SECS: AtomicU64 = AtomicU64::new(0);
|
||||||
|
|
||||||
|
/// Sets a wall-clock limit for every git invocation of this process (0 disables it). Meant for
|
||||||
|
/// the daemon, whose single sync loop must never block forever on a stuck fetch, hook or helper.
|
||||||
|
pub fn set_timeout(secs: u64) {
|
||||||
|
TIMEOUT_SECS.store(secs, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs `cmd`, killing it (and its process group: ssh, helpers) when it outlives the limit.
|
||||||
|
fn output(cmd: Command, args: &[String]) -> Result<Output, GitError> {
|
||||||
|
output_within(cmd, args, TIMEOUT_SECS.load(Ordering::Relaxed))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn output_within(mut cmd: Command, args: &[String], secs: u64) -> Result<Output, GitError> {
|
||||||
|
if secs == 0 {
|
||||||
|
return Ok(cmd.output()?);
|
||||||
|
}
|
||||||
|
use std::io::Read;
|
||||||
|
use std::os::unix::process::CommandExt;
|
||||||
|
cmd.stdin(Stdio::null())
|
||||||
|
.stdout(Stdio::piped())
|
||||||
|
.stderr(Stdio::piped())
|
||||||
|
.process_group(0);
|
||||||
|
let mut child = cmd.spawn()?;
|
||||||
|
let reader = |mut r: Box<dyn Read + Send>| {
|
||||||
|
let (tx, rx) = std::sync::mpsc::channel();
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
let _ = r.read_to_end(&mut buf);
|
||||||
|
let _ = tx.send(buf);
|
||||||
|
});
|
||||||
|
rx
|
||||||
|
};
|
||||||
|
let out_rx = reader(Box::new(child.stdout.take().expect("piped")));
|
||||||
|
let err_rx = reader(Box::new(child.stderr.take().expect("piped")));
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(secs);
|
||||||
|
let mut nap = Duration::from_millis(1);
|
||||||
|
let status = loop {
|
||||||
|
if let Some(st) = child.try_wait()? {
|
||||||
|
break st;
|
||||||
|
}
|
||||||
|
if Instant::now() >= deadline {
|
||||||
|
let _ = Command::new("kill")
|
||||||
|
.args(["-KILL", "--", &format!("-{}", child.id())])
|
||||||
|
.status();
|
||||||
|
let _ = child.kill();
|
||||||
|
let _ = child.wait();
|
||||||
|
return Err(GitError::Other(format!(
|
||||||
|
"git {} timed out after {secs} s and was killed",
|
||||||
|
args.join(" ")
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
std::thread::sleep(nap);
|
||||||
|
nap = (nap * 2).min(Duration::from_millis(100));
|
||||||
|
};
|
||||||
|
// A lingering ssh master (ControlPersist) may keep the pipes open after git exits.
|
||||||
|
let grace = Duration::from_secs(2);
|
||||||
|
Ok(Output {
|
||||||
|
status,
|
||||||
|
stdout: out_rx.recv_timeout(grace).unwrap_or_default(),
|
||||||
|
stderr: err_rx.recv_timeout(grace).unwrap_or_default(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum GitError {
|
pub enum GitError {
|
||||||
@@ -37,6 +104,10 @@ impl From<io::Error> for GitError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn owned(args: &[&str]) -> Vec<String> {
|
||||||
|
args.iter().map(|s| s.to_string()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
/// A git invocation context: a working directory plus extra environment.
|
/// A git invocation context: a working directory plus extra environment.
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct Git {
|
pub struct Git {
|
||||||
@@ -73,7 +144,7 @@ impl Git {
|
|||||||
|
|
||||||
/// Run git, returning trimmed stdout. Any non-zero exit is an error.
|
/// Run git, returning trimmed stdout. Any non-zero exit is an error.
|
||||||
pub fn run(&self, args: &[&str]) -> Result<String, GitError> {
|
pub fn run(&self, args: &[&str]) -> Result<String, GitError> {
|
||||||
let out = self.command(args).output()?;
|
let out = output(self.command(args), &owned(args))?;
|
||||||
if out.status.success() {
|
if out.status.success() {
|
||||||
Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
|
Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
|
||||||
} else {
|
} else {
|
||||||
@@ -87,7 +158,7 @@ impl Git {
|
|||||||
|
|
||||||
/// Run git; a non-zero exit yields `None` (for probes like `rev-parse --verify`).
|
/// Run git; a non-zero exit yields `None` (for probes like `rev-parse --verify`).
|
||||||
pub fn probe(&self, args: &[&str]) -> Result<Option<String>, GitError> {
|
pub fn probe(&self, args: &[&str]) -> Result<Option<String>, GitError> {
|
||||||
let out = self.command(args).output()?;
|
let out = output(self.command(args), &owned(args))?;
|
||||||
if out.status.success() {
|
if out.status.success() {
|
||||||
Ok(Some(
|
Ok(Some(
|
||||||
String::from_utf8_lossy(&out.stdout).trim().to_string(),
|
String::from_utf8_lossy(&out.stdout).trim().to_string(),
|
||||||
@@ -97,3 +168,58 @@ impl Git {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Environment that keeps unattended git from ever waiting on a person: no terminal or askpass
|
||||||
|
/// prompts (a desktop `SSH_ASKPASS` such as ksshaskpass would otherwise open a dialog and block
|
||||||
|
/// forever), and stalled HTTP transfers abort. The ssh command is left alone so a user's (or a
|
||||||
|
/// repo's) `core.sshCommand` keeps working; wall-clock limits come from [`set_timeout`].
|
||||||
|
pub fn noninteractive_env() -> Vec<(String, String)> {
|
||||||
|
[
|
||||||
|
("GIT_TERMINAL_PROMPT", "0"),
|
||||||
|
("GIT_ASKPASS", "true"),
|
||||||
|
("SSH_ASKPASS_REQUIRE", "never"),
|
||||||
|
("GIT_HTTP_LOW_SPEED_LIMIT", "1000"),
|
||||||
|
("GIT_HTTP_LOW_SPEED_TIME", "60"),
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.map(|(k, v)| (k.to_string(), v.to_string()))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the user configured their own ssh command for git (env or `core.sshCommand`).
|
||||||
|
pub fn has_custom_ssh() -> bool {
|
||||||
|
std::env::var_os("GIT_SSH_COMMAND").is_some()
|
||||||
|
|| std::env::var_os("GIT_SSH").is_some()
|
||||||
|
|| std::process::Command::new("git")
|
||||||
|
.args(["config", "--get", "core.sshCommand"])
|
||||||
|
.output()
|
||||||
|
.is_ok_and(|o| o.status.success() && !o.stdout.is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod env_tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unattended_git_never_prompts_and_leaves_the_ssh_command_alone() {
|
||||||
|
let env = noninteractive_env();
|
||||||
|
let get = |k: &str| env.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str());
|
||||||
|
assert_eq!(get("GIT_TERMINAL_PROMPT"), Some("0"));
|
||||||
|
assert_eq!(get("SSH_ASKPASS_REQUIRE"), Some("never"));
|
||||||
|
assert_eq!(get("GIT_SSH_COMMAND"), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_git_call_over_the_limit_is_killed() {
|
||||||
|
// A hook-like stall: `git -c alias.x='!sleep 30' x`. The global limit is not touched, so
|
||||||
|
// tests running in parallel are unaffected.
|
||||||
|
let args = owned(&["-c", "alias.zzsleep=!sleep 30", "zzsleep"]);
|
||||||
|
let t = Instant::now();
|
||||||
|
let r = output_within(Git::new(".").command(&args), &args, 1);
|
||||||
|
assert!(r.unwrap_err().to_string().contains("timed out"));
|
||||||
|
assert!(t.elapsed() < Duration::from_secs(10));
|
||||||
|
let v = owned(&["--version"]);
|
||||||
|
let out = output_within(Git::new(".").command(&v), &v, 5).unwrap();
|
||||||
|
assert!(String::from_utf8_lossy(&out.stdout).starts_with("git version"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@ pub mod git;
|
|||||||
pub mod inspect;
|
pub mod inspect;
|
||||||
pub mod layout;
|
pub mod layout;
|
||||||
pub mod migrate;
|
pub mod migrate;
|
||||||
|
pub mod prune;
|
||||||
pub mod receive;
|
pub mod receive;
|
||||||
pub mod registry;
|
pub mod registry;
|
||||||
pub mod resolve;
|
pub mod resolve;
|
||||||
|
|||||||
@@ -0,0 +1,273 @@
|
|||||||
|
//! Removing worktrees whose work is already merged.
|
||||||
|
//!
|
||||||
|
//! A branch counts as merged when either
|
||||||
|
//! - it is the head of a pull request merged on the forge and its tip is that head (or an
|
||||||
|
//! ancestor of it): squash and rebase merges leave no ancestry, so the forge has to say so; or
|
||||||
|
//! - it was merged without a pull request: its tip was pushed (`<remote>/<branch>` points at it),
|
||||||
|
//! is a strict ancestor of `<remote>/<default>` and is not on its first-parent history (a
|
||||||
|
//! merge commit brought it in). A branch created from the default branch with no commits of
|
||||||
|
//! its own is on that history, so it never counts; neither does a fast-forward merge.
|
||||||
|
//!
|
||||||
|
//! Branches named in `sync.prune_protected` (long-lived ones such as `development`) and the
|
||||||
|
//! default branch are never pruned. A worktree is removed only when it holds no local work: no
|
||||||
|
//! uncommitted or untracked files, no ignored files other than regenerable ones
|
||||||
|
//! (`sync.prune_disposable`), no git operation in progress. The tip is kept under a backup ref
|
||||||
|
//! before anything is removed.
|
||||||
|
|
||||||
|
use crate::git::{Git, GitError};
|
||||||
|
use crate::inspect::worktrees;
|
||||||
|
use crate::receive::backup_ref;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
/// The head of a pull request merged on the forge.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct MergedHead {
|
||||||
|
pub number: u64,
|
||||||
|
/// Branch name of the pull request's head (in the same repo; fork PRs are left out).
|
||||||
|
pub branch: String,
|
||||||
|
/// Commit the pull request's head pointed at when it was merged.
|
||||||
|
pub sha: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum Pruned {
|
||||||
|
/// Worktree removed and local branch deleted; the tip is kept under `backup_ref`.
|
||||||
|
Removed {
|
||||||
|
branch: String,
|
||||||
|
/// The merged pull request; `None` when merged into the default branch without one.
|
||||||
|
pr: Option<u64>,
|
||||||
|
path: PathBuf,
|
||||||
|
backup_ref: String,
|
||||||
|
},
|
||||||
|
/// Merged, but the worktree holds something that is not on the forge: kept.
|
||||||
|
Kept {
|
||||||
|
branch: String,
|
||||||
|
pr: Option<u64>,
|
||||||
|
why: String,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How a pruned branch was merged, for messages ("merged in PR #3").
|
||||||
|
pub fn merged_how(pr: Option<u64>) -> String {
|
||||||
|
match pr {
|
||||||
|
Some(n) => format!("merged in PR #{n}"),
|
||||||
|
None => "merged into the default branch".into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Long-lived branches that are never pruned; `sync.prune_protected` adds to them.
|
||||||
|
pub fn default_protected() -> Vec<String> {
|
||||||
|
[
|
||||||
|
"main",
|
||||||
|
"master",
|
||||||
|
"development",
|
||||||
|
"develop",
|
||||||
|
"dev",
|
||||||
|
"staging",
|
||||||
|
"production",
|
||||||
|
]
|
||||||
|
.map(String::from)
|
||||||
|
.to_vec()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Backup-ref kind of a pruned branch (`refs/sync-backup/<machine>/<stamp>/merged/<branch>`).
|
||||||
|
const KIND: &str = "merged";
|
||||||
|
|
||||||
|
/// An operation in progress in `worktree` that removing it would break.
|
||||||
|
pub fn operation_in_progress(worktree: &Path) -> Option<&'static str> {
|
||||||
|
let gd = Git::new(worktree)
|
||||||
|
.run(&["rev-parse", "--absolute-git-dir"])
|
||||||
|
.ok()?;
|
||||||
|
let gd = PathBuf::from(gd);
|
||||||
|
[
|
||||||
|
"index.lock",
|
||||||
|
"rebase-merge",
|
||||||
|
"rebase-apply",
|
||||||
|
"MERGE_HEAD",
|
||||||
|
"CHERRY_PICK_HEAD",
|
||||||
|
"REVERT_HEAD",
|
||||||
|
"BISECT_LOG",
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.find(|f| gd.join(f).exists())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why `worktree` holds local work, if it does. Ignored entries whose last path component is
|
||||||
|
/// in `disposable` (build output, dependency caches) do not count.
|
||||||
|
fn local_work(worktree: &Path, disposable: &[String]) -> Result<Option<String>, GitError> {
|
||||||
|
if let Some(op) = operation_in_progress(worktree) {
|
||||||
|
return Ok(Some(format!("git operation in progress ({op})")));
|
||||||
|
}
|
||||||
|
let st = Git::new(worktree).run(&["status", "--porcelain", "--ignored", "-z"])?;
|
||||||
|
let mut kept = Vec::new();
|
||||||
|
for entry in st.split('\0').filter(|e| e.len() > 3) {
|
||||||
|
let (code, path) = entry.split_at(3);
|
||||||
|
if code != "!! " {
|
||||||
|
return Ok(Some("uncommitted or untracked changes".into()));
|
||||||
|
}
|
||||||
|
let last = path
|
||||||
|
.trim_end_matches('/')
|
||||||
|
.rsplit('/')
|
||||||
|
.next()
|
||||||
|
.unwrap_or(path);
|
||||||
|
if !disposable.iter().any(|d| d == last) {
|
||||||
|
kept.push(path.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if kept.is_empty() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
kept.truncate(5);
|
||||||
|
Ok(Some(format!("ignored files: {}", kept.join(", "))))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_ancestor(g: &Git, a: &str, b: &str) -> bool {
|
||||||
|
matches!(g.probe(&["merge-base", "--is-ancestor", a, b]), Ok(Some(_)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resolve(g: &Git, r: &str) -> Option<String> {
|
||||||
|
g.probe(&["rev-parse", "-q", "--verify", &format!("{r}^{{commit}}")])
|
||||||
|
.ok()
|
||||||
|
.flatten()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Merged without a pull request: `tip` was pushed as `<remote>/<branch>`, is a strict ancestor
|
||||||
|
/// of `<remote>/<default>` and is not on its first-parent history (a merge commit brought it).
|
||||||
|
fn merged_by_ancestry(g: &Git, remote: &str, default: &str, branch: &str, tip: &str) -> bool {
|
||||||
|
let Some(base) = resolve(g, &format!("refs/remotes/{remote}/{default}")) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
resolve(g, &format!("refs/remotes/{remote}/{branch}")).as_deref() == Some(tip)
|
||||||
|
&& base != tip
|
||||||
|
&& is_ancestor(g, tip, &base)
|
||||||
|
&& !on_first_parent_chain(g, tip, &base)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True when `tip` is on the first-parent history of `base`: the default branch passed through
|
||||||
|
/// it. That is a branch created from the default branch with no commits of its own (or merged
|
||||||
|
/// by fast-forward, which the PR path still covers), so ancestry says nothing about a merge.
|
||||||
|
fn on_first_parent_chain(g: &Git, tip: &str, base: &str) -> bool {
|
||||||
|
// On error, assume it is (never prune on doubt).
|
||||||
|
g.run(&["rev-list", "--first-parent", base])
|
||||||
|
.map_or(true, |l| l.lines().any(|c| c == tip))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What to prune and what to keep.
|
||||||
|
pub struct Rules<'a> {
|
||||||
|
/// Remote whose default branch and branches the ancestry rule compares against.
|
||||||
|
pub remote: &'a str,
|
||||||
|
/// Heads of pull requests merged on the forge (may be empty: unknown).
|
||||||
|
pub merged: &'a [MergedHead],
|
||||||
|
/// Ignored file/directory names that do not count as local work.
|
||||||
|
pub disposable: &'a [String],
|
||||||
|
/// Branch names never pruned.
|
||||||
|
pub protected: &'a [String],
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes the worktrees of the bare-layout repo at `root` whose branch is already merged (see
|
||||||
|
/// the module docs). Only worktrees inside `root` are touched, never the one of the default
|
||||||
|
/// branch (`.bare`'s HEAD) nor protected branches.
|
||||||
|
pub fn prune_merged(
|
||||||
|
root: &Path,
|
||||||
|
rules: &Rules,
|
||||||
|
machine: &str,
|
||||||
|
stamp: &str,
|
||||||
|
) -> Result<Vec<Pruned>, GitError> {
|
||||||
|
let bare = root.join(".bare");
|
||||||
|
let g = Git::new(&bare);
|
||||||
|
let default = g.probe(&["symbolic-ref", "--short", "-q", "HEAD"])?;
|
||||||
|
let canonical_root = root.canonicalize()?;
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for wt in worktrees(&bare)? {
|
||||||
|
let Some(branch) = wt.branch.as_deref() else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if default.as_deref() == Some(branch)
|
||||||
|
|| rules.protected.iter().any(|p| p == branch)
|
||||||
|
|| !wt.path.starts_with(&canonical_root)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Ok(tip) = g.run(&["rev-parse", &format!("refs/heads/{branch}")]) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
// The newest merged PR of this branch whose head contains the local tip, else a merge
|
||||||
|
// without a PR.
|
||||||
|
let pr = rules
|
||||||
|
.merged
|
||||||
|
.iter()
|
||||||
|
.filter(|m| m.branch == branch)
|
||||||
|
.find(|m| m.sha == tip || is_ancestor(&g, &tip, &m.sha))
|
||||||
|
.map(|m| m.number);
|
||||||
|
if pr.is_none()
|
||||||
|
&& !default
|
||||||
|
.as_deref()
|
||||||
|
.is_some_and(|d| merged_by_ancestry(&g, rules.remote, d, branch, &tip))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if !wt.path.is_dir() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Some(why) = local_work(&wt.path, rules.disposable)? {
|
||||||
|
out.push(Pruned::Kept {
|
||||||
|
branch: branch.to_string(),
|
||||||
|
pr,
|
||||||
|
why,
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let bref = backup_ref(machine, stamp, &format!("{KIND}/{branch}"));
|
||||||
|
g.run(&["update-ref", &bref, &tip])?;
|
||||||
|
// `--force`: the only files left are disposable ignored ones (checked above).
|
||||||
|
g.run(&["worktree", "remove", "--force", &wt.path.to_string_lossy()])?;
|
||||||
|
g.run(&["branch", "-D", branch])?;
|
||||||
|
out.push(Pruned::Removed {
|
||||||
|
branch: branch.to_string(),
|
||||||
|
pr,
|
||||||
|
path: wt.path.clone(),
|
||||||
|
backup_ref: bref,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Branches `materialize` must not bring back: the remote tip is the head of a merged PR, or
|
||||||
|
/// the tip this machine pruned (its `merged/<branch>` backup ref). New commits pushed to the
|
||||||
|
/// branch after the merge make it materialize again. Protected branches are never settled.
|
||||||
|
pub fn settled_branches(
|
||||||
|
bare: &Path,
|
||||||
|
remote: &str,
|
||||||
|
merged: &[MergedHead],
|
||||||
|
protected: &[String],
|
||||||
|
machine: &str,
|
||||||
|
) -> Result<Vec<String>, GitError> {
|
||||||
|
let g = Git::new(bare);
|
||||||
|
let backups = g.run(&[
|
||||||
|
"for-each-ref",
|
||||||
|
"--format=%(objectname) %(refname)",
|
||||||
|
&format!("refs/sync-backup/{machine}/"),
|
||||||
|
])?;
|
||||||
|
let pruned: Vec<(&str, &str)> = backups
|
||||||
|
.lines()
|
||||||
|
.filter_map(|l| l.split_once(' '))
|
||||||
|
.filter_map(|(sha, r)| {
|
||||||
|
let rest = r.strip_prefix(&format!("refs/sync-backup/{machine}/"))?;
|
||||||
|
let (_, kind) = rest.split_once('/')?;
|
||||||
|
Some((sha, kind.strip_prefix(&format!("{KIND}/"))?))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let prefix = format!("refs/remotes/{remote}/");
|
||||||
|
let tips = g.run(&["for-each-ref", "--format=%(objectname) %(refname)", &prefix])?;
|
||||||
|
Ok(tips
|
||||||
|
.lines()
|
||||||
|
.filter_map(|l| l.split_once(' '))
|
||||||
|
.filter_map(|(sha, r)| Some((sha, r.strip_prefix(&prefix)?)))
|
||||||
|
.filter(|(_, b)| !protected.iter().any(|p| p == b))
|
||||||
|
.filter(|(sha, b)| {
|
||||||
|
merged.iter().any(|m| m.branch == *b && m.sha == *sha)
|
||||||
|
|| pruned.iter().any(|(s, pb)| pb == b && s == sha)
|
||||||
|
})
|
||||||
|
.map(|(_, b)| b.to_string())
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
@@ -45,6 +45,7 @@ pub(crate) fn ignored_conflicts(g: &Git, target: &str) -> Result<Vec<String>, Gi
|
|||||||
"-z",
|
"-z",
|
||||||
])?;
|
])?;
|
||||||
let ignored: Vec<&str> = ignored.split('\0').filter(|p| !p.is_empty()).collect();
|
let ignored: Vec<&str> = ignored.split('\0').filter(|p| !p.is_empty()).collect();
|
||||||
|
let top = std::path::PathBuf::from(g.run(&["rev-parse", "--show-toplevel"])?);
|
||||||
Ok(added
|
Ok(added
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter(|a| {
|
.filter(|a| {
|
||||||
@@ -52,10 +53,26 @@ pub(crate) fn ignored_conflicts(g: &Git, target: &str) -> Result<Vec<String>, Gi
|
|||||||
.iter()
|
.iter()
|
||||||
.any(|i| a == i || (i.ends_with('/') && a.starts_with(i)))
|
.any(|i| a == i || (i.ends_with('/') && a.starts_with(i)))
|
||||||
})
|
})
|
||||||
|
// An ignored directory (`.claude/`) only covers the path: there is something to
|
||||||
|
// overwrite only if the file, or a file where one of its parent directories goes, exists.
|
||||||
|
.filter(|a| occupied(&top, a))
|
||||||
.map(String::from)
|
.map(String::from)
|
||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// True when writing `rel` under `top` would replace something on disk: the path itself
|
||||||
|
/// exists, or one of its parents exists as something other than a directory.
|
||||||
|
fn occupied(top: &Path, rel: &str) -> bool {
|
||||||
|
let path = top.join(rel);
|
||||||
|
if path.symlink_metadata().is_ok() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
path.ancestors()
|
||||||
|
.skip(1)
|
||||||
|
.take_while(|p| p.starts_with(top) && *p != top)
|
||||||
|
.any(|p| p.symlink_metadata().is_ok_and(|m| !m.is_dir()))
|
||||||
|
}
|
||||||
|
|
||||||
fn current_branch(g: &Git) -> Result<String, GitError> {
|
fn current_branch(g: &Git) -> Result<String, GitError> {
|
||||||
g.probe(&["symbolic-ref", "--short", "-q", "HEAD"])?
|
g.probe(&["symbolic-ref", "--short", "-q", "HEAD"])?
|
||||||
.ok_or_else(|| GitError::Other("detached HEAD".into()))
|
.ok_or_else(|| GitError::Other("detached HEAD".into()))
|
||||||
@@ -345,6 +362,15 @@ pub fn apply_snapshot(
|
|||||||
|
|
||||||
/// Create worktrees under `root` for remote branches that have none. Returns new paths.
|
/// Create worktrees under `root` for remote branches that have none. Returns new paths.
|
||||||
pub fn materialize(root: &Path, remote: &str) -> Result<Vec<PathBuf>, GitError> {
|
pub fn materialize(root: &Path, remote: &str) -> Result<Vec<PathBuf>, GitError> {
|
||||||
|
materialize_except(root, remote, &[])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Like [`materialize`], leaving out the branches in `skip` (e.g. merged ones that were pruned).
|
||||||
|
pub fn materialize_except(
|
||||||
|
root: &Path,
|
||||||
|
remote: &str,
|
||||||
|
skip: &[String],
|
||||||
|
) -> Result<Vec<PathBuf>, GitError> {
|
||||||
let bare = root.join(".bare");
|
let bare = root.join(".bare");
|
||||||
let g = Git::new(&bare);
|
let g = Git::new(&bare);
|
||||||
let prefix = format!("refs/remotes/{remote}/");
|
let prefix = format!("refs/remotes/{remote}/");
|
||||||
@@ -362,7 +388,10 @@ pub fn materialize(root: &Path, remote: &str) -> Result<Vec<PathBuf>, GitError>
|
|||||||
let Some(branch) = r.strip_prefix(&prefix) else {
|
let Some(branch) = r.strip_prefix(&prefix) else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
if branch == "HEAD" || existing_branches.iter().any(|b| b == branch) {
|
if branch == "HEAD"
|
||||||
|
|| existing_branches.iter().any(|b| b == branch)
|
||||||
|
|| skip.iter().any(|b| b == branch)
|
||||||
|
{
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let refs: Vec<&str> = taken.iter().map(String::as_str).collect();
|
let refs: Vec<&str> = taken.iter().map(String::as_str).collect();
|
||||||
|
|||||||
@@ -47,7 +47,10 @@ fn temp_index_path() -> PathBuf {
|
|||||||
.duration_since(UNIX_EPOCH)
|
.duration_since(UNIX_EPOCH)
|
||||||
.map(|d| d.as_nanos())
|
.map(|d| d.as_nanos())
|
||||||
.unwrap_or(0);
|
.unwrap_or(0);
|
||||||
std::env::temp_dir().join(format!("grove-index-{}-{nanos}", std::process::id()))
|
// A counter too: daemon workers snapshot several repos at once.
|
||||||
|
static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||||
|
let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||||
|
std::env::temp_dir().join(format!("grove-index-{}-{nanos}-{n}", std::process::id()))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tree of everything in the worktree (tracked changes and untracked files, not ignored ones),
|
/// Tree of everything in the worktree (tracked changes and untracked files, not ignored ones),
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
//! One full sync pass over a repo: snapshot, push, fetch, receive, apply, materialize, archive.
|
//! One full sync pass over a repo: snapshot, push, fetch, receive, apply, materialize, archive,
|
||||||
|
//! prune merged.
|
||||||
//! Failures of individual steps are reported per worktree and never abort the whole pass.
|
//! Failures of individual steps are reported per worktree and never abort the whole pass.
|
||||||
|
|
||||||
use crate::git::{Git, GitError};
|
use crate::git::{Git, GitError};
|
||||||
use crate::inspect::{facts, state, worktrees};
|
use crate::inspect::{facts, state, worktrees};
|
||||||
|
use crate::prune::{MergedHead, Pruned, Rules, prune_merged, settled_branches};
|
||||||
use crate::receive::{
|
use crate::receive::{
|
||||||
Applied, Archived, Received, apply_snapshot, archive_gone, fetch, foreign_snapshots,
|
Applied, Archived, Received, apply_snapshot, archive_gone, fetch, foreign_snapshots,
|
||||||
materialize, push_snapshot, receive,
|
materialize_except, push_snapshot, receive,
|
||||||
};
|
};
|
||||||
use crate::snapshot::{Outcome, ref_name, take};
|
use crate::snapshot::{Outcome, ref_name, take};
|
||||||
use crate::state::State;
|
use crate::state::State;
|
||||||
@@ -24,6 +26,16 @@ pub struct Options {
|
|||||||
/// repo, or `snapshots = "none"`) no `refs/sync/<machine>/*` ref is created or pushed;
|
/// repo, or `snapshots = "none"`) no `refs/sync/<machine>/*` ref is created or pushed;
|
||||||
/// fetching, fast-forwarding and applying other machines' snapshots are unaffected.
|
/// fetching, fast-forwarding and applying other machines' snapshots are unaffected.
|
||||||
pub push_snapshots: bool,
|
pub push_snapshots: bool,
|
||||||
|
/// Heads of pull requests merged on the forge (empty: unknown or pruning disabled).
|
||||||
|
/// Worktrees of those branches without local work are removed (bare layout only), and
|
||||||
|
/// `materialize` does not bring them back.
|
||||||
|
pub merged: Vec<MergedHead>,
|
||||||
|
/// Names of ignored files/directories that do not count as local work when pruning.
|
||||||
|
pub disposable: Vec<String>,
|
||||||
|
/// Prune worktrees of merged branches (bare layout only, see `prune`).
|
||||||
|
pub prune: bool,
|
||||||
|
/// Branch names never pruned.
|
||||||
|
pub protected: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
@@ -44,6 +56,7 @@ pub struct SyncReport {
|
|||||||
pub fetch_error: Option<String>,
|
pub fetch_error: Option<String>,
|
||||||
pub materialized: Vec<PathBuf>,
|
pub materialized: Vec<PathBuf>,
|
||||||
pub archived: Vec<Archived>,
|
pub archived: Vec<Archived>,
|
||||||
|
pub pruned: Vec<Pruned>,
|
||||||
pub worktrees: Vec<WorktreeReport>,
|
pub worktrees: Vec<WorktreeReport>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,7 +85,22 @@ pub fn sync_repo(path: &Path, o: &Options) -> Result<SyncReport, GitError> {
|
|||||||
Ok(a) => rep.archived = a,
|
Ok(a) => rep.archived = a,
|
||||||
Err(e) => rep.fetch_error = Some(format!("archive: {e}")),
|
Err(e) => rep.fetch_error = Some(format!("archive: {e}")),
|
||||||
}
|
}
|
||||||
match materialize(path, &o.remote) {
|
}
|
||||||
|
if bare_layout && o.prune && rep.fetch_error.is_none() && !o.offline {
|
||||||
|
let rules = Rules {
|
||||||
|
remote: &o.remote,
|
||||||
|
merged: &o.merged,
|
||||||
|
disposable: &o.disposable,
|
||||||
|
protected: &o.protected,
|
||||||
|
};
|
||||||
|
match prune_merged(path, &rules, &o.machine, &o.stamp) {
|
||||||
|
Ok(p) => rep.pruned = p,
|
||||||
|
Err(e) => rep.fetch_error = Some(format!("prune merged: {e}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if bare_layout && o.materialize && rep.fetch_error.is_none() {
|
||||||
|
let skip = settled_branches(&gitdir, &o.remote, &o.merged, &o.protected, &o.machine);
|
||||||
|
match skip.and_then(|skip| materialize_except(path, &o.remote, &skip)) {
|
||||||
Ok(m) => rep.materialized = m,
|
Ok(m) => rep.materialized = m,
|
||||||
Err(e) => rep.fetch_error = Some(format!("materialize: {e}")),
|
Err(e) => rep.fetch_error = Some(format!("materialize: {e}")),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,298 @@
|
|||||||
|
mod common;
|
||||||
|
use common::*;
|
||||||
|
use grove_core::git::Git;
|
||||||
|
use grove_core::migrate::migrate;
|
||||||
|
use grove_core::prune::{MergedHead, Pruned, Rules, default_protected, prune_merged};
|
||||||
|
use grove_core::sync::{Options, sync_repo};
|
||||||
|
use std::fs;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
struct World {
|
||||||
|
_tmp: tmp::TempDir,
|
||||||
|
base: PathBuf,
|
||||||
|
/// Another machine's plain clone (plays the forge user who merges).
|
||||||
|
dev: Git,
|
||||||
|
/// This machine's bare-layout repo.
|
||||||
|
root: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn world() -> World {
|
||||||
|
let tmp = tmpdir("prune");
|
||||||
|
let base = tmp.to_path_buf();
|
||||||
|
let remote = base.join("remote.git");
|
||||||
|
Git::new(&base)
|
||||||
|
.run(&[
|
||||||
|
"init",
|
||||||
|
"-q",
|
||||||
|
"--bare",
|
||||||
|
"-b",
|
||||||
|
"main",
|
||||||
|
remote.to_str().unwrap(),
|
||||||
|
])
|
||||||
|
.unwrap();
|
||||||
|
let dev = init(&base.join("dev"));
|
||||||
|
dev.run(&["remote", "add", "origin", remote.to_str().unwrap()])
|
||||||
|
.unwrap();
|
||||||
|
commit(&dev, ".gitignore", "*.env\ntarget/\n");
|
||||||
|
dev.run(&["push", "-q", "-u", "origin", "main"]).unwrap();
|
||||||
|
let d = base.join("me");
|
||||||
|
Git::new(&base)
|
||||||
|
.run(&["clone", "-q", remote.to_str().unwrap(), d.to_str().unwrap()])
|
||||||
|
.unwrap();
|
||||||
|
migrate(&d, "me", &base.join("bk"), "1").unwrap();
|
||||||
|
World {
|
||||||
|
_tmp: tmp,
|
||||||
|
base,
|
||||||
|
dev,
|
||||||
|
root: d.canonicalize().unwrap(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn opts(stamp: &str, merged: Vec<MergedHead>) -> Options {
|
||||||
|
Options {
|
||||||
|
machine: "me".into(),
|
||||||
|
stamp: stamp.into(),
|
||||||
|
remote: "origin".into(),
|
||||||
|
offline: false,
|
||||||
|
materialize: true,
|
||||||
|
push_snapshots: false,
|
||||||
|
merged,
|
||||||
|
disposable: vec!["target".into()],
|
||||||
|
prune: true,
|
||||||
|
protected: default_protected(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pushes branch `b` with one commit from `dev` and returns its tip.
|
||||||
|
fn push_branch(w: &World, b: &str) -> String {
|
||||||
|
w.dev.run(&["checkout", "-q", "-b", b, "main"]).unwrap();
|
||||||
|
commit(&w.dev, &format!("{}.txt", b.replace('/', "-")), "x\n");
|
||||||
|
w.dev.run(&["push", "-q", "-u", "origin", b]).unwrap();
|
||||||
|
let tip = w.dev.run(&["rev-parse", "HEAD"]).unwrap();
|
||||||
|
w.dev.run(&["checkout", "-q", "main"]).unwrap();
|
||||||
|
tip
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A squash merge: the branch's content lands on main as a new commit (no ancestry), and the
|
||||||
|
/// head branch stays on the remote.
|
||||||
|
fn squash_merge(w: &World, b: &str) {
|
||||||
|
w.dev.run(&["merge", "-q", "--squash", b]).unwrap();
|
||||||
|
w.dev.run(&["commit", "-qm", "squash"]).unwrap();
|
||||||
|
w.dev.run(&["push", "-q", "origin", "main"]).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn head(n: u64, branch: &str, sha: &str) -> MergedHead {
|
||||||
|
MergedHead {
|
||||||
|
number: n,
|
||||||
|
branch: branch.into(),
|
||||||
|
sha: sha.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_branch(root: &Path, b: &str) -> bool {
|
||||||
|
Git::new(root.join(".bare"))
|
||||||
|
.probe(&["rev-parse", "-q", "--verify", &format!("refs/heads/{b}")])
|
||||||
|
.unwrap()
|
||||||
|
.is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_squash_merged_worktree_is_removed_and_not_brought_back() {
|
||||||
|
let w = world();
|
||||||
|
let tip = push_branch(&w, "feat/x");
|
||||||
|
sync_repo(&w.root, &opts("s1", vec![])).unwrap();
|
||||||
|
let wt = w.root.join("feat-x");
|
||||||
|
assert!(wt.exists());
|
||||||
|
// Build output is regenerable: it does not keep the worktree.
|
||||||
|
fs::create_dir_all(wt.join("target/debug")).unwrap();
|
||||||
|
fs::write(wt.join("target/debug/bin"), "b").unwrap();
|
||||||
|
squash_merge(&w, "feat/x");
|
||||||
|
|
||||||
|
let rep = sync_repo(&w.root, &opts("s2", vec![head(7, "feat/x", &tip)])).unwrap();
|
||||||
|
assert!(rep.fetch_error.is_none(), "{:?}", rep.fetch_error);
|
||||||
|
let [
|
||||||
|
Pruned::Removed {
|
||||||
|
branch,
|
||||||
|
pr,
|
||||||
|
backup_ref,
|
||||||
|
..
|
||||||
|
},
|
||||||
|
] = rep.pruned.as_slice()
|
||||||
|
else {
|
||||||
|
panic!("{:?}", rep.pruned);
|
||||||
|
};
|
||||||
|
assert_eq!((branch.as_str(), *pr), ("feat/x", Some(7)));
|
||||||
|
assert!(!wt.exists() && !has_branch(&w.root, "feat/x"));
|
||||||
|
let bare = Git::new(w.root.join(".bare"));
|
||||||
|
assert_eq!(bare.run(&["rev-parse", backup_ref]).unwrap(), tip);
|
||||||
|
assert!(rep.materialized.is_empty(), "{:?}", rep.materialized);
|
||||||
|
|
||||||
|
// The remote branch is still there; later passes (even without a forge answer) leave it.
|
||||||
|
let rep = sync_repo(&w.root, &opts("s3", vec![])).unwrap();
|
||||||
|
assert!(rep.materialized.is_empty() && !wt.exists());
|
||||||
|
|
||||||
|
// New commits on the branch after the merge are new work: it comes back.
|
||||||
|
w.dev.run(&["checkout", "-q", "feat/x"]).unwrap();
|
||||||
|
commit(&w.dev, "more.txt", "m\n");
|
||||||
|
w.dev.run(&["push", "-q", "origin", "feat/x"]).unwrap();
|
||||||
|
let rep = sync_repo(&w.root, &opts("s4", vec![head(7, "feat/x", &tip)])).unwrap();
|
||||||
|
assert_eq!(rep.materialized, vec![wt.clone()]);
|
||||||
|
assert!(rep.pruned.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn local_work_keeps_a_merged_worktree() {
|
||||||
|
let w = world();
|
||||||
|
let tip = push_branch(&w, "a");
|
||||||
|
let tip_b = push_branch(&w, "b");
|
||||||
|
let tip_c = push_branch(&w, "c");
|
||||||
|
sync_repo(&w.root, &opts("s1", vec![])).unwrap();
|
||||||
|
fs::write(w.root.join("a/new.txt"), "untracked\n").unwrap();
|
||||||
|
fs::write(w.root.join("b/secret.env"), "ignored, not regenerable\n").unwrap();
|
||||||
|
// A local commit the merged PR does not have.
|
||||||
|
let gc = Git::new(w.root.join("c"));
|
||||||
|
gc.run(&["config", "user.email", "t@t"]).unwrap();
|
||||||
|
gc.run(&["config", "user.name", "t"]).unwrap();
|
||||||
|
commit(&gc, "local.txt", "l\n");
|
||||||
|
|
||||||
|
let merged = vec![
|
||||||
|
head(1, "a", &tip),
|
||||||
|
head(2, "b", &tip_b),
|
||||||
|
head(3, "c", &tip_c),
|
||||||
|
];
|
||||||
|
let rep = sync_repo(&w.root, &opts("s2", merged)).unwrap();
|
||||||
|
let mut kept: Vec<(String, String)> = rep
|
||||||
|
.pruned
|
||||||
|
.iter()
|
||||||
|
.map(|p| match p {
|
||||||
|
Pruned::Kept { branch, why, .. } => (branch.clone(), why.clone()),
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
kept.sort();
|
||||||
|
assert_eq!(
|
||||||
|
kept,
|
||||||
|
vec![
|
||||||
|
("a".into(), "uncommitted or untracked changes".into()),
|
||||||
|
("b".into(), "ignored files: secret.env".into()),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
for b in ["a", "b", "c"] {
|
||||||
|
assert!(w.root.join(b).exists() && has_branch(&w.root, b), "{b}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_older_tip_is_pruned_but_the_default_branch_and_outside_worktrees_never_are() {
|
||||||
|
let w = world();
|
||||||
|
let first = push_branch(&w, "f");
|
||||||
|
sync_repo(&w.root, &opts("s1", vec![])).unwrap();
|
||||||
|
// The PR got more commits (from another machine) before it was merged.
|
||||||
|
w.dev.run(&["checkout", "-q", "f"]).unwrap();
|
||||||
|
commit(&w.dev, "f2.txt", "2\n");
|
||||||
|
w.dev.run(&["push", "-q", "origin", "f"]).unwrap();
|
||||||
|
let last = w.dev.run(&["rev-parse", "HEAD"]).unwrap();
|
||||||
|
w.dev.run(&["checkout", "-q", "main"]).unwrap();
|
||||||
|
assert_ne!(first, last);
|
||||||
|
// A linked worktree outside the repo directory is the user's.
|
||||||
|
let ext = w.base.join("elsewhere");
|
||||||
|
let bare = Git::new(w.root.join(".bare"));
|
||||||
|
let tip_o = push_branch(&w, "o");
|
||||||
|
bare.run(&["fetch", "-q", "origin"]).unwrap();
|
||||||
|
bare.run(&[
|
||||||
|
"worktree",
|
||||||
|
"add",
|
||||||
|
"-q",
|
||||||
|
"-b",
|
||||||
|
"o",
|
||||||
|
ext.to_str().unwrap(),
|
||||||
|
"origin/o",
|
||||||
|
])
|
||||||
|
.unwrap();
|
||||||
|
let main_tip = bare.run(&["rev-parse", "refs/heads/main"]).unwrap();
|
||||||
|
|
||||||
|
// `prune_merged` alone: `f` is still at `first` locally (no fetch/fast-forward).
|
||||||
|
let merged = vec![
|
||||||
|
head(4, "f", &last),
|
||||||
|
head(5, "main", &main_tip),
|
||||||
|
head(6, "o", &tip_o),
|
||||||
|
];
|
||||||
|
let rules = Rules {
|
||||||
|
remote: "origin",
|
||||||
|
merged: &merged,
|
||||||
|
disposable: &[],
|
||||||
|
protected: &[],
|
||||||
|
};
|
||||||
|
let pruned = prune_merged(&w.root, &rules, "me", "t").unwrap();
|
||||||
|
assert!(
|
||||||
|
matches!(pruned.as_slice(), [Pruned::Removed { branch, pr: Some(4), .. }] if branch == "f"),
|
||||||
|
"{pruned:?}"
|
||||||
|
);
|
||||||
|
assert!(w.root.join("main").exists() && ext.exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_branch_merged_without_a_pr_is_removed_but_protected_and_fresh_ones_are_not() {
|
||||||
|
let w = world();
|
||||||
|
let tip = push_branch(&w, "feat/ff");
|
||||||
|
push_branch(&w, "development");
|
||||||
|
push_branch(&w, "wip");
|
||||||
|
sync_repo(&w.root, &opts("s1", vec![])).unwrap();
|
||||||
|
// A branch at the default branch's tip has nothing of its own yet.
|
||||||
|
w.dev.run(&["push", "-q", "origin", "main:fresh"]).unwrap();
|
||||||
|
|
||||||
|
// Merged into main without a pull request (no forge answer at all), with `development`
|
||||||
|
// (long-lived, protected); `wip` is not merged.
|
||||||
|
for b in ["feat/ff", "development"] {
|
||||||
|
w.dev
|
||||||
|
.run(&["merge", "-q", "--no-ff", "-m", "m", b])
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
w.dev.run(&["push", "-q", "origin", "main"]).unwrap();
|
||||||
|
w.dev.run(&["push", "-q", "origin", "main:fresh2"]).unwrap();
|
||||||
|
let rep = sync_repo(&w.root, &opts("s2", vec![])).unwrap();
|
||||||
|
assert!(rep.fetch_error.is_none(), "{:?}", rep.fetch_error);
|
||||||
|
let [
|
||||||
|
Pruned::Removed {
|
||||||
|
branch,
|
||||||
|
pr: None,
|
||||||
|
backup_ref,
|
||||||
|
..
|
||||||
|
},
|
||||||
|
] = rep.pruned.as_slice()
|
||||||
|
else {
|
||||||
|
panic!("{:?}", rep.pruned);
|
||||||
|
};
|
||||||
|
assert_eq!(branch, "feat/ff");
|
||||||
|
let bare = Git::new(w.root.join(".bare"));
|
||||||
|
assert_eq!(bare.run(&["rev-parse", backup_ref]).unwrap(), tip);
|
||||||
|
assert!(!w.root.join("feat-ff").exists() && !has_branch(&w.root, "feat/ff"));
|
||||||
|
for d in ["development", "wip", "fresh2"] {
|
||||||
|
assert!(w.root.join(d).exists(), "{d}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// `feat/ff` stays on the remote and is not materialized again. `fresh` (materialized in
|
||||||
|
// s2) has no commits of its own: main's first-parent history passed through its tip, so it
|
||||||
|
// is not taken for a merge although main moved past it.
|
||||||
|
let rep = sync_repo(&w.root, &opts("s3", vec![])).unwrap();
|
||||||
|
assert!(rep.pruned.is_empty(), "{:?}", rep.pruned);
|
||||||
|
assert!(!w.root.join("feat-ff").exists());
|
||||||
|
assert!(w.root.join("fresh").exists() && w.root.join("fresh2").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_protected_branch_is_kept_even_as_the_head_of_a_merged_pr() {
|
||||||
|
let w = world();
|
||||||
|
let tip = push_branch(&w, "development");
|
||||||
|
squash_merge(&w, "development");
|
||||||
|
// Not materialized yet: a merged PR head must not keep a protected branch away.
|
||||||
|
let rep = sync_repo(&w.root, &opts("s1", vec![head(9, "development", &tip)])).unwrap();
|
||||||
|
assert!(
|
||||||
|
w.root.join("development").exists(),
|
||||||
|
"{:?}",
|
||||||
|
rep.materialized
|
||||||
|
);
|
||||||
|
let rep = sync_repo(&w.root, &opts("s2", vec![head(9, "development", &tip)])).unwrap();
|
||||||
|
assert!(rep.pruned.is_empty(), "{:?}", rep.pruned);
|
||||||
|
assert!(w.root.join("development").exists());
|
||||||
|
}
|
||||||
@@ -353,6 +353,52 @@ fn fast_forward_declines_instead_of_overwriting_local_ignored_file() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn files_new_in_an_ignored_directory_do_not_block_a_fast_forward() {
|
||||||
|
let w = world();
|
||||||
|
commit(&w.g1, "tool/settings.json", "{}\n");
|
||||||
|
w.g1.run(&["push", "-q"]).unwrap();
|
||||||
|
// The whole directory is ignored and exists locally, but not the incoming file.
|
||||||
|
fs::write(w.d2.join(".git/info/exclude"), "tool/\n").unwrap();
|
||||||
|
fs::create_dir_all(w.d2.join("tool/cache")).unwrap();
|
||||||
|
fs::write(w.d2.join("tool/cache/x"), "local\n").unwrap();
|
||||||
|
fetch(&w.d2, REMOTE).unwrap();
|
||||||
|
assert!(
|
||||||
|
matches!(
|
||||||
|
receive(&w.d2, "m2", "t").unwrap(),
|
||||||
|
Received::FastForwarded { .. }
|
||||||
|
),
|
||||||
|
"nothing local would be overwritten"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
fs::read_to_string(w.d2.join("tool/settings.json")).unwrap(),
|
||||||
|
"{}\n"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
fs::read_to_string(w.d2.join("tool/cache/x")).unwrap(),
|
||||||
|
"local\n"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_existing_file_in_an_ignored_directory_still_blocks_a_fast_forward() {
|
||||||
|
let w = world();
|
||||||
|
commit(&w.g1, "tool/settings.json", "theirs\n");
|
||||||
|
w.g1.run(&["push", "-q"]).unwrap();
|
||||||
|
fs::write(w.d2.join(".git/info/exclude"), "tool/\n").unwrap();
|
||||||
|
fs::create_dir_all(w.d2.join("tool")).unwrap();
|
||||||
|
fs::write(w.d2.join("tool/settings.json"), "mine\n").unwrap();
|
||||||
|
fetch(&w.d2, REMOTE).unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
receive(&w.d2, "m2", "t").unwrap(),
|
||||||
|
Received::Declined(_)
|
||||||
|
));
|
||||||
|
assert_eq!(
|
||||||
|
fs::read_to_string(w.d2.join("tool/settings.json")).unwrap(),
|
||||||
|
"mine\n"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn snapshot_apply_declines_instead_of_overwriting_local_ignored_file() {
|
fn snapshot_apply_declines_instead_of_overwriting_local_ignored_file() {
|
||||||
let w = world();
|
let w = world();
|
||||||
@@ -386,6 +432,10 @@ fn archive_and_receive_in_one_pass_do_not_collide_on_backup_refs() {
|
|||||||
offline: false,
|
offline: false,
|
||||||
materialize: true,
|
materialize: true,
|
||||||
push_snapshots: true,
|
push_snapshots: true,
|
||||||
|
merged: vec![],
|
||||||
|
disposable: vec![],
|
||||||
|
prune: false,
|
||||||
|
protected: vec![],
|
||||||
};
|
};
|
||||||
w.g1.run(&["checkout", "-q", "-b", "feat/z"]).unwrap();
|
w.g1.run(&["checkout", "-q", "-b", "feat/z"]).unwrap();
|
||||||
commit(&w.g1, "z.txt", "z\n");
|
commit(&w.g1, "z.txt", "z\n");
|
||||||
|
|||||||
@@ -16,6 +16,10 @@ fn opts(machine: &str, stamp: &str) -> Options {
|
|||||||
offline: false,
|
offline: false,
|
||||||
materialize: true,
|
materialize: true,
|
||||||
push_snapshots: true,
|
push_snapshots: true,
|
||||||
|
merged: vec![],
|
||||||
|
disposable: vec![],
|
||||||
|
prune: false,
|
||||||
|
protected: vec![],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,16 @@
|
|||||||
//! Event loop: file events are debounced per repo, a periodic pass covers fetches and anything
|
//! Event loop: file events are debounced per repo, a periodic pass covers fetches and anything
|
||||||
//! the watcher missed, failures back off exponentially. One worker thread runs the sync passes,
|
//! the watcher missed, failures back off exponentially. The loop thread schedules; a pool of
|
||||||
//! so passes never overlap.
|
//! `sync.workers` threads runs the passes, several repos at once but never two passes of the
|
||||||
|
//! same repo.
|
||||||
|
|
||||||
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::merged::{MergedCache, has_candidates};
|
||||||
|
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::prune::{Pruned, merged_how};
|
||||||
use grove_core::receive::Received;
|
use grove_core::receive::Received;
|
||||||
use grove_core::sync::{Options, sync_repo};
|
use grove_core::sync::{Options, sync_repo};
|
||||||
use notify::{EventKind, RecursiveMode, Watcher};
|
use notify::{EventKind, RecursiveMode, Watcher};
|
||||||
@@ -96,9 +100,72 @@ pub enum Msg {
|
|||||||
Rescan,
|
Rescan,
|
||||||
/// Sync one repo (or all) as soon as possible.
|
/// Sync one repo (or all) as soon as possible.
|
||||||
SyncNow(Option<PathBuf>),
|
SyncNow(Option<PathBuf>),
|
||||||
|
/// A worker finished a pass: consecutive failures (0 = success), and whether it was offline.
|
||||||
|
Done {
|
||||||
|
repo: PathBuf,
|
||||||
|
failures: u32,
|
||||||
|
offline: bool,
|
||||||
|
},
|
||||||
Shutdown,
|
Shutdown,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One pass for a worker to run.
|
||||||
|
struct Job {
|
||||||
|
repo: PathBuf,
|
||||||
|
offline: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starts `n` threads that run passes from `jobs` and report each one as [`Msg::Done`].
|
||||||
|
fn spawn_workers(
|
||||||
|
n: usize,
|
||||||
|
jobs: Receiver<Job>,
|
||||||
|
cfg: &Arc<Config>,
|
||||||
|
st: &Arc<Settings>,
|
||||||
|
visibility: &Arc<Visibility>,
|
||||||
|
forge: &Arc<ForgeMemory>,
|
||||||
|
ctx: &Ctx,
|
||||||
|
) -> Vec<JoinHandle<()>> {
|
||||||
|
let jobs = Arc::new(Mutex::new(jobs));
|
||||||
|
(0..n)
|
||||||
|
.map(|_| {
|
||||||
|
let (jobs, cfg, st, visibility, forge, ctx) = (
|
||||||
|
jobs.clone(),
|
||||||
|
cfg.clone(),
|
||||||
|
st.clone(),
|
||||||
|
visibility.clone(),
|
||||||
|
forge.clone(),
|
||||||
|
ctx.clone(),
|
||||||
|
);
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
loop {
|
||||||
|
// The lock is held only while waiting for the next job.
|
||||||
|
let job = jobs.lock().unwrap().recv();
|
||||||
|
let Ok(Job { repo, offline }) = job else {
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
// A panicking pass must still report back, or its repo is never synced again.
|
||||||
|
let failures = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||||
|
pass(&repo, &cfg, &st, &visibility, offline, &forge, &ctx)
|
||||||
|
}))
|
||||||
|
.unwrap_or_else(|_| {
|
||||||
|
ctx.activity.log(
|
||||||
|
"error",
|
||||||
|
Some(&repo.display().to_string()),
|
||||||
|
"sync pass panicked; retried with backoff",
|
||||||
|
);
|
||||||
|
1
|
||||||
|
});
|
||||||
|
let _ = ctx.tx.send(Msg::Done {
|
||||||
|
repo,
|
||||||
|
failures,
|
||||||
|
offline,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct Ctx {
|
pub struct Ctx {
|
||||||
pub shared: Arc<Mutex<Shared>>,
|
pub shared: Arc<Mutex<Shared>>,
|
||||||
@@ -334,6 +401,7 @@ fn rescan(
|
|||||||
root: &Path,
|
root: &Path,
|
||||||
groups: &[String],
|
groups: &[String],
|
||||||
watch: &mut Watch,
|
watch: &mut Watch,
|
||||||
|
running: &HashSet<PathBuf>,
|
||||||
ctx: &Ctx,
|
ctx: &Ctx,
|
||||||
) -> (Vec<PathBuf>, Vec<PathBuf>) {
|
) -> (Vec<PathBuf>, Vec<PathBuf>) {
|
||||||
// Shallow watches first, then discover: a `.bare` created in a child between the two steps
|
// Shallow watches first, then discover: a `.bare` created in a child between the two steps
|
||||||
@@ -350,8 +418,16 @@ fn rescan(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
watch.sync(&wanted, false, ctx);
|
watch.sync(&wanted, false, ctx);
|
||||||
let d = discover(root, groups);
|
let mut d = discover(root, groups);
|
||||||
let found = d.managed;
|
// A repo whose pass is running may hold `.grove-busy` (purge) for a moment: it is judged
|
||||||
|
// when the pass reports back, not now.
|
||||||
|
d.stalled.retain(|r| !running.contains(r));
|
||||||
|
let mut found = d.managed;
|
||||||
|
for r in running {
|
||||||
|
if !found.contains(r) && r.is_dir() {
|
||||||
|
found.push(r.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
for r in &d.stalled {
|
for r in &d.stalled {
|
||||||
if watch.warned_stalled.insert(r.clone()) {
|
if watch.warned_stalled.insert(r.clone()) {
|
||||||
ctx.activity.log(
|
ctx.activity.log(
|
||||||
@@ -406,7 +482,26 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
|||||||
let fetch_every = Duration::from_secs(cfg.sync.fetch_interval_s.max(1));
|
let fetch_every = Duration::from_secs(cfg.sync.fetch_interval_s.max(1));
|
||||||
let root = cfg.root_path();
|
let root = cfg.root_path();
|
||||||
let groups: Vec<String> = cfg.groups.iter().map(|g| g.name.clone()).collect();
|
let groups: Vec<String> = cfg.groups.iter().map(|g| g.name.clone()).collect();
|
||||||
let mut visibility = Visibility::load(st.visibility_cache.clone());
|
let cfg = Arc::new(cfg);
|
||||||
|
let st = Arc::new(st);
|
||||||
|
let visibility = Arc::new(Visibility::load(st.visibility_cache.clone()));
|
||||||
|
// Deletions being confirmed and merged pull requests, per repo.
|
||||||
|
let forge = Arc::new(ForgeMemory::default());
|
||||||
|
let (jobs, job_rx) = channel::<Job>();
|
||||||
|
let workers = spawn_workers(
|
||||||
|
cfg.sync.workers.max(1),
|
||||||
|
job_rx,
|
||||||
|
&cfg,
|
||||||
|
&st,
|
||||||
|
&visibility,
|
||||||
|
&forge,
|
||||||
|
&ctx,
|
||||||
|
);
|
||||||
|
// Repos a worker is running a pass for: never scheduled twice.
|
||||||
|
let mut running: HashSet<PathBuf> = HashSet::new();
|
||||||
|
// Repos whose `sync` was requested while their pass ran: that pass's failure sets no backoff.
|
||||||
|
let mut sync_asked: HashSet<PathBuf> = HashSet::new();
|
||||||
|
let pool = cfg.sync.workers.max(1);
|
||||||
let mut watch = make_watch(
|
let mut watch = make_watch(
|
||||||
ctx.tx.clone(),
|
ctx.tx.clone(),
|
||||||
cfg.sync.ignore_extra.clone(),
|
cfg.sync.ignore_extra.clone(),
|
||||||
@@ -414,7 +509,7 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
|||||||
groups.clone(),
|
groups.clone(),
|
||||||
&ctx,
|
&ctx,
|
||||||
);
|
);
|
||||||
rescan(&root, &groups, &mut watch, &ctx);
|
rescan(&root, &groups, &mut watch, &running, &ctx);
|
||||||
|
|
||||||
// due_at: when a repo should next be synced; backoff_until: earliest retry after failures.
|
// due_at: when a repo should next be synced; backoff_until: earliest retry after failures.
|
||||||
let mut due_at: HashMap<PathBuf, Instant> = HashMap::new();
|
let mut due_at: HashMap<PathBuf, Instant> = HashMap::new();
|
||||||
@@ -427,11 +522,15 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
|||||||
// 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;
|
||||||
|
|
||||||
loop {
|
'main: loop {
|
||||||
let now = Instant::now();
|
let now = Instant::now();
|
||||||
|
// With every worker busy nothing can start before a `Done` arrives: due repos must not
|
||||||
|
// shorten the wait (that would spin).
|
||||||
|
let idle = running.len() < pool;
|
||||||
let wake = due_at
|
let wake = due_at
|
||||||
.values()
|
.iter()
|
||||||
.copied()
|
.filter(|(r, _)| idle && !running.contains(*r))
|
||||||
|
.map(|(_, t)| *t)
|
||||||
.chain([next_full])
|
.chain([next_full])
|
||||||
.chain(rescan_at)
|
.chain(rescan_at)
|
||||||
.min()
|
.min()
|
||||||
@@ -462,19 +561,44 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
|||||||
}
|
}
|
||||||
Ok(Msg::SyncNow(Some(r))) => {
|
Ok(Msg::SyncNow(Some(r))) => {
|
||||||
backoff_until.remove(&r);
|
backoff_until.remove(&r);
|
||||||
|
if running.contains(&r) {
|
||||||
|
sync_asked.insert(r.clone());
|
||||||
|
}
|
||||||
due_at.insert(r, Instant::now());
|
due_at.insert(r, Instant::now());
|
||||||
}
|
}
|
||||||
Ok(Msg::SyncNow(None)) => {
|
Ok(Msg::SyncNow(None)) => {
|
||||||
backoff_until.clear();
|
backoff_until.clear();
|
||||||
|
sync_asked.extend(running.iter().cloned());
|
||||||
next_full = Instant::now();
|
next_full = Instant::now();
|
||||||
}
|
}
|
||||||
|
Ok(Msg::Done {
|
||||||
|
repo,
|
||||||
|
failures,
|
||||||
|
offline,
|
||||||
|
}) => {
|
||||||
|
running.remove(&repo);
|
||||||
|
let asked = sync_asked.remove(&repo);
|
||||||
|
if !is_ready(&repo) {
|
||||||
|
// It vanished mid-pass (or was purged): whatever the pass reported is moot.
|
||||||
|
let (found, _) = rescan(&root, &groups, &mut watch, &running, &ctx);
|
||||||
|
forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
|
||||||
|
} else if !offline {
|
||||||
|
if failures == 0 || asked {
|
||||||
|
backoff_until.remove(&repo);
|
||||||
|
} else {
|
||||||
|
let wait = Duration::from_secs(5u64.saturating_mul(1 << failures.min(6)))
|
||||||
|
.min(MAX_BACKOFF);
|
||||||
|
backoff_until.insert(repo, Instant::now() + wait);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Ok(Msg::Shutdown) | Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
|
Ok(Msg::Shutdown) | Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
|
||||||
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
|
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
|
||||||
}
|
}
|
||||||
// Discovery also runs while paused so the status stays current; only syncing stops.
|
// Discovery also runs while paused so the status stays current; only syncing stops.
|
||||||
if rescan_at.is_some_and(|t| t <= Instant::now()) {
|
if rescan_at.is_some_and(|t| t <= Instant::now()) {
|
||||||
rescan_at = None;
|
rescan_at = None;
|
||||||
let (found, added) = rescan(&root, &groups, &mut watch, &ctx);
|
let (found, added) = rescan(&root, &groups, &mut watch, &running, &ctx);
|
||||||
forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
|
forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
|
||||||
for r in added {
|
for r in added {
|
||||||
due_at.insert(r, Instant::now());
|
due_at.insert(r, Instant::now());
|
||||||
@@ -486,20 +610,31 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
|||||||
let now = Instant::now();
|
let now = Instant::now();
|
||||||
if now >= next_full {
|
if now >= next_full {
|
||||||
// Safety net for events the watcher missed (one `read_dir` per group).
|
// Safety net for events the watcher missed (one `read_dir` per group).
|
||||||
let (found, _) = rescan(&root, &groups, &mut watch, &ctx);
|
let (found, _) = rescan(&root, &groups, &mut watch, &running, &ctx);
|
||||||
forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
|
forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
|
||||||
|
// A repo still waiting keeps its earlier due time, so it is not overtaken.
|
||||||
for r in found {
|
for r in found {
|
||||||
due_at.insert(r, now);
|
due_at
|
||||||
|
.entry(r)
|
||||||
|
.and_modify(|t| *t = (*t).min(now))
|
||||||
|
.or_insert(now);
|
||||||
}
|
}
|
||||||
next_full = now + fetch_every;
|
next_full = now + fetch_every;
|
||||||
}
|
}
|
||||||
let mut due: Vec<PathBuf> = due_at
|
// A repo whose pass is running stays due and is dispatched when that pass is done.
|
||||||
|
// Longest waiting first: with more due repos than workers, the order decides who waits.
|
||||||
|
let mut due: Vec<(Instant, PathBuf)> = due_at
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|(_, t)| **t <= now)
|
.filter(|(r, t)| **t <= now && !running.contains(*r))
|
||||||
.map(|(r, _)| r.clone())
|
.map(|(r, t)| (*t, r.clone()))
|
||||||
.collect();
|
.collect();
|
||||||
due.sort();
|
due.sort();
|
||||||
for r in due {
|
for (_, r) in due {
|
||||||
|
// Only as many passes as idle workers: the rest stay due, so pause stops them and
|
||||||
|
// `offline` is decided when a pass really starts.
|
||||||
|
if running.len() >= pool {
|
||||||
|
break;
|
||||||
|
}
|
||||||
if !ctx.shared.lock().unwrap().repos.contains_key(&r) {
|
if !ctx.shared.lock().unwrap().repos.contains_key(&r) {
|
||||||
due_at.remove(&r);
|
due_at.remove(&r);
|
||||||
continue;
|
continue;
|
||||||
@@ -508,35 +643,24 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
|||||||
first_at.remove(&r);
|
first_at.remove(&r);
|
||||||
if !is_ready(&r) {
|
if !is_ready(&r) {
|
||||||
// Removed or migrated away since the last discovery: drop it, no error.
|
// Removed or migrated away since the last discovery: drop it, no error.
|
||||||
let (found, _) = rescan(&root, &groups, &mut watch, &ctx);
|
let (found, _) = rescan(&root, &groups, &mut watch, &running, &ctx);
|
||||||
forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
|
forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
// 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);
|
running.insert(r.clone());
|
||||||
if !is_ready(&r) {
|
if jobs.send(Job { repo: r, offline }).is_err() {
|
||||||
// It vanished mid-pass: whatever the pass reported is moot.
|
break 'main;
|
||||||
let (found, _) = rescan(&root, &groups, &mut watch, &ctx);
|
|
||||||
forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if offline {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if failures == 0 {
|
|
||||||
backoff_until.remove(&r);
|
|
||||||
} else {
|
|
||||||
let wait =
|
|
||||||
Duration::from_secs(5u64.saturating_mul(1 << failures.min(6))).min(MAX_BACKOFF);
|
|
||||||
backoff_until.insert(r, Instant::now() + wait);
|
|
||||||
}
|
|
||||||
if ctx.shared.lock().unwrap().paused {
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Workers finish the pass they are running; nothing is cut short.
|
||||||
|
drop(jobs);
|
||||||
|
for w in workers {
|
||||||
|
let _ = w.join();
|
||||||
|
}
|
||||||
ctx.activity.log("stop", None, "daemon stopped");
|
ctx.activity.log("stop", None, "daemon stopped");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -552,15 +676,27 @@ fn forget_removed(
|
|||||||
backoff_until.retain(|r, _| found.contains(r));
|
backoff_until.retain(|r, _| found.contains(r));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What the daemon remembers between passes about each repo's forge (in memory only), shared
|
||||||
|
/// by the workers.
|
||||||
|
#[derive(Default)]
|
||||||
|
struct ForgeMemory {
|
||||||
|
/// Repos whose forge first confirmed their deletion at this time (see `purge`).
|
||||||
|
gone_since: Mutex<HashMap<PathBuf, (u64, u64)>>,
|
||||||
|
/// Merged pull requests per repo (see `merged`).
|
||||||
|
merged: MergedCache,
|
||||||
|
}
|
||||||
|
|
||||||
/// One sync pass for `repo`; returns the number of consecutive failures (0 = success).
|
/// One sync pass for `repo`; returns the number of consecutive failures (0 = success).
|
||||||
fn pass(
|
fn pass(
|
||||||
repo: &Path,
|
repo: &Path,
|
||||||
cfg: &Config,
|
cfg: &Config,
|
||||||
st: &Settings,
|
st: &Settings,
|
||||||
visibility: &mut Visibility,
|
visibility: &Visibility,
|
||||||
offline: bool,
|
offline: bool,
|
||||||
|
forge: &ForgeMemory,
|
||||||
ctx: &Ctx,
|
ctx: &Ctx,
|
||||||
) -> u32 {
|
) -> u32 {
|
||||||
|
let ForgeMemory { gone_since, merged } = forge;
|
||||||
let name = repo.display().to_string();
|
let name = repo.display().to_string();
|
||||||
if !is_ready(repo) {
|
if !is_ready(repo) {
|
||||||
// Being migrated/cloned (or gone): leave it alone, the rediscovery sorts it out.
|
// Being migrated/cloned (or gone): leave it alone, the rediscovery sorts it out.
|
||||||
@@ -591,6 +727,22 @@ fn pass(
|
|||||||
}
|
}
|
||||||
allowed
|
allowed
|
||||||
};
|
};
|
||||||
|
// Offline passes prune nothing; the last answer still keeps pruned branches away.
|
||||||
|
let merged_heads = if !cfg.sync.prune_merged || !has_candidates(repo) {
|
||||||
|
Vec::new()
|
||||||
|
} else if offline {
|
||||||
|
merged.cached(repo)
|
||||||
|
} else {
|
||||||
|
let h = merged.heads(cfg, repo, &st.remote, &RealForge, Instant::now());
|
||||||
|
if let Some(e) = h.new_error {
|
||||||
|
ctx.activity.log(
|
||||||
|
"prune_lookup_failed",
|
||||||
|
Some(&name),
|
||||||
|
format!("cannot list merged pull requests: {e}"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
h.heads
|
||||||
|
};
|
||||||
let opts = Options {
|
let opts = Options {
|
||||||
machine: cfg.machine.name.clone(),
|
machine: cfg.machine.name.clone(),
|
||||||
stamp: stamp(),
|
stamp: stamp(),
|
||||||
@@ -598,8 +750,15 @@ fn pass(
|
|||||||
offline,
|
offline,
|
||||||
materialize,
|
materialize,
|
||||||
push_snapshots,
|
push_snapshots,
|
||||||
|
merged: merged_heads,
|
||||||
|
disposable: cfg.sync.prune_disposable.clone(),
|
||||||
|
prune: cfg.sync.prune_merged,
|
||||||
|
protected: cfg.sync.protected_branches(),
|
||||||
};
|
};
|
||||||
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 {
|
||||||
@@ -664,6 +823,31 @@ fn pass(
|
|||||||
for a in &rep.archived {
|
for a in &rep.archived {
|
||||||
ctx.activity.log("archived", Some(&name), format!("{a:?}"));
|
ctx.activity.log("archived", Some(&name), format!("{a:?}"));
|
||||||
}
|
}
|
||||||
|
let mut kept = Vec::new();
|
||||||
|
for p in &rep.pruned {
|
||||||
|
match p {
|
||||||
|
Pruned::Removed {
|
||||||
|
branch,
|
||||||
|
pr,
|
||||||
|
path,
|
||||||
|
backup_ref,
|
||||||
|
} => ctx.activity.log(
|
||||||
|
"pruned_merged",
|
||||||
|
Some(&name),
|
||||||
|
format!(
|
||||||
|
"{branch}: {}; removed {} (tip kept in {backup_ref})",
|
||||||
|
merged_how(*pr),
|
||||||
|
path.display()
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Pruned::Kept { branch, pr, why } => {
|
||||||
|
kept.push(format!("{branch}: {} but kept: {why}", merged_how(*pr)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for k in merged.new_notes(repo, kept) {
|
||||||
|
ctx.activity.log("prune_kept", Some(&name), k);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !errors.is_empty() && !is_ready(repo) {
|
if !errors.is_empty() && !is_ready(repo) {
|
||||||
@@ -693,6 +877,117 @@ 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: &Mutex<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.lock().unwrap().remove(repo);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
match purge::confirmed_gone(cfg, repo, &st.remote, &RealForge) {
|
||||||
|
Ok(true) => {}
|
||||||
|
Ok(false) => {
|
||||||
|
gone_since.lock().unwrap().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 first = {
|
||||||
|
let mut map = gone_since.lock().unwrap();
|
||||||
|
let entry = map.entry(repo.to_path_buf()).or_insert((now, now));
|
||||||
|
if now.saturating_sub(entry.1) > purge::STALE_AFTER_SECS {
|
||||||
|
// Stale: start over.
|
||||||
|
*entry = (now, now);
|
||||||
|
}
|
||||||
|
entry.1 = now;
|
||||||
|
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: &Mutex<HashMap<PathBuf, (u64, u64)>>| {
|
||||||
|
gone_since.lock().unwrap().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,8 @@ pub mod activity;
|
|||||||
pub mod daemon;
|
pub mod daemon;
|
||||||
pub mod discover;
|
pub mod discover;
|
||||||
pub mod ipc;
|
pub mod ipc;
|
||||||
|
pub mod merged;
|
||||||
|
pub mod purge;
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
#[path = "../../../test-support/tmp.rs"]
|
#[path = "../../../test-support/tmp.rs"]
|
||||||
mod test_tmp;
|
mod test_tmp;
|
||||||
|
|||||||
@@ -5,6 +5,9 @@ use grove_core::config::Config;
|
|||||||
use grove_daemon::{Daemon, Settings};
|
use grove_daemon::{Daemon, Settings};
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
/// Upper bound for one git call of the daemon (a large first fetch included).
|
||||||
|
const GIT_TIMEOUT_SECS: u64 = 900;
|
||||||
|
|
||||||
fn main() -> Result<()> {
|
fn main() -> Result<()> {
|
||||||
let mut args = std::env::args().skip(1);
|
let mut args = std::env::args().skip(1);
|
||||||
let mut config: Option<PathBuf> = None;
|
let mut config: Option<PathBuf> = None;
|
||||||
@@ -23,6 +26,13 @@ fn main() -> Result<()> {
|
|||||||
.context("cannot determine config path")?;
|
.context("cannot determine config path")?;
|
||||||
let cfg = Config::load(&path)?;
|
let cfg = Config::load(&path)?;
|
||||||
grove_core::snapshot::set_max_file_bytes(cfg.sync.max_file_mb * 1024 * 1024);
|
grove_core::snapshot::set_max_file_bytes(cfg.sync.max_file_mb * 1024 * 1024);
|
||||||
|
// Unattended: git/ssh must never prompt (the session's SSH_ASKPASS would open a dialog and
|
||||||
|
// block every sync), and no git call may block the sync loop forever.
|
||||||
|
for (k, v) in grove_core::git::noninteractive_env() {
|
||||||
|
// SAFETY: still single-threaded; no other thread reads the environment yet.
|
||||||
|
unsafe { std::env::set_var(k, v) };
|
||||||
|
}
|
||||||
|
grove_core::git::set_timeout(GIT_TIMEOUT_SECS);
|
||||||
let st = Settings::standard();
|
let st = Settings::standard();
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"groved: machine {:?}, root {}, socket {}",
|
"groved: machine {:?}, root {}, socket {}",
|
||||||
|
|||||||
@@ -0,0 +1,256 @@
|
|||||||
|
//! Which branches of a repo were merged through a pull request on its forge (`origin`), so
|
||||||
|
//! that their worktrees can be pruned (`grove_core::prune`).
|
||||||
|
//!
|
||||||
|
//! The daemon asks the forge at most every [`TTL`] per repo, and only for repos that have a
|
||||||
|
//! worktree on a branch other than the default one. A failed lookup keeps the last answer, so a
|
||||||
|
//! forge outage never makes `materialize` bring back worktrees that were pruned.
|
||||||
|
|
||||||
|
use crate::visibility::{RealForge, parse_remote, provider_for};
|
||||||
|
use grove_core::config::{Config, Provider as ProviderCfg};
|
||||||
|
use grove_core::git::Git;
|
||||||
|
use grove_core::inspect::worktrees;
|
||||||
|
use grove_core::prune::MergedHead;
|
||||||
|
use std::collections::{BTreeSet, HashMap};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::Mutex;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
/// How long a forge answer is reused.
|
||||||
|
pub const TTL: Duration = Duration::from_secs(300);
|
||||||
|
|
||||||
|
/// Lists the merged pull requests of a repo on a forge.
|
||||||
|
pub trait PullSource {
|
||||||
|
fn merged(
|
||||||
|
&self,
|
||||||
|
id: &str,
|
||||||
|
pc: &ProviderCfg,
|
||||||
|
owner: &str,
|
||||||
|
name: &str,
|
||||||
|
) -> Result<Vec<MergedHead>, String>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PullSource for RealForge {
|
||||||
|
fn merged(
|
||||||
|
&self,
|
||||||
|
id: &str,
|
||||||
|
pc: &ProviderCfg,
|
||||||
|
owner: &str,
|
||||||
|
name: &str,
|
||||||
|
) -> Result<Vec<MergedHead>, String> {
|
||||||
|
let (token, _) = grove_providers::token::resolve(id, pc).map_err(|e| e.to_string())?;
|
||||||
|
let forge = grove_providers::build(pc, token);
|
||||||
|
let pulls = grove_providers::merged_pulls_following_moves(forge.as_ref(), owner, name)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
Ok(pulls
|
||||||
|
.into_iter()
|
||||||
|
.map(|p| MergedHead {
|
||||||
|
number: p.number,
|
||||||
|
branch: p.head_ref,
|
||||||
|
sha: p.head_sha,
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The merged pull requests of the repo at `repo` (bare layout), looked up on the forge that
|
||||||
|
/// serves its `remote` fetch URL.
|
||||||
|
pub fn lookup(
|
||||||
|
cfg: &Config,
|
||||||
|
repo: &Path,
|
||||||
|
remote: &str,
|
||||||
|
src: &dyn PullSource,
|
||||||
|
) -> Result<Vec<MergedHead>, 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)?;
|
||||||
|
src.merged(pid, pc, &id.owner, &id.name)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True when the repo has a worktree on a branch other than `.bare`'s HEAD: only then can
|
||||||
|
/// anything be pruned, so only then is the forge asked.
|
||||||
|
pub fn has_candidates(repo: &Path) -> bool {
|
||||||
|
let bare = repo.join(".bare");
|
||||||
|
let default = Git::new(&bare)
|
||||||
|
.probe(&["symbolic-ref", "--short", "-q", "HEAD"])
|
||||||
|
.ok()
|
||||||
|
.flatten();
|
||||||
|
worktrees(&bare).is_ok_and(|wts| {
|
||||||
|
wts.iter()
|
||||||
|
.filter_map(|w| w.branch.as_deref())
|
||||||
|
.any(|b| Some(b) != default.as_deref())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Entry {
|
||||||
|
checked: Option<Instant>,
|
||||||
|
heads: Vec<MergedHead>,
|
||||||
|
error: Option<String>,
|
||||||
|
/// "Kept" notes already logged, so a merged worktree with local work is reported once.
|
||||||
|
noted: BTreeSet<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Per-repo forge answers and notes (in memory only), shared by the daemon's sync workers. The
|
||||||
|
/// lock is never held across a forge request.
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct MergedCache {
|
||||||
|
entries: Mutex<HashMap<PathBuf, Entry>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Result of [`MergedCache::heads`].
|
||||||
|
pub struct Heads {
|
||||||
|
pub heads: Vec<MergedHead>,
|
||||||
|
/// A lookup error that differs from the previous one (to be logged once).
|
||||||
|
pub new_error: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MergedCache {
|
||||||
|
/// The merged heads of `repo`, asking `src` when the cached answer is older than [`TTL`].
|
||||||
|
pub fn heads(
|
||||||
|
&self,
|
||||||
|
cfg: &Config,
|
||||||
|
repo: &Path,
|
||||||
|
remote: &str,
|
||||||
|
src: &dyn PullSource,
|
||||||
|
now: Instant,
|
||||||
|
) -> Heads {
|
||||||
|
{
|
||||||
|
let mut entries = self.entries.lock().unwrap();
|
||||||
|
let e = entries.entry(repo.to_path_buf()).or_default();
|
||||||
|
if e.checked
|
||||||
|
.is_some_and(|t| now.saturating_duration_since(t) < TTL)
|
||||||
|
{
|
||||||
|
return Heads {
|
||||||
|
heads: e.heads.clone(),
|
||||||
|
new_error: None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
e.checked = Some(now);
|
||||||
|
}
|
||||||
|
let answer = lookup(cfg, repo, remote, src);
|
||||||
|
let mut entries = self.entries.lock().unwrap();
|
||||||
|
let e = entries.entry(repo.to_path_buf()).or_default();
|
||||||
|
let mut new_error = None;
|
||||||
|
match answer {
|
||||||
|
Ok(h) => {
|
||||||
|
e.heads = h;
|
||||||
|
e.error = None;
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
if e.error.as_deref() != Some(&err) {
|
||||||
|
new_error = Some(err.clone());
|
||||||
|
}
|
||||||
|
e.error = Some(err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Heads {
|
||||||
|
heads: e.heads.clone(),
|
||||||
|
new_error,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Of the "kept" notes of this pass, those not logged yet for `repo`. Notes that no longer
|
||||||
|
/// apply are forgotten, so they are logged again if they come back.
|
||||||
|
pub fn new_notes(&self, repo: &Path, notes: Vec<String>) -> Vec<String> {
|
||||||
|
let mut entries = self.entries.lock().unwrap();
|
||||||
|
let e = entries.entry(repo.to_path_buf()).or_default();
|
||||||
|
let now: BTreeSet<String> = notes.into_iter().collect();
|
||||||
|
let fresh = now.difference(&e.noted).cloned().collect();
|
||||||
|
e.noted = now;
|
||||||
|
fresh
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The last answer for `repo`, without asking the forge (offline passes).
|
||||||
|
pub fn cached(&self, repo: &Path) -> Vec<MergedHead> {
|
||||||
|
self.entries
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.get(repo)
|
||||||
|
.map(|e| e.heads.clone())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::test_tmp as tmp;
|
||||||
|
use std::cell::{Cell, RefCell};
|
||||||
|
|
||||||
|
struct Fake {
|
||||||
|
calls: Cell<u32>,
|
||||||
|
asked: RefCell<Vec<String>>,
|
||||||
|
answer: RefCell<Result<Vec<MergedHead>, String>>,
|
||||||
|
}
|
||||||
|
impl PullSource for Fake {
|
||||||
|
fn merged(
|
||||||
|
&self,
|
||||||
|
id: &str,
|
||||||
|
_: &ProviderCfg,
|
||||||
|
owner: &str,
|
||||||
|
name: &str,
|
||||||
|
) -> Result<Vec<MergedHead>, String> {
|
||||||
|
self.calls.set(self.calls.get() + 1);
|
||||||
|
self.asked.borrow_mut().push(format!("{id}:{owner}/{name}"));
|
||||||
|
self.answer.borrow().clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn head(n: u64) -> MergedHead {
|
||||||
|
MergedHead {
|
||||||
|
number: n,
|
||||||
|
branch: format!("b{n}"),
|
||||||
|
sha: "0".repeat(40),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn answers_are_cached_and_kept_on_failure() {
|
||||||
|
let d = tmp::TempDir::new("merged-cache");
|
||||||
|
let repo = d.path().join("G/r");
|
||||||
|
std::fs::create_dir_all(&repo).unwrap();
|
||||||
|
let bare = repo.join(".bare");
|
||||||
|
Git::new(d.path())
|
||||||
|
.run(&["init", "-q", "--bare", bare.to_str().unwrap()])
|
||||||
|
.unwrap();
|
||||||
|
Git::new(&bare)
|
||||||
|
.run(&["remote", "add", "origin", "git@git.example.es:Org/r.git"])
|
||||||
|
.unwrap();
|
||||||
|
let cfg = Config::parse(
|
||||||
|
"[machine]\nname=\"m\"\n[root]\npath=\"/x\"\n\
|
||||||
|
[providers.gitea]\nkind=\"gitea\"\nurl=\"https://git.example.es\"\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let f = Fake {
|
||||||
|
calls: Cell::new(0),
|
||||||
|
asked: RefCell::new(vec![]),
|
||||||
|
answer: RefCell::new(Ok(vec![head(1)])),
|
||||||
|
};
|
||||||
|
let c = MergedCache::default();
|
||||||
|
let t0 = Instant::now();
|
||||||
|
assert_eq!(c.heads(&cfg, &repo, "origin", &f, t0).heads, vec![head(1)]);
|
||||||
|
assert_eq!(f.asked.borrow().as_slice(), ["gitea:Org/r"]);
|
||||||
|
// Within the TTL the forge is not asked again.
|
||||||
|
c.heads(&cfg, &repo, "origin", &f, t0 + Duration::from_secs(10));
|
||||||
|
assert_eq!(f.calls.get(), 1);
|
||||||
|
// A failure keeps the last answer and is reported once.
|
||||||
|
*f.answer.borrow_mut() = Err("down".into());
|
||||||
|
let h = c.heads(&cfg, &repo, "origin", &f, t0 + TTL);
|
||||||
|
assert_eq!((h.heads, h.new_error), (vec![head(1)], Some("down".into())));
|
||||||
|
let h = c.heads(&cfg, &repo, "origin", &f, t0 + TTL * 2);
|
||||||
|
assert_eq!((h.heads, h.new_error), (vec![head(1)], None));
|
||||||
|
assert_eq!(f.calls.get(), 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn notes_are_reported_once_while_they_hold() {
|
||||||
|
let c = MergedCache::default();
|
||||||
|
let r = Path::new("/r");
|
||||||
|
assert_eq!(c.new_notes(r, vec!["a".into()]), vec!["a".to_string()]);
|
||||||
|
assert!(c.new_notes(r, vec!["a".into()]).is_empty());
|
||||||
|
assert!(c.new_notes(r, vec![]).is_empty());
|
||||||
|
assert_eq!(c.new_notes(r, vec!["a".into()]), vec!["a".to_string()]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,387 @@
|
|||||||
|
//! 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;
|
||||||
|
/// A confirmation older than this (no check in between, e.g. the forge was unreachable) no
|
||||||
|
/// longer counts and the wait starts over. Much longer than the time between two passes of
|
||||||
|
/// one repo, which can exceed 20 minutes with many repos.
|
||||||
|
pub const STALE_AFTER_SECS: u64 = 6 * 3600;
|
||||||
|
|
||||||
|
/// 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",
|
||||||
|
"cannot find repository", // Gitea/Forgejo over SSH
|
||||||
|
"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(
|
||||||
|
"git fetch -q --prune origin failed (Some(128)): error:\nerror: Cannot find \
|
||||||
|
repository: dasemu/x\nerror:\nfatal: Could not read from remote 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,6 +15,7 @@ use grove_core::sync::git_dir_for;
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::collections::{BTreeMap, HashMap};
|
use std::collections::{BTreeMap, HashMap};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
/// How long a "private" answer is trusted (a repo can be made public at any time).
|
/// How long a "private" answer is trusted (a repo can be made public at any time).
|
||||||
pub const PRIVATE_TTL: u64 = 3600;
|
pub const PRIVATE_TTL: u64 = 3600;
|
||||||
@@ -223,10 +224,16 @@ impl Entry {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Visibility cache. Owned by the daemon's single worker thread.
|
/// Visibility cache, shared by the daemon's sync workers. The lock is never held across a
|
||||||
|
/// forge request, so lookups for different repos run in parallel.
|
||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default)]
|
||||||
pub struct Visibility {
|
pub struct Visibility {
|
||||||
path: Option<PathBuf>,
|
path: Option<PathBuf>,
|
||||||
|
state: Mutex<Cache>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
struct Cache {
|
||||||
entries: BTreeMap<String, Entry>,
|
entries: BTreeMap<String, Entry>,
|
||||||
failed: HashMap<String, (u64, String)>,
|
failed: HashMap<String, (u64, String)>,
|
||||||
logins: HashMap<String, String>,
|
logins: HashMap<String, String>,
|
||||||
@@ -242,12 +249,14 @@ impl Visibility {
|
|||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
Visibility {
|
Visibility {
|
||||||
path,
|
path,
|
||||||
|
state: Mutex::new(Cache {
|
||||||
entries,
|
entries,
|
||||||
..Visibility::default()
|
..Cache::default()
|
||||||
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn save(&self) {
|
fn save(&self, entries: &BTreeMap<String, Entry>) {
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
use std::os::unix::fs::OpenOptionsExt;
|
use std::os::unix::fs::OpenOptionsExt;
|
||||||
let Some(path) = &self.path else { return };
|
let Some(path) = &self.path else { return };
|
||||||
@@ -256,7 +265,7 @@ impl Visibility {
|
|||||||
}
|
}
|
||||||
let tmp = path.with_extension("json.tmp");
|
let tmp = path.with_extension("json.tmp");
|
||||||
let _ = std::fs::remove_file(&tmp);
|
let _ = std::fs::remove_file(&tmp);
|
||||||
let Ok(text) = serde_json::to_string_pretty(&self.entries) else {
|
let Ok(text) = serde_json::to_string_pretty(entries) else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
let written = std::fs::OpenOptions::new()
|
let written = std::fs::OpenOptions::new()
|
||||||
@@ -272,7 +281,7 @@ impl Visibility {
|
|||||||
|
|
||||||
/// What the forge says about `owner/name` on provider `pid`, from the cache or the forge.
|
/// What the forge says about `owner/name` on provider `pid`, from the cache or the forge.
|
||||||
fn seen(
|
fn seen(
|
||||||
&mut self,
|
&self,
|
||||||
pid: &str,
|
pid: &str,
|
||||||
pc: &ProviderCfg,
|
pc: &ProviderCfg,
|
||||||
owner: &str,
|
owner: &str,
|
||||||
@@ -282,34 +291,39 @@ impl Visibility {
|
|||||||
) -> Result<Seen, String> {
|
) -> Result<Seen, String> {
|
||||||
let url = pc.url.as_deref().unwrap_or_default().trim_end_matches('/');
|
let url = pc.url.as_deref().unwrap_or_default().trim_end_matches('/');
|
||||||
let key = format!("{pid}|{url}|{owner}/{name}").to_ascii_lowercase();
|
let key = format!("{pid}|{url}|{owner}/{name}").to_ascii_lowercase();
|
||||||
if let Some(e) = self.entries.get(&key)
|
{
|
||||||
|
let c = self.state.lock().unwrap();
|
||||||
|
if let Some(e) = c.entries.get(&key)
|
||||||
&& e.fresh(now)
|
&& e.fresh(now)
|
||||||
{
|
{
|
||||||
return Ok(e.seen);
|
return Ok(e.seen);
|
||||||
}
|
}
|
||||||
if let Some((at, why)) = self.failed.get(&key)
|
if let Some((at, why)) = c.failed.get(&key)
|
||||||
&& at.saturating_sub(0) <= now
|
&& at.saturating_sub(0) <= now
|
||||||
&& now - at < RETRY
|
&& now - at < RETRY
|
||||||
{
|
{
|
||||||
return Err(why.clone());
|
return Err(why.clone());
|
||||||
}
|
}
|
||||||
match forge.seen(pid, pc, owner, name) {
|
}
|
||||||
|
let answer = forge.seen(pid, pc, owner, name);
|
||||||
|
let mut c = self.state.lock().unwrap();
|
||||||
|
match answer {
|
||||||
Ok(seen) => {
|
Ok(seen) => {
|
||||||
self.failed.remove(&key);
|
c.failed.remove(&key);
|
||||||
self.entries.insert(key, Entry { seen, checked: now });
|
c.entries.insert(key, Entry { seen, checked: now });
|
||||||
self.save();
|
self.save(&c.entries);
|
||||||
Ok(seen)
|
Ok(seen)
|
||||||
}
|
}
|
||||||
Err(why) => {
|
Err(why) => {
|
||||||
let why = format!("lookup on {pid:?} failed: {why}");
|
let why = format!("lookup on {pid:?} failed: {why}");
|
||||||
self.failed.insert(key, (now, why.clone()));
|
c.failed.insert(key, (now, why.clone()));
|
||||||
Err(why)
|
Err(why)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Visibility of the repo behind one push URL.
|
/// Visibility of the repo behind one push URL.
|
||||||
pub fn check_url(&mut self, cfg: &Config, url: &str, now: u64, forge: &dyn Forge) -> Verdict {
|
pub fn check_url(&self, cfg: &Config, url: &str, now: u64, forge: &dyn Forge) -> Verdict {
|
||||||
let Some(id) = parse_remote(url) else {
|
let Some(id) = parse_remote(url) else {
|
||||||
return Verdict::Unknown("push URL not understood".into());
|
return Verdict::Unknown("push URL not understood".into());
|
||||||
};
|
};
|
||||||
@@ -327,7 +341,7 @@ impl Visibility {
|
|||||||
|
|
||||||
/// Mirror target `name` on provider `pid`: `Ok` when it is private or does not exist.
|
/// Mirror target `name` on provider `pid`: `Ok` when it is private or does not exist.
|
||||||
fn check_mirror(
|
fn check_mirror(
|
||||||
&mut self,
|
&self,
|
||||||
cfg: &Config,
|
cfg: &Config,
|
||||||
group: &str,
|
group: &str,
|
||||||
pid: &str,
|
pid: &str,
|
||||||
@@ -346,16 +360,20 @@ impl Visibility {
|
|||||||
.and_then(|g| g.owner(pid))
|
.and_then(|g| g.owner(pid))
|
||||||
{
|
{
|
||||||
Some(o) => o.to_string(),
|
Some(o) => o.to_string(),
|
||||||
None => match self.logins.get(pid) {
|
None => {
|
||||||
Some(l) => l.clone(),
|
let known = self.state.lock().unwrap().logins.get(pid).cloned();
|
||||||
|
match known {
|
||||||
|
Some(l) => l,
|
||||||
None => {
|
None => {
|
||||||
let l = forge
|
let l = forge
|
||||||
.login(pid, pc)
|
.login(pid, pc)
|
||||||
.map_err(|e| format!("mirror on {pid:?}: cannot get login: {e}"))?;
|
.map_err(|e| format!("mirror on {pid:?}: cannot get login: {e}"))?;
|
||||||
self.logins.insert(pid.to_string(), l.clone());
|
let mut c = self.state.lock().unwrap();
|
||||||
|
c.logins.insert(pid.to_string(), l.clone());
|
||||||
l
|
l
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
match self.seen(pid, pc, &owner, name, now, forge) {
|
match self.seen(pid, pc, &owner, name, now, forge) {
|
||||||
Ok(Seen::NotPrivate) => Err(format!("mirror {pid}:{owner}/{name} is public")),
|
Ok(Seen::NotPrivate) => Err(format!("mirror {pid}:{owner}/{name} is public")),
|
||||||
@@ -395,7 +413,7 @@ pub fn snapshot_gate(
|
|||||||
cfg: &Config,
|
cfg: &Config,
|
||||||
repo: &Path,
|
repo: &Path,
|
||||||
remote: &str,
|
remote: &str,
|
||||||
vis: &mut Visibility,
|
vis: &Visibility,
|
||||||
now: u64,
|
now: u64,
|
||||||
forge: &dyn Forge,
|
forge: &dyn Forge,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
@@ -559,7 +577,7 @@ owners = { github = "gh-org" }
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
let e = provider_for(&dup, &parse_remote("https://h.io/o/r").unwrap()).unwrap_err();
|
let e = provider_for(&dup, &parse_remote("https://h.io/o/r").unwrap()).unwrap_err();
|
||||||
assert!(e.contains("several"));
|
assert!(e.contains("several"));
|
||||||
let mut v = Visibility::default();
|
let v = Visibility::default();
|
||||||
let fake = Fake::default().with("o/r", Ok(Seen::Private));
|
let fake = Fake::default().with("o/r", Ok(Seen::Private));
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
v.check_url(&dup, "https://h.io/o/r", 0, &fake),
|
v.check_url(&dup, "https://h.io/o/r", 0, &fake),
|
||||||
@@ -571,7 +589,7 @@ owners = { github = "gh-org" }
|
|||||||
#[test]
|
#[test]
|
||||||
fn unknown_visibility_is_public_and_withholds_snapshots() {
|
fn unknown_visibility_is_public_and_withholds_snapshots() {
|
||||||
let c = cfg();
|
let c = cfg();
|
||||||
let mut v = Visibility::default();
|
let v = Visibility::default();
|
||||||
let boom = Fake::default();
|
let boom = Fake::default();
|
||||||
for url in [
|
for url in [
|
||||||
"https://gitlab.com/o/r.git",
|
"https://gitlab.com/o/r.git",
|
||||||
@@ -608,7 +626,7 @@ owners = { github = "gh-org" }
|
|||||||
#[test]
|
#[test]
|
||||||
fn private_answers_expire_after_an_hour_and_failures_are_throttled() {
|
fn private_answers_expire_after_an_hour_and_failures_are_throttled() {
|
||||||
let c = cfg();
|
let c = cfg();
|
||||||
let mut v = Visibility::default();
|
let v = Visibility::default();
|
||||||
let f = Fake::default().with("o/r", Ok(Seen::Private));
|
let f = Fake::default().with("o/r", Ok(Seen::Private));
|
||||||
let url = "https://github.com/o/r";
|
let url = "https://github.com/o/r";
|
||||||
assert_eq!(v.check_url(&c, url, 100, &f), Verdict::Private);
|
assert_eq!(v.check_url(&c, url, 100, &f), Verdict::Private);
|
||||||
@@ -654,7 +672,7 @@ owners = { github = "gh-org" }
|
|||||||
#[test]
|
#[test]
|
||||||
fn cache_keys_include_provider_and_are_case_normalised() {
|
fn cache_keys_include_provider_and_are_case_normalised() {
|
||||||
let c = cfg();
|
let c = cfg();
|
||||||
let mut v = Visibility::default();
|
let v = Visibility::default();
|
||||||
let f = Fake::default().with("o/r", Ok(Seen::Private));
|
let f = Fake::default().with("o/r", Ok(Seen::Private));
|
||||||
v.check_url(&c, "https://github.com/O/R.git", 0, &f);
|
v.check_url(&c, "https://github.com/O/R.git", 0, &f);
|
||||||
v.check_url(&c, "git@github.com:o/r", 0, &f);
|
v.check_url(&c, "git@github.com:o/r", 0, &f);
|
||||||
@@ -676,7 +694,7 @@ owners = { github = "gh-org" }
|
|||||||
let file = dir.join("visibility.json");
|
let file = dir.join("visibility.json");
|
||||||
let c = cfg();
|
let c = cfg();
|
||||||
let f = Fake::default().with("o/r", Ok(Seen::NotPrivate));
|
let f = Fake::default().with("o/r", Ok(Seen::NotPrivate));
|
||||||
let mut v = Visibility::load(Some(file.clone()));
|
let v = Visibility::load(Some(file.clone()));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
v.check_url(&c, "https://github.com/o/r", 50, &f),
|
v.check_url(&c, "https://github.com/o/r", 50, &f),
|
||||||
Verdict::Public
|
Verdict::Public
|
||||||
@@ -684,7 +702,7 @@ owners = { github = "gh-org" }
|
|||||||
let mode = std::fs::metadata(&file).unwrap().permissions().mode() & 0o777;
|
let mode = std::fs::metadata(&file).unwrap().permissions().mode() & 0o777;
|
||||||
assert_eq!(mode, 0o600);
|
assert_eq!(mode, 0o600);
|
||||||
let never = Fake::default();
|
let never = Fake::default();
|
||||||
let mut again = Visibility::load(Some(file));
|
let again = Visibility::load(Some(file));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
again.check_url(&c, "https://github.com/o/r", 60, &never),
|
again.check_url(&c, "https://github.com/o/r", 60, &never),
|
||||||
Verdict::Public
|
Verdict::Public
|
||||||
@@ -721,22 +739,16 @@ owners = { github = "gh-org" }
|
|||||||
let f = Fake::default()
|
let f = Fake::default()
|
||||||
.with("o/r", Ok(Seen::Private))
|
.with("o/r", Ok(Seen::Private))
|
||||||
.with("o/open", Ok(Seen::NotPrivate));
|
.with("o/open", Ok(Seen::NotPrivate));
|
||||||
let mut v = Visibility::default();
|
let v = Visibility::default();
|
||||||
let gate = |repo: &Path, v: &mut Visibility| snapshot_gate(&c, repo, "origin", v, 0, &f);
|
let gate = |repo: &Path, v: &Visibility| snapshot_gate(&c, repo, "origin", v, 0, &f);
|
||||||
let ok = "https://git.example.com:3000/o/r.git";
|
let ok = "https://git.example.com:3000/o/r.git";
|
||||||
assert!(gate(&mk(&base, "priv", &[ok], &[]), &mut v).is_ok());
|
assert!(gate(&mk(&base, "priv", &[ok], &[]), &v).is_ok());
|
||||||
assert!(gate(&mk(&base, "off", &[ok], &[]), &mut v).is_err());
|
assert!(gate(&mk(&base, "off", &[ok], &[]), &v).is_err());
|
||||||
assert!(
|
assert!(gate(&mk(&base, "all", &["https://unknown.example/o/r"], &[]), &v).is_ok());
|
||||||
gate(
|
|
||||||
&mk(&base, "all", &["https://unknown.example/o/r"], &[]),
|
|
||||||
&mut v
|
|
||||||
)
|
|
||||||
.is_ok()
|
|
||||||
);
|
|
||||||
// Fetch URL private, but the push goes to a public repo (pushurl).
|
// Fetch URL private, but the push goes to a public repo (pushurl).
|
||||||
let e = gate(
|
let e = gate(
|
||||||
&mk(&base, "priv2", &[ok], &["https://github.com/o/open"]),
|
&mk(&base, "priv2", &[ok], &["https://github.com/o/open"]),
|
||||||
&mut v,
|
&v,
|
||||||
);
|
);
|
||||||
assert!(e.is_err());
|
assert!(e.is_err());
|
||||||
// Private-only without any remote: unknown, withheld.
|
// Private-only without any remote: unknown, withheld.
|
||||||
@@ -744,7 +756,7 @@ owners = { github = "gh-org" }
|
|||||||
std::fs::create_dir_all(&bare).unwrap();
|
std::fs::create_dir_all(&bare).unwrap();
|
||||||
Git::new(&bare).run(&["init", "-q", "--bare"]).unwrap();
|
Git::new(&bare).run(&["init", "-q", "--bare"]).unwrap();
|
||||||
assert!(
|
assert!(
|
||||||
gate(&base.join("priv/none"), &mut v)
|
gate(&base.join("priv/none"), &v)
|
||||||
.unwrap_err()
|
.unwrap_err()
|
||||||
.contains("unknown")
|
.contains("unknown")
|
||||||
);
|
);
|
||||||
@@ -760,24 +772,24 @@ owners = { github = "gh-org" }
|
|||||||
let f = Fake::default()
|
let f = Fake::default()
|
||||||
.with("o/r", Ok(Seen::Private))
|
.with("o/r", Ok(Seen::Private))
|
||||||
.with("o/open", Ok(Seen::NotPrivate));
|
.with("o/open", Ok(Seen::NotPrivate));
|
||||||
let mut v = Visibility::default();
|
let v = Visibility::default();
|
||||||
let ok = "https://git.example.com:3000/o/r.git";
|
let ok = "https://git.example.com:3000/o/r.git";
|
||||||
let open = "https://github.com/o/open";
|
let open = "https://github.com/o/open";
|
||||||
// Group "priv": private fetch URL + public pushurl => withheld; both private => allowed.
|
// Group "priv": private fetch URL + public pushurl => withheld; both private => allowed.
|
||||||
let both = mk(&base, "priv", &[ok], &[ok, "https://github.com/o/r"]);
|
let both = mk(&base, "priv", &[ok], &[ok, "https://github.com/o/r"]);
|
||||||
assert!(snapshot_gate(&c, &both, "origin", &mut v, 0, &f).is_ok());
|
assert!(snapshot_gate(&c, &both, "origin", &v, 0, &f).is_ok());
|
||||||
std::fs::remove_dir_all(base.join("priv")).unwrap();
|
std::fs::remove_dir_all(base.join("priv")).unwrap();
|
||||||
let leaky = mk(&base, "priv", &[ok, open], &[]);
|
let leaky = mk(&base, "priv", &[ok, open], &[]);
|
||||||
let e = snapshot_gate(&c, &leaky, "origin", &mut v, 0, &f).unwrap_err();
|
let e = snapshot_gate(&c, &leaky, "origin", &v, 0, &f).unwrap_err();
|
||||||
assert!(e.contains("public"), "{e}");
|
assert!(e.contains("public"), "{e}");
|
||||||
// pushInsteadOf rewrites the push URL to a public repo.
|
// pushInsteadOf rewrites the push URL to a public repo.
|
||||||
let g = Git::new(leaky.join(".bare"));
|
let g = Git::new(leaky.join(".bare"));
|
||||||
g.run(&["remote", "set-url", "--delete", "origin", open])
|
g.run(&["remote", "set-url", "--delete", "origin", open])
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(snapshot_gate(&c, &leaky, "origin", &mut v, 0, &f).is_ok());
|
assert!(snapshot_gate(&c, &leaky, "origin", &v, 0, &f).is_ok());
|
||||||
g.run(&["config", &format!("url.{open}.pushInsteadOf"), ok])
|
g.run(&["config", &format!("url.{open}.pushInsteadOf"), ok])
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(snapshot_gate(&c, &leaky, "origin", &mut v, 0, &f).is_err());
|
assert!(snapshot_gate(&c, &leaky, "origin", &v, 0, &f).is_err());
|
||||||
std::fs::remove_dir_all(&base).unwrap();
|
std::fs::remove_dir_all(&base).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -789,8 +801,8 @@ owners = { github = "gh-org" }
|
|||||||
let _ = std::fs::remove_dir_all(&base);
|
let _ = std::fs::remove_dir_all(&base);
|
||||||
let repo = mk(&base, "mir", &["https://git.example.com:3000/o/r.git"], &[]);
|
let repo = mk(&base, "mir", &["https://git.example.com:3000/o/r.git"], &[]);
|
||||||
let gate = |f: &Fake| {
|
let gate = |f: &Fake| {
|
||||||
let mut v = Visibility::default();
|
let v = Visibility::default();
|
||||||
snapshot_gate(&c, &repo, "origin", &mut v, 0, f)
|
snapshot_gate(&c, &repo, "origin", &v, 0, f)
|
||||||
};
|
};
|
||||||
let base_f = || Fake::default().with("o/r", Ok(Seen::Private));
|
let base_f = || Fake::default().with("o/r", Ok(Seen::Private));
|
||||||
// No mirror (404): fine. Mirror owner comes from `owners`.
|
// No mirror (404): fine. Mirror owner comes from `owners`.
|
||||||
|
|||||||
@@ -768,3 +768,69 @@ fn clone_appears_only_when_complete() {
|
|||||||
assert!(seen, "cloned repo never managed");
|
assert!(seen, "cloned repo never managed");
|
||||||
d.shutdown();
|
d.shutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_hanging_fetch_does_not_hold_up_other_repos() {
|
||||||
|
let w = world("workers", &["pca"]);
|
||||||
|
// `a-slow` sorts first, so its pass is dispatched first; its fetch hangs for 15 s.
|
||||||
|
let slow = w.base.join("pca/g/a-slow");
|
||||||
|
bare_layout(&slow, &w.remote);
|
||||||
|
let bare = slow.join(".bare");
|
||||||
|
git(
|
||||||
|
&bare,
|
||||||
|
&["remote", "set-url", "origin", "ssh://hang.invalid/x.git"],
|
||||||
|
);
|
||||||
|
git(&bare, &["config", "core.sshCommand", "sleep 15; false"]);
|
||||||
|
let mut cfg = config(&w, "pca", 200, 60);
|
||||||
|
cfg.sync.workers = 2;
|
||||||
|
let started = Instant::now();
|
||||||
|
let d = Daemon::start(cfg, settings(&w, "pca")).unwrap();
|
||||||
|
fs::write(w.base.join("pca/g/repo/main/new.txt"), "x\n").unwrap();
|
||||||
|
wait_until("snapshot of the other repo pushed", 10, || {
|
||||||
|
!git(&w.remote, &["for-each-ref", "refs/sync/pca/"]).is_empty()
|
||||||
|
});
|
||||||
|
assert!(started.elapsed() < Duration::from_secs(12));
|
||||||
|
d.shutdown();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_repo_gets_a_pass_when_a_cycle_takes_longer_than_the_interval() {
|
||||||
|
let w = world("fair", &["pca"]);
|
||||||
|
// Four repos sorting before `g/repo` whose fetch takes 1.5 s each: with one worker a cycle
|
||||||
|
// takes ~6 s against a 1 s interval.
|
||||||
|
for n in ["a", "b", "c", "d"] {
|
||||||
|
let r = w.base.join(format!("pca/g/{n}"));
|
||||||
|
bare_layout(&r, &w.remote);
|
||||||
|
git(
|
||||||
|
&r.join(".bare"),
|
||||||
|
&[
|
||||||
|
"config",
|
||||||
|
"remote.origin.uploadpack",
|
||||||
|
"sleep 1.5; git-upload-pack",
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let mut cfg = config(&w, "pca", 200, 1);
|
||||||
|
cfg.sync.workers = 1;
|
||||||
|
let d = Daemon::start(cfg, settings(&w, "pca")).unwrap();
|
||||||
|
let sock = w.base.join("pca.sock");
|
||||||
|
let last = |s: &serde_json::Value, name: &str| {
|
||||||
|
s["repos"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.find(|r| r["path"].as_str().unwrap().ends_with(&format!("/g/{name}")))
|
||||||
|
.and_then(|r| r["last_sync"].as_u64())
|
||||||
|
};
|
||||||
|
// `repo` keeps getting passes: it is not starved by the slow ones (before, sorted dispatch
|
||||||
|
// gave every new cycle to `a`..`d` again and `repo` never ran).
|
||||||
|
let mut seen = Vec::new();
|
||||||
|
wait_until("two passes of the last repo", 45, || {
|
||||||
|
let t = last(&status(&sock), "repo");
|
||||||
|
if t.is_some() && seen.last() != Some(&t) {
|
||||||
|
seen.push(t);
|
||||||
|
}
|
||||||
|
seen.len() >= 2
|
||||||
|
});
|
||||||
|
d.shutdown();
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
use crate::http::Http;
|
use crate::http::Http;
|
||||||
use crate::{
|
use crate::{
|
||||||
Capabilities, Error, MirrorSpec, NewRepo, Provider, PullMirrorSpec, RemoteRepo, Result,
|
Capabilities, Error, MergedPull, MirrorSpec, NewRepo, Provider, PullMirrorSpec, RemoteRepo,
|
||||||
|
Result, same_repo,
|
||||||
};
|
};
|
||||||
use grove_core::config::ProviderKind;
|
use grove_core::config::ProviderKind;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
@@ -156,4 +157,24 @@ impl Provider for Gitea {
|
|||||||
Some(&body),
|
Some(&body),
|
||||||
)?))
|
)?))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn merged_pulls(&self, owner: &str, name: &str) -> Result<Vec<MergedPull>> {
|
||||||
|
let v = self.http.ok(
|
||||||
|
"GET",
|
||||||
|
&format!("/repos/{owner}/{name}/pulls?state=closed&sort=recentupdate&limit=50"),
|
||||||
|
None,
|
||||||
|
)?;
|
||||||
|
Ok(v.as_array()
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.filter(|p| p["merged"].as_bool() == Some(true) && same_repo(p))
|
||||||
|
.filter_map(|p| {
|
||||||
|
Some(MergedPull {
|
||||||
|
number: p["number"].as_u64()?,
|
||||||
|
head_ref: p["head"]["ref"].as_str()?.to_string(),
|
||||||
|
head_sha: p["head"]["sha"].as_str()?.to_string(),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
use crate::http::Http;
|
use crate::http::Http;
|
||||||
use crate::{
|
use crate::{
|
||||||
Capabilities, Error, MirrorSpec, NewRepo, Provider, PullMirrorSpec, RemoteRepo, Result,
|
Capabilities, Error, MergedPull, MirrorSpec, NewRepo, Provider, PullMirrorSpec, RemoteRepo,
|
||||||
|
Result, same_repo,
|
||||||
};
|
};
|
||||||
use grove_core::config::ProviderKind;
|
use grove_core::config::ProviderKind;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
@@ -138,4 +139,28 @@ impl Provider for GitHub {
|
|||||||
"GitHub cannot pull-mirror another forge",
|
"GitHub cannot pull-mirror another forge",
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn merged_pulls(&self, owner: &str, name: &str) -> Result<Vec<MergedPull>> {
|
||||||
|
let v = self.http.ok(
|
||||||
|
"GET",
|
||||||
|
&format!(
|
||||||
|
"/repos/{owner}/{name}/pulls?state=closed&sort=updated&direction=desc&per_page=100"
|
||||||
|
),
|
||||||
|
None,
|
||||||
|
)?;
|
||||||
|
Ok(v.as_array()
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.filter(|p| p["merged_at"].is_string() && same_repo(p))
|
||||||
|
.filter_map(pull)
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pull(p: &Value) -> Option<MergedPull> {
|
||||||
|
Some(MergedPull {
|
||||||
|
number: p["number"].as_u64()?,
|
||||||
|
head_ref: p["head"]["ref"].as_str()?.to_string(),
|
||||||
|
head_sha: p["head"]["sha"].as_str()?.to_string(),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
@@ -119,6 +119,25 @@ pub struct PullMirrorSpec {
|
|||||||
pub interval: String,
|
pub interval: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A pull request merged on the forge whose head branch is in the same repo.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct MergedPull {
|
||||||
|
pub number: u64,
|
||||||
|
pub head_ref: String,
|
||||||
|
pub head_sha: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Head repo of a pull request equals its base repo (fork PRs reuse branch names freely).
|
||||||
|
/// A head repo that was deleted reports `null`: not the same repo.
|
||||||
|
pub(crate) fn same_repo(pr: &serde_json::Value) -> bool {
|
||||||
|
let name = |side: &str| {
|
||||||
|
pr[side]["repo"]["full_name"]
|
||||||
|
.as_str()
|
||||||
|
.map(str::to_ascii_lowercase)
|
||||||
|
};
|
||||||
|
matches!((name("head"), name("base")), (Some(h), Some(b)) if h == b)
|
||||||
|
}
|
||||||
|
|
||||||
pub trait Provider: Send + Sync {
|
pub trait Provider: Send + Sync {
|
||||||
fn kind(&self) -> ProviderKind;
|
fn kind(&self) -> ProviderKind;
|
||||||
fn capabilities(&self) -> Capabilities;
|
fn capabilities(&self) -> Capabilities;
|
||||||
@@ -134,6 +153,33 @@ pub trait Provider: Send + Sync {
|
|||||||
fn configure_mirror(&self, owner: &str, repo: &str, spec: &MirrorSpec) -> Result<()>;
|
fn configure_mirror(&self, owner: &str, repo: &str, spec: &MirrorSpec) -> Result<()>;
|
||||||
/// Creates a pull mirror (see [`Capabilities::pull_mirror`]).
|
/// Creates a pull mirror (see [`Capabilities::pull_mirror`]).
|
||||||
fn create_pull_mirror(&self, spec: &PullMirrorSpec) -> Result<RemoteRepo>;
|
fn create_pull_mirror(&self, spec: &PullMirrorSpec) -> Result<RemoteRepo>;
|
||||||
|
/// The most recently updated closed pull requests (one page) that were merged, newest
|
||||||
|
/// first, leaving out those whose head is in a fork.
|
||||||
|
fn merged_pulls(&self, owner: &str, name: &str) -> Result<Vec<MergedPull>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`Provider::merged_pulls`] that also finds a repo transferred or renamed on the forge: `origin`
|
||||||
|
/// may still name the old place, which git and the repo endpoint follow by redirect but the
|
||||||
|
/// pulls endpoint does not. On failure the repo is looked up and, if its current owner/name
|
||||||
|
/// differ, its pulls are listed under those.
|
||||||
|
pub fn merged_pulls_following_moves(
|
||||||
|
p: &dyn Provider,
|
||||||
|
owner: &str,
|
||||||
|
name: &str,
|
||||||
|
) -> Result<Vec<MergedPull>> {
|
||||||
|
let err = match p.merged_pulls(owner, name) {
|
||||||
|
Ok(pulls) => return Ok(pulls),
|
||||||
|
Err(e) => e,
|
||||||
|
};
|
||||||
|
match p.get_repo(owner, name) {
|
||||||
|
Ok(r)
|
||||||
|
if !r.owner.is_empty()
|
||||||
|
&& !(r.owner.eq_ignore_ascii_case(owner) && r.name.eq_ignore_ascii_case(name)) =>
|
||||||
|
{
|
||||||
|
p.merged_pulls(&r.owner, &r.name)
|
||||||
|
}
|
||||||
|
_ => Err(err),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds the provider described by `cfg`, using `token`.
|
/// Builds the provider described by `cfg`, using `token`.
|
||||||
|
|||||||
@@ -31,10 +31,19 @@ pub fn get(provider_id: &str) -> Result<String> {
|
|||||||
return Ok(t.trim().to_string());
|
return Ok(t.trim().to_string());
|
||||||
}
|
}
|
||||||
let e = keyring::Entry::new(SERVICE, provider_id).map_err(|e| Error::Other(e.to_string()))?;
|
let e = keyring::Entry::new(SERVICE, provider_id).map_err(|e| Error::Other(e.to_string()))?;
|
||||||
match e.get_password() {
|
// A locked keyring may wait on an unlock dialog: never block the caller for longer than the
|
||||||
Ok(t) => Ok(t),
|
// forge CLIs get (the thread is left behind if the Secret Service never answers).
|
||||||
Err(keyring::Error::NoEntry) => Err(Error::NoToken(provider_id.into())),
|
let (tx, rx) = std::sync::mpsc::channel();
|
||||||
Err(e) => Err(Error::Other(format!("secret service: {e}"))),
|
std::thread::spawn(move || {
|
||||||
|
let _ = tx.send(e.get_password());
|
||||||
|
});
|
||||||
|
match rx.recv_timeout(CLI_TIMEOUT) {
|
||||||
|
Ok(Ok(t)) => Ok(t),
|
||||||
|
Ok(Err(keyring::Error::NoEntry)) => Err(Error::NoToken(provider_id.into())),
|
||||||
|
Ok(Err(e)) => Err(Error::Other(format!("secret service: {e}"))),
|
||||||
|
Err(_) => Err(Error::Other(
|
||||||
|
"secret service did not answer in time (locked keyring?)".into(),
|
||||||
|
)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -481,3 +481,84 @@ fn git_url_follows_the_protocol_and_needs_an_ssh_url_for_ssh() {
|
|||||||
);
|
);
|
||||||
assert!(r[1].git_url(Protocol::Ssh).is_err());
|
assert!(r[1].git_url(Protocol::Ssh).is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn merged_pulls_keep_only_merged_same_repo_heads() {
|
||||||
|
// Merged, closed without merging, merged from a fork, merged from a deleted fork.
|
||||||
|
let gitea = r#"[
|
||||||
|
{"number":3,"merged":true,"head":{"ref":"feat/a","sha":"aaa","repo":{"full_name":"O/r"}},"base":{"repo":{"full_name":"o/r"}}},
|
||||||
|
{"number":2,"merged":false,"head":{"ref":"b","sha":"bbb","repo":{"full_name":"o/r"}},"base":{"repo":{"full_name":"o/r"}}},
|
||||||
|
{"number":1,"merged":true,"head":{"ref":"c","sha":"ccc","repo":{"full_name":"x/r"}},"base":{"repo":{"full_name":"o/r"}}},
|
||||||
|
{"number":0,"merged":true,"head":{"ref":"d","sha":"ddd","repo":null},"base":{"repo":{"full_name":"o/r"}}}
|
||||||
|
]"#;
|
||||||
|
let (url, rx) = mock(vec![(200, gitea)]);
|
||||||
|
let pulls = Gitea::new(ProviderKind::Forgejo, &url, "t".into())
|
||||||
|
.merged_pulls("o", "r")
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
rx.recv()
|
||||||
|
.unwrap()
|
||||||
|
.starts_with("GET /api/v1/repos/o/r/pulls?state=closed&sort=recentupdate&limit=50 ")
|
||||||
|
);
|
||||||
|
assert_eq!(pulls.len(), 1);
|
||||||
|
assert_eq!(
|
||||||
|
(
|
||||||
|
pulls[0].number,
|
||||||
|
pulls[0].head_ref.as_str(),
|
||||||
|
pulls[0].head_sha.as_str()
|
||||||
|
),
|
||||||
|
(3, "feat/a", "aaa")
|
||||||
|
);
|
||||||
|
|
||||||
|
let github = r#"[
|
||||||
|
{"number":9,"merged_at":"2026-01-01T00:00:00Z","head":{"ref":"x","sha":"999","repo":{"full_name":"o/r"}},"base":{"repo":{"full_name":"o/r"}}},
|
||||||
|
{"number":8,"merged_at":null,"head":{"ref":"y","sha":"888","repo":{"full_name":"o/r"}},"base":{"repo":{"full_name":"o/r"}}}
|
||||||
|
]"#;
|
||||||
|
let (url, rx) = mock(vec![(200, github), (404, r#"{"message":"Not Found"}"#)]);
|
||||||
|
let gh = GitHub::new(&url, "t".into());
|
||||||
|
let pulls = gh.merged_pulls("o", "r").unwrap();
|
||||||
|
assert!(rx.recv().unwrap().starts_with(
|
||||||
|
"GET /repos/o/r/pulls?state=closed&sort=updated&direction=desc&per_page=100 "
|
||||||
|
));
|
||||||
|
assert_eq!(pulls.iter().map(|p| p.number).collect::<Vec<_>>(), vec![9]);
|
||||||
|
assert!(matches!(
|
||||||
|
gh.merged_pulls("o", "gone").unwrap_err(),
|
||||||
|
Error::Api { status: 404, .. }
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn merged_pulls_follow_a_transferred_repo() {
|
||||||
|
let pulls = r#"[{"number":4,"merged":true,"head":{"ref":"f","sha":"fff","repo":{"full_name":"Org/r"}},"base":{"repo":{"full_name":"Org/r"}}}]"#;
|
||||||
|
let (url, rx) = mock(vec![
|
||||||
|
(404, r#"{"message":"not found"}"#),
|
||||||
|
(
|
||||||
|
200,
|
||||||
|
r#"{"name":"r","owner":{"login":"Org"},"private":true}"#,
|
||||||
|
),
|
||||||
|
(200, pulls),
|
||||||
|
]);
|
||||||
|
let g = Gitea::new(ProviderKind::Gitea, &url, "t".into());
|
||||||
|
let got = grove_providers::merged_pulls_following_moves(&g, "me", "r").unwrap();
|
||||||
|
assert_eq!(got.iter().map(|p| p.number).collect::<Vec<_>>(), vec![4]);
|
||||||
|
let asked: Vec<String> = rx
|
||||||
|
.try_iter()
|
||||||
|
.map(|l| l.lines().next().unwrap().to_string())
|
||||||
|
.collect();
|
||||||
|
assert!(asked[1].starts_with("GET /api/v1/repos/me/r "), "{asked:?}");
|
||||||
|
assert!(
|
||||||
|
asked[2].starts_with("GET /api/v1/repos/Org/r/pulls?"),
|
||||||
|
"{asked:?}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Not moved: the original error stands.
|
||||||
|
let (url, _rx) = mock(vec![
|
||||||
|
(404, r#"{"message":"not found"}"#),
|
||||||
|
(404, r#"{"message":"not found"}"#),
|
||||||
|
]);
|
||||||
|
let g = Gitea::new(ProviderKind::Gitea, &url, "t".into());
|
||||||
|
assert!(matches!(
|
||||||
|
grove_providers::merged_pulls_following_moves(&g, "me", "gone").unwrap_err(),
|
||||||
|
Error::Api { status: 404, .. }
|
||||||
|
));
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ use grove_core::config::{Config, ProviderKind};
|
|||||||
use grove_core::git::Git;
|
use grove_core::git::Git;
|
||||||
use grove_core::inspect::{state, worktrees};
|
use grove_core::inspect::{state, worktrees};
|
||||||
use grove_core::migrate::migrate;
|
use grove_core::migrate::migrate;
|
||||||
|
use grove_core::prune::{Pruned, merged_how};
|
||||||
use grove_core::receive::{Applied, Archived, Received};
|
use grove_core::receive::{Applied, Archived, Received};
|
||||||
use grove_core::resolve::{Choice, resolve};
|
use grove_core::resolve::{Choice, resolve};
|
||||||
use grove_core::snapshot::{Outcome, take};
|
use grove_core::snapshot::{Outcome, take};
|
||||||
@@ -345,6 +346,21 @@ fn main() -> Result<()> {
|
|||||||
Cmd::Sync { path, offline } => {
|
Cmd::Sync { path, offline } => {
|
||||||
let cfg = load_config(&cli.config)?;
|
let cfg = load_config(&cli.config)?;
|
||||||
grove_core::snapshot::set_max_file_bytes(cfg.sync.max_file_mb * 1024 * 1024);
|
grove_core::snapshot::set_max_file_bytes(cfg.sync.max_file_mb * 1024 * 1024);
|
||||||
|
// Merged pull requests, for pruning (bare layout only; best effort).
|
||||||
|
let merged = if *offline || !cfg.sync.prune_merged || !path.join(".bare").is_dir() {
|
||||||
|
Vec::new()
|
||||||
|
} else {
|
||||||
|
grove_daemon::merged::lookup(
|
||||||
|
&cfg,
|
||||||
|
path,
|
||||||
|
"origin",
|
||||||
|
&grove_daemon::visibility::RealForge,
|
||||||
|
)
|
||||||
|
.unwrap_or_else(|e| {
|
||||||
|
eprintln!("grove: cannot list merged pull requests: {e}");
|
||||||
|
Vec::new()
|
||||||
|
})
|
||||||
|
};
|
||||||
let rep = sync_repo(
|
let rep = sync_repo(
|
||||||
path,
|
path,
|
||||||
&Options {
|
&Options {
|
||||||
@@ -359,6 +375,10 @@ fn main() -> Result<()> {
|
|||||||
.and_then(|g| cfg.groups.iter().find(|x| x.name == g))
|
.and_then(|g| cfg.groups.iter().find(|x| x.name == g))
|
||||||
.is_none_or(|g| g.auto_materialize),
|
.is_none_or(|g| g.auto_materialize),
|
||||||
push_snapshots: true,
|
push_snapshots: true,
|
||||||
|
merged,
|
||||||
|
disposable: cfg.sync.prune_disposable.clone(),
|
||||||
|
prune: cfg.sync.prune_merged,
|
||||||
|
protected: cfg.sync.protected_branches(),
|
||||||
},
|
},
|
||||||
)?;
|
)?;
|
||||||
print_report(&rep)
|
print_report(&rep)
|
||||||
@@ -505,6 +525,23 @@ fn print_report(rep: &SyncReport) -> Result<()> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
for p in &rep.pruned {
|
||||||
|
match p {
|
||||||
|
Pruned::Removed {
|
||||||
|
branch,
|
||||||
|
pr,
|
||||||
|
path,
|
||||||
|
backup_ref,
|
||||||
|
} => println!(
|
||||||
|
"pruned {branch}: {}, removed {} (backup {backup_ref})",
|
||||||
|
merged_how(*pr),
|
||||||
|
path.display()
|
||||||
|
),
|
||||||
|
Pruned::Kept { branch, pr, why } => {
|
||||||
|
println!("kept {branch}: {} but {why}", merged_how(*pr))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
for w in &rep.worktrees {
|
for w in &rep.worktrees {
|
||||||
let branch = w.branch.as_deref().unwrap_or("(detached)");
|
let branch = w.branch.as_deref().unwrap_or("(detached)");
|
||||||
let mut notes = Vec::new();
|
let mut notes = Vec::new();
|
||||||
|
|||||||
@@ -95,14 +95,8 @@ pub fn connect(cfg: &Config, id: &str) -> Result<Forge> {
|
|||||||
/// Git environment for SSH remotes: the user's keys/agent authenticate and nothing prompts.
|
/// Git environment for SSH remotes: the user's keys/agent authenticate and nothing prompts.
|
||||||
/// `BatchMode` is only forced when the user has no ssh command of their own.
|
/// `BatchMode` is only forced when the user has no ssh command of their own.
|
||||||
fn ssh_env() -> Vec<(String, String)> {
|
fn ssh_env() -> Vec<(String, String)> {
|
||||||
let mut env = vec![("GIT_TERMINAL_PROMPT".to_string(), "0".to_string())];
|
let mut env = grove_core::git::noninteractive_env();
|
||||||
let custom = std::env::var_os("GIT_SSH_COMMAND").is_some()
|
if !grove_core::git::has_custom_ssh() {
|
||||||
|| std::env::var_os("GIT_SSH").is_some()
|
|
||||||
|| std::process::Command::new("git")
|
|
||||||
.args(["config", "--get", "core.sshCommand"])
|
|
||||||
.output()
|
|
||||||
.is_ok_and(|o| o.status.success() && !o.stdout.is_empty());
|
|
||||||
if !custom {
|
|
||||||
env.push(("GIT_SSH_COMMAND".into(), "ssh -o BatchMode=yes".into()));
|
env.push(("GIT_SSH_COMMAND".into(), "ssh -o BatchMode=yes".into()));
|
||||||
}
|
}
|
||||||
env
|
env
|
||||||
|
|||||||
@@ -5,3 +5,7 @@
|
|||||||
3. Config: TOML for user intent (implemented); runtime state storage still open.
|
3. Config: TOML for user intent (implemented); runtime state storage still open.
|
||||||
4. License: MIT (decided).
|
4. License: MIT (decided).
|
||||||
5. Final name: Grove (decided; binary `grove`, crates `grove-core` and `grove`).
|
5. Final name: Grove (decided; binary `grove`, crates `grove-core` and `grove`).
|
||||||
|
6. Open: `groved` under systemd gets `PATH=/usr/local/bin:/usr/bin:/bin`, so a `tea`/`gh` in `~/.local/bin` is not found and the token lookup fails. Options: ship `Environment=PATH=%h/.local/bin:...` in `contrib/groved.service`, or resolve the helpers by absolute path (`~/.local/bin`, then `PATH`). Workaround in use: a user drop-in (see `two-pc-run.md`).
|
||||||
|
7. Open: `grove add` refuses `extensions.worktreeConfig = true` even when no `config.worktree` exists. Claude Code worktrees leave that flag behind. Options: accept it when no per-worktree config file exists (and sparse checkout is off), or keep refusing and print the exact `git config --unset` hint.
|
||||||
|
8. Merged worktrees are pruned (`prune-merged.md`), but the PR's head branch is left on the forge and this machine's `refs/sync/<machine>/<branch>` snapshot ref stays there too. Open: should grove delete either once the PR is merged (the forge's "delete branch after merge" covers the first)?
|
||||||
|
9. Open: a branch recreated under the name of a fast-forward-merged PR before the default branch moves has the PR head as tip and is pruned at once if clean (nothing is lost; a backup ref is kept). Options: accept it, or require the worktree to be older than the merge.
|
||||||
+13
-2
@@ -17,8 +17,19 @@ is `grove_core::sync::sync_repo`, the same code the CLI runs. The daemon only de
|
|||||||
cannot starve snapshots.
|
cannot starve snapshots.
|
||||||
- **Periodic pass**: every `fetch_interval_s` all repos get a full pass (fetch, receive, apply
|
- **Periodic pass**: every `fetch_interval_s` all repos get a full pass (fetch, receive, apply
|
||||||
snapshots, materialize/archive). Also what catches missed events.
|
snapshots, materialize/archive). Also what catches missed events.
|
||||||
- **One worker thread**: passes never overlap. Events that arrive during a pass queue another pass;
|
- **Worker pool**: the loop thread only schedules; `sync.workers` threads (default 4, 1 to 32) run
|
||||||
it finds nothing to do and ends the chain.
|
the passes, so a slow or hanging fetch of one repo no longer holds up the others. A repo never
|
||||||
|
has two passes at once: one that becomes due while its pass runs is dispatched when it ends.
|
||||||
|
Events that arrive during a pass queue another pass; it finds nothing to do and ends the chain.
|
||||||
|
Due repos are dispatched longest-waiting first, and a full pass never moves an earlier due
|
||||||
|
time later, so when a cycle takes longer than `fetch_interval_s` every repo still gets its
|
||||||
|
turn (dispatching by path starved the repos late in the alphabet).
|
||||||
|
Passes are handed out only to idle workers, so the rest stay due: pause stops them, and whether
|
||||||
|
a pass runs offline (backoff) is decided when it starts. A `sync` request for a repo whose pass
|
||||||
|
is running is not undone by that pass failing. A panicking pass is logged and counts as a
|
||||||
|
failure. Rediscovery does not drop or flag (stalled) a repo while its pass runs.
|
||||||
|
The visibility and merged-PR caches are shared and never locked across a forge request.
|
||||||
|
Shutdown and pause let running passes finish. `workers = 1` is the old sequential behaviour.
|
||||||
- **Failures** (network, auth, git errors) back off exponentially per repo: 10 s, 20 s, ... capped at
|
- **Failures** (network, auth, git errors) back off exponentially per repo: 10 s, 20 s, ... capped at
|
||||||
5 min, and are logged as `error`. `sync` over IPC clears the backoff. While backing off, changes
|
5 min, and are logged as `error`. `sync` over IPC clears the backoff. While backing off, changes
|
||||||
are still snapshotted locally (an offline pass); only the network is retried after the backoff.
|
are still snapshotted locally (an offline pass); only the network is retried after the backoff.
|
||||||
|
|||||||
@@ -118,6 +118,39 @@ 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 (also Gitea's SSH "Cannot find repository"). 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
|
||||||
|
`STALE_AFTER_SECS`, 6 h, between two confirmations starts over: a pass over many repos can take
|
||||||
|
longer than 20 min, so a shorter gap never let a deletion be confirmed). 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
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
# Pruning merged worktrees
|
||||||
|
|
||||||
|
Worktrees of branches that were pushed, reviewed in a pull request and merged used to stay
|
||||||
|
forever: `archive_gone` only removes a worktree when its remote branch is deleted, the forge
|
||||||
|
often keeps the head branch, squash and rebase merges leave no ancestry for git to see, and a
|
||||||
|
Rust/Node worktree always holds ignored build output that kept it "dirty". The daemon now asks
|
||||||
|
the forge which pull requests were merged and removes those worktrees itself. Branches merged
|
||||||
|
into the default branch without a pull request (merged locally and pushed) are removed too.
|
||||||
|
|
||||||
|
## Config
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[sync]
|
||||||
|
prune_merged = true # default
|
||||||
|
prune_disposable = ["target", "node_modules", ".venv", "venv", "__pycache__", ".pytest_cache",
|
||||||
|
".mypy_cache", ".ruff_cache", ".tox", ".gradle", ".next", ".nuxt", ".svelte-kit", ".turbo",
|
||||||
|
".parcel-cache", "dist", "build", "out", "coverage", ".cache"] # default
|
||||||
|
prune_protected = [] # default; extra branch names never pruned
|
||||||
|
```
|
||||||
|
|
||||||
|
- `prune_merged = false` turns the feature off.
|
||||||
|
- `prune_protected`: extra branch names (exact, no globs) never pruned nor kept from being
|
||||||
|
materialized, added to the built-in `main`, `master`, `development`, `develop`, `dev`,
|
||||||
|
`staging`, `production` (a `development` -> `main` PR has `development` as its head). The
|
||||||
|
default branch (`.bare`'s HEAD) never is either. Other long-lived branches (`release/1.2`,
|
||||||
|
`hotfix/x`) merged back with no new commits are pruned like any other: list them here.
|
||||||
|
- `prune_disposable`: names (not paths, not globs) of ignored files/directories that are
|
||||||
|
regenerable and may go with a pruned worktree. Entries must be plain names.
|
||||||
|
|
||||||
|
## What counts as merged
|
||||||
|
|
||||||
|
`Provider::merged_pulls(owner, repo)` lists one page of the most recently updated closed pull
|
||||||
|
requests (GitHub: 100, `merged_at` set; Gitea/Forgejo: 50, `merged: true`), keeping only those
|
||||||
|
whose head repo is the base repo: fork PRs reuse branch names freely. The repo is found from
|
||||||
|
`origin`'s fetch URL, matched to a configured provider like the visibility check (`phase6.md`),
|
||||||
|
with the token from `token::resolve`. When that fails, the repo is looked up and, if the forge
|
||||||
|
reports another owner/name (transferred or renamed: git and the repo endpoint follow the old
|
||||||
|
`origin` by redirect, the pulls endpoint does not), its pulls are listed under the current one.
|
||||||
|
|
||||||
|
Without a pull request, a branch counts as merged when its tip was pushed
|
||||||
|
(`origin/<branch>` points at it), is a strict ancestor of `origin/<default>` and is not on its
|
||||||
|
first-parent history, i.e. a merge commit brought it in. This needs no forge. A branch created
|
||||||
|
from the default branch with no commits of its own is on that history and is never pruned this
|
||||||
|
way; neither is a fast-forward merge (only the PR path catches those).
|
||||||
|
|
||||||
|
## When a worktree is removed
|
||||||
|
|
||||||
|
All of these must hold (`grove_core::prune::prune_merged`):
|
||||||
|
|
||||||
|
1. The repo is bare layout, the fetch of this pass worked, and the pass is not offline.
|
||||||
|
2. The worktree is on a branch that is not `.bare`'s HEAD (the default branch) nor in
|
||||||
|
`prune_protected`, and it lives
|
||||||
|
inside the repo directory (`root/<group>/<repo>/...`, so nested ones such as
|
||||||
|
`main/.claude/worktrees/x` count). Linked worktrees elsewhere are the user's and are never
|
||||||
|
touched.
|
||||||
|
3. A merged PR has that branch as head and its head commit equals the local tip, or contains it
|
||||||
|
(the PR got more commits from another machine before the merge); or, without a PR, the
|
||||||
|
ancestry rule above holds.
|
||||||
|
4. No local work: no staged, modified or untracked file, no git operation in progress
|
||||||
|
(`index.lock`, rebase, merge, cherry-pick, revert, bisect), and no ignored entry whose name
|
||||||
|
is not in `prune_disposable` (`.env` keeps it, `target/` does not).
|
||||||
|
|
||||||
|
Then the tip is saved under `refs/sync-backup/<machine>/<stamp>/merged/<branch>`, the worktree
|
||||||
|
is removed (`git worktree remove --force`, needed for the disposable ignored files only) and the
|
||||||
|
local branch is deleted. Nothing on the forge changes: the remote branch, if any, stays.
|
||||||
|
|
||||||
|
A merged worktree with local work is kept and reported, once per change, as `prune_kept`
|
||||||
|
(`feat/x: merged in PR #12 but kept: ignored files: .env`).
|
||||||
|
|
||||||
|
## Not brought back by `auto_materialize`
|
||||||
|
|
||||||
|
`materialize` creates a worktree for every remote branch without one, so a pruned branch whose
|
||||||
|
head was not deleted on the forge would come back on the next pass. It now skips a remote
|
||||||
|
branch whose tip is the head of a merged PR or the tip this machine pruned (its `merged/` backup
|
||||||
|
ref), so this holds also offline or when the forge cannot be asked. New commits pushed to the
|
||||||
|
branch after the merge are new work: the worktree is materialized again.
|
||||||
|
|
||||||
|
## Daemon
|
||||||
|
|
||||||
|
- The forge is asked at most every 5 minutes per repo, and only when the repo has a worktree
|
||||||
|
on a non-default branch. The answer is in memory only.
|
||||||
|
- A failed lookup keeps the last answer and is logged once as `prune_lookup_failed` (until the
|
||||||
|
error changes).
|
||||||
|
- Offline passes (backoff) prune nothing, but still use the last answer to keep pruned branches
|
||||||
|
from being materialized.
|
||||||
|
- The ancestry rule runs on every online pass, also when the forge lookup fails.
|
||||||
|
- Activity log: `pruned_merged` (removed, with the PR or "merged into the default branch", path
|
||||||
|
and backup ref) and `prune_kept`.
|
||||||
|
|
||||||
|
`grove sync <path>` does the same in one shot (no cache) and prints `pruned ...` / `kept ...`
|
||||||
|
lines; a failed lookup is a warning, and only the ancestry rule applies.
|
||||||
|
|
||||||
|
## Validation
|
||||||
|
|
||||||
|
- `grove-core/tests/prune.rs`: squash merge with the head branch kept on the remote (pruned with
|
||||||
|
`target/` present, backup ref, not re-materialized with or without a forge answer, comes back
|
||||||
|
after a new commit), local work (untracked file, non-disposable ignored file, local commit)
|
||||||
|
keeps the worktree, an older tip contained in the PR head is pruned, the default branch and a
|
||||||
|
linked worktree outside the repo are never touched.
|
||||||
|
- `grove-providers/tests/api.rs`: request shape on both forges, only merged same-repo PRs kept
|
||||||
|
(fork and deleted-fork heads left out), API errors surface.
|
||||||
|
- `grove-daemon` `merged` unit tests: TTL cache, last answer kept on failure, error and kept
|
||||||
|
notes logged once.
|
||||||
|
- Config: defaults and validation of `prune_disposable`.
|
||||||
|
|
||||||
|
## Not verified
|
||||||
|
|
||||||
|
- Against a real GitHub or Gitea (mock-tested only).
|
||||||
|
- Only the first page of closed PRs is read: a branch merged long ago in a busy repo (more than
|
||||||
|
100 / 50 PRs closed since) is not found. `grove sync` on it does not help either; remove it by
|
||||||
|
hand.
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# Real two-PC run
|
||||||
|
|
||||||
|
First real run on two machines, 16/11/2026: `Dasemu-LT` (laptop, already running Grove) and
|
||||||
|
`Dasemu-PC` (desktop, Fedora 44, KDE Plasma / Wayland, installed fresh from `development` at
|
||||||
|
`e6030f7`). Real forges: Gitea `git.zenvairo.es` (SSH on port 2222) and github.com, both with
|
||||||
|
`protocol = "ssh"`.
|
||||||
|
|
||||||
|
## Result
|
||||||
|
|
||||||
|
Passed. An uncommitted file in a private test repo on `Dasemu-PC` was snapshotted by the daemon
|
||||||
|
and pushed as `refs/sync/Dasemu-PC/main` (snapshot commit on top of `main`, containing only the
|
||||||
|
untracked file). On `Dasemu-LT`, after `grove import Darío <test repo>` and one daemon pass, the
|
||||||
|
snapshot showed up as `refs/sync-remote/Dasemu-PC/main`. The other direction was already visible
|
||||||
|
on real repos: `Academia-LMS` carries both `refs/sync/Dasemu-LT/feat/student-portal` and
|
||||||
|
`refs/sync/Dasemu-PC/feat/student-portal`. The throwaway repo was deleted from Gitea afterwards.
|
||||||
|
|
||||||
|
Notes:
|
||||||
|
|
||||||
|
- Right after `grove import`, the clone has no `refs/sync-remote/*` yet; they arrive with the
|
||||||
|
daemon's first pass over the new repo (up to `fetch_interval_s`, or `grove daemon sync PATH`).
|
||||||
|
- A repo created while the daemon runs is picked up (`repo_added`), but its worktree states only
|
||||||
|
appear after its first pass.
|
||||||
|
|
||||||
|
## Install on the second machine
|
||||||
|
|
||||||
|
`cargo test` passed; `grove`, `groved` and `grove-gui` installed with `cargo install --root ~/.local`.
|
||||||
|
`grove doctor` found both tokens (tea, gh). Migration of the existing `~/Hacking`:
|
||||||
|
|
||||||
|
- 14 plain clones migrated with `grove add`; 9 of them had a read-only Gitea pull mirror as
|
||||||
|
`origin` and were switched to their GitHub source (the `e6030f7` fix), Grove itself included.
|
||||||
|
- 19 missing repos cloned with `grove import`; 4 unversioned folders turned into repos with
|
||||||
|
`grove new` (2 public on GitHub with a Gitea mirror, 2 private on Gitea).
|
||||||
|
- First daemon pass: no `diverged`, 8 `dirty`, 2 `ahead`; 36 public repos report
|
||||||
|
`snapshots withheld` as intended.
|
||||||
|
|
||||||
|
## Problems found
|
||||||
|
|
||||||
|
1. **systemd PATH.** The user unit runs with `PATH=/usr/local/bin:/usr/bin:/bin`. `tea` lived in
|
||||||
|
`~/.local/bin`, so under systemd `groved` found no Gitea token (`grove doctor` run with that
|
||||||
|
PATH: `no token for provider "gitea"`). Worked around with a drop-in
|
||||||
|
`~/.config/systemd/user/groved.service.d/path.conf` setting
|
||||||
|
`Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin`. See `DECISIONS.md` (6).
|
||||||
|
2. **Leftover `extensions.worktreeConfig`.** Claude Code worktrees set
|
||||||
|
`extensions.worktreeConfig = true`; it stays after the worktrees are removed. `grove add`
|
||||||
|
refused 12 such clones ("sparse checkout / per-worktree config is not supported yet") although
|
||||||
|
none had a `config.worktree` file. Unsetting the extension (only when no `config.worktree`
|
||||||
|
exists and sparse checkout is off) let them migrate. See `DECISIONS.md` (7).
|
||||||
|
3. **Clones with a dirty linked worktree** still cannot be migrated (2 repos left as plain clones).
|
||||||
|
4. **Repos deleted on the forge after import** (2 on Gitea) make the daemon log a fetch error on
|
||||||
|
every pass. `development` now moves such repos to `Purged/` (PR #4); not part of this install.
|
||||||
Reference in new issue
Block a user