mirror of
https://github.com/Dasemu/Grove.git
synced 2026-11-26 07:16:11 +00:00
Merge remote-tracking branch 'origin/feat/daemon-scope' into feat/native-gui
This commit is contained in:
commit
23b7970644
26 files changed
+2297
-108
No files matched your search
@@ -25,6 +25,7 @@ user's branch or index.
|
||||
- Dependencies: serde+toml, clap+anyhow, notify+serde_json, ureq, keyring, age, slint (GUI, `winit` + software renderer) and ksni (tray), approved. Ask before adding more.
|
||||
- Everything in the repo is English. Open questions go to `docs/DECISIONS.md`.
|
||||
- Never destroy local work; divergence is surfaced, never auto-merged.
|
||||
- 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
|
||||
- Remote: Gitea `git.zenvairo.es`, owner `dasemu` (section `Darío`), CLI `tea`. SSH (port 22)
|
||||
|
||||
Generated
+1
@@ -2085,6 +2085,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"grove-core",
|
||||
"grove-providers",
|
||||
"notify",
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
@@ -62,6 +62,9 @@ pub struct Group {
|
||||
pub layout: Layout,
|
||||
#[serde(default = "yes")]
|
||||
pub auto_materialize: bool,
|
||||
/// Overrides `sync.snapshots` for this group.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub snapshots: Option<SnapshotPolicy>,
|
||||
/// Account or organisation that owns the group's repos, per provider id. A provider not
|
||||
/// listed here uses the authenticated user.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
@@ -72,6 +75,20 @@ pub struct Group {
|
||||
pub public: Option<Route>,
|
||||
}
|
||||
|
||||
/// Whether the daemon pushes WIP snapshots (`refs/sync/<machine>/<branch>`) of a repo.
|
||||
/// Snapshots contain uncommitted work, so they must not land in public repos.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum SnapshotPolicy {
|
||||
/// Push only when the forge confirms the repo is private (unknown counts as public).
|
||||
#[default]
|
||||
PrivateOnly,
|
||||
/// Push for every repo, public ones included.
|
||||
All,
|
||||
/// Never push snapshots.
|
||||
None,
|
||||
}
|
||||
|
||||
/// A primary forge plus the forges it is mirrored to.
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
|
||||
pub struct Route {
|
||||
@@ -109,6 +126,9 @@ pub struct Sync {
|
||||
/// Changed files larger than this many MiB are not snapshotted (0 = no limit).
|
||||
#[serde(default = "default_max_file_mb")]
|
||||
pub max_file_mb: u64,
|
||||
/// Default snapshot push policy; a group can override it.
|
||||
#[serde(default)]
|
||||
pub snapshots: SnapshotPolicy,
|
||||
}
|
||||
|
||||
impl Default for Sync {
|
||||
@@ -118,6 +138,7 @@ impl Default for Sync {
|
||||
fetch_interval_s: default_fetch(),
|
||||
ignore_extra: Vec::new(),
|
||||
max_file_mb: default_max_file_mb(),
|
||||
snapshots: SnapshotPolicy::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -201,6 +222,15 @@ impl Config {
|
||||
Some(base.join("grove"))
|
||||
}
|
||||
|
||||
/// The snapshot policy of the group named `group`, falling back to `sync.snapshots`.
|
||||
pub fn snapshot_policy(&self, group: &str) -> SnapshotPolicy {
|
||||
self.groups
|
||||
.iter()
|
||||
.find(|g| g.name == group)
|
||||
.and_then(|g| g.snapshots)
|
||||
.unwrap_or(self.sync.snapshots)
|
||||
}
|
||||
|
||||
/// `root.path` with a leading `~` expanded.
|
||||
pub fn root_path(&self) -> PathBuf {
|
||||
expand_home(&self.root.path)
|
||||
@@ -220,6 +250,13 @@ impl Config {
|
||||
));
|
||||
}
|
||||
for g in &self.groups {
|
||||
// Group names are directory names under the root.
|
||||
if g.name.is_empty() || g.name.starts_with('.') || g.name.contains(['/', '\\']) {
|
||||
return bad(format!(
|
||||
"group name {:?} must be a plain directory name",
|
||||
g.name
|
||||
));
|
||||
}
|
||||
let mut routes = vec![("", g.route(true))];
|
||||
if let Some(p) = &g.public {
|
||||
routes.push(("public.", p.clone()));
|
||||
@@ -346,6 +383,41 @@ name = "grove-config"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_policy_defaults_to_private_only_and_groups_override() {
|
||||
let c = Config::parse(FULL).unwrap();
|
||||
assert_eq!(c.sync.snapshots, SnapshotPolicy::PrivateOnly);
|
||||
assert_eq!(c.snapshot_policy("work"), SnapshotPolicy::PrivateOnly);
|
||||
assert_eq!(c.snapshot_policy("unknown"), SnapshotPolicy::PrivateOnly);
|
||||
let t = FULL
|
||||
.replace(
|
||||
"fetch_interval_s = 30",
|
||||
"fetch_interval_s = 30\nsnapshots = \"none\"",
|
||||
)
|
||||
.replace(
|
||||
"mirror_to = [\"github\"]",
|
||||
"mirror_to = [\"github\"]\nsnapshots = \"all\"",
|
||||
);
|
||||
let c = Config::parse(&t).unwrap();
|
||||
assert_eq!(c.snapshot_policy("work"), SnapshotPolicy::All);
|
||||
assert_eq!(c.snapshot_policy("other"), SnapshotPolicy::None);
|
||||
let again = toml::to_string_pretty(&c).unwrap();
|
||||
assert_eq!(Config::parse(&again).unwrap(), c);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_unknown_snapshot_policy_and_bad_group_names() {
|
||||
let bad = FULL.replace("fetch_interval_s = 30", "snapshots = \"public\"");
|
||||
assert!(matches!(Config::parse(&bad), Err(ConfigError::Parse(_))));
|
||||
for n in ["a/b", ".hidden", ""] {
|
||||
let t = FULL.replace("name = \"work\"", &format!("name = \"{n}\""));
|
||||
assert!(
|
||||
matches!(Config::parse(&t), Err(ConfigError::Invalid(_))),
|
||||
"{n:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const ROUTED: &str = r#"
|
||||
[machine]
|
||||
name = "a"
|
||||
|
||||
@@ -63,7 +63,8 @@ impl Git {
|
||||
|
||||
fn command<S: AsRef<OsStr>>(&self, args: &[S]) -> Command {
|
||||
let mut cmd = Command::new("git");
|
||||
cmd.current_dir(&self.dir).args(args);
|
||||
// Fixed locale: callers parse git's output and messages.
|
||||
cmd.current_dir(&self.dir).args(args).env("LC_ALL", "C");
|
||||
for (k, v) in &self.envs {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,11 @@
|
||||
//! Safety: a full tar backup and a backup ref are taken first; the observable state
|
||||
//! (`status --ignored`, stashes, refs) is compared before and after; any failure after
|
||||
//! the first modification triggers a rollback to the original layout.
|
||||
//!
|
||||
//! Linked worktrees (`git worktree add`) are supported: the ones nested inside the repo move
|
||||
//! together with the main checkout, the ones outside stay where they are, and the two link files
|
||||
//! of each (`<wt>/.git` and `.bare/worktrees/<id>/gitdir`) are rewritten to the new locations.
|
||||
//! Locked, missing/prunable and mid-operation linked worktrees are refused.
|
||||
|
||||
use crate::git::{Git, GitError};
|
||||
use crate::layout::dir_name;
|
||||
@@ -73,6 +78,41 @@ pub struct Report {
|
||||
pub branch: String,
|
||||
pub backup_tar: PathBuf,
|
||||
pub backup_ref: String,
|
||||
/// Linked worktrees that existed before the migration (they were kept usable).
|
||||
pub linked: Vec<LinkedReport>,
|
||||
/// Extra tar backups, one per linked worktree outside the repo directory.
|
||||
pub linked_backups: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct LinkedReport {
|
||||
/// Location before the migration.
|
||||
pub old_path: PathBuf,
|
||||
/// Location now (differs from `old_path` only for worktrees nested inside the repo).
|
||||
pub path: PathBuf,
|
||||
/// `None` for a detached HEAD.
|
||||
pub branch: Option<String>,
|
||||
}
|
||||
|
||||
/// A linked worktree found by the pre-flight, with what is needed to relink and roll back.
|
||||
#[derive(Debug, Clone)]
|
||||
struct Linked {
|
||||
old_path: PathBuf,
|
||||
branch: Option<String>,
|
||||
/// Directory name under `.git/worktrees/`.
|
||||
id: String,
|
||||
/// Original contents of `<wt>/.git` and `.git/worktrees/<id>/gitdir`.
|
||||
orig_gitfile: String,
|
||||
orig_gitdir: String,
|
||||
}
|
||||
|
||||
impl Linked {
|
||||
fn new_path(&self, root: &Path, dir: &str) -> PathBuf {
|
||||
match self.old_path.strip_prefix(root) {
|
||||
Ok(rel) => root.join(dir).join(rel),
|
||||
Err(_) => self.old_path.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Steps after which a failure can be injected (tests only).
|
||||
@@ -83,6 +123,7 @@ pub enum Step {
|
||||
GitMoved,
|
||||
WorktreeAdded,
|
||||
Filled,
|
||||
Relinked,
|
||||
IndexMoved,
|
||||
Verified,
|
||||
}
|
||||
@@ -95,6 +136,10 @@ struct Progress {
|
||||
wt_meta: Option<PathBuf>,
|
||||
filled: bool,
|
||||
index_moved: bool,
|
||||
/// Link files of linked worktrees may have been rewritten.
|
||||
relinking: bool,
|
||||
/// Ids under `.git/worktrees/` before the migration; any other one is ours.
|
||||
orig_ids: Vec<String>,
|
||||
/// Original `core.worktree`, restored on rollback.
|
||||
orig_core_worktree: Option<String>,
|
||||
}
|
||||
@@ -104,19 +149,33 @@ struct Observed {
|
||||
status: String,
|
||||
stash: String,
|
||||
refs: String,
|
||||
/// Per linked worktree (same order as the pre-flight list): HEAD, branch, status.
|
||||
linked: Vec<String>,
|
||||
}
|
||||
|
||||
fn observe(git: &Git) -> Result<Observed, GitError> {
|
||||
fn observe(git: &Git, linked: &[PathBuf]) -> Result<Observed, GitError> {
|
||||
let refs = git.run(&["for-each-ref", "--format=%(refname) %(objectname)"])?;
|
||||
let refs = refs
|
||||
.lines()
|
||||
.filter(|l| !l.starts_with("refs/sync-backup/"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let mut lk = Vec::new();
|
||||
for path in linked {
|
||||
let g = Git::new(path);
|
||||
lk.push(format!(
|
||||
"{}\n{}\n{}",
|
||||
g.run(&["rev-parse", "HEAD"])?,
|
||||
g.probe(&["symbolic-ref", "-q", "HEAD"])?
|
||||
.unwrap_or_default(),
|
||||
g.run(&["status", "--porcelain", "--ignored"])?
|
||||
));
|
||||
}
|
||||
Ok(Observed {
|
||||
status: git.run(&["status", "--porcelain", "--ignored"])?,
|
||||
stash: git.run(&["stash", "list", "--format=%H"])?,
|
||||
refs,
|
||||
linked: lk,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -149,14 +208,14 @@ fn refuse<T>(m: impl Into<String>) -> Result<T, MigrateError> {
|
||||
Err(MigrateError::Refused(m.into()))
|
||||
}
|
||||
|
||||
fn preflight(root: &Path) -> Result<String, MigrateError> {
|
||||
fn preflight(root: &Path) -> Result<(String, Vec<Linked>), MigrateError> {
|
||||
let dotgit = root.join(".git");
|
||||
if root.join(BARE).exists() {
|
||||
return refuse("already migrated (.bare exists)");
|
||||
}
|
||||
if root.join(STAGE).exists() {
|
||||
return refuse(format!(
|
||||
"{STAGE} exists: a previous migration was interrupted. Your files are in {STAGE} and the git dir in .bare; restore from the backup tar or move them back by hand"
|
||||
"{STAGE} exists: a previous migration was interrupted. Your files are in {STAGE} and the git dir in .bare; restore from the backup tar or move them back by hand. Linked worktrees may also need their .git link files restored from the backup tars or `git worktree repair`"
|
||||
));
|
||||
}
|
||||
if !dotgit.is_dir() {
|
||||
@@ -176,19 +235,10 @@ fn preflight(root: &Path) -> Result<String, MigrateError> {
|
||||
{
|
||||
return refuse("repository has no commits yet");
|
||||
}
|
||||
for f in [
|
||||
"rebase-merge",
|
||||
"rebase-apply",
|
||||
"MERGE_HEAD",
|
||||
"CHERRY_PICK_HEAD",
|
||||
"REVERT_HEAD",
|
||||
"BISECT_LOG",
|
||||
] {
|
||||
if dotgit.join(f).exists() {
|
||||
return refuse(format!(
|
||||
"operation in progress ({f}): finish or abort it first"
|
||||
));
|
||||
}
|
||||
if let Some(f) = operation_in_progress(&dotgit) {
|
||||
return refuse(format!(
|
||||
"operation in progress ({f}): finish or abort it first"
|
||||
));
|
||||
}
|
||||
if matches!(
|
||||
git.probe(&["config", "--get", "core.sparseCheckout"])?
|
||||
@@ -201,18 +251,132 @@ fn preflight(root: &Path) -> Result<String, MigrateError> {
|
||||
) {
|
||||
return refuse("sparse checkout / per-worktree config is not supported yet");
|
||||
}
|
||||
if root.join(".gitmodules").exists() || dotgit.join("modules").exists() {
|
||||
if root.join(".gitmodules").exists()
|
||||
|| dotgit.join("modules").exists()
|
||||
|| list_ids(&dotgit)
|
||||
.iter()
|
||||
.any(|id| dotgit.join("worktrees").join(id).join("modules").exists())
|
||||
{
|
||||
return refuse("submodules are not supported yet");
|
||||
}
|
||||
if git
|
||||
.run(&["worktree", "list", "--porcelain"])?
|
||||
.matches("worktree ")
|
||||
.count()
|
||||
> 1
|
||||
{
|
||||
return refuse("repository already has linked worktrees; not supported yet");
|
||||
for key in ["worktree.useRelativePaths", "extensions.relativeWorktrees"] {
|
||||
if matches!(
|
||||
git.probe(&["config", "--type=bool", "--get", key])?
|
||||
.as_deref(),
|
||||
Some("true")
|
||||
) {
|
||||
return refuse(format!(
|
||||
"{key} (relative worktree links) is not supported yet"
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(branch)
|
||||
let linked = linked_worktrees(root, &git)?;
|
||||
Ok((branch, linked))
|
||||
}
|
||||
|
||||
const OPERATION_FILES: [&str; 6] = [
|
||||
"rebase-merge",
|
||||
"rebase-apply",
|
||||
"MERGE_HEAD",
|
||||
"CHERRY_PICK_HEAD",
|
||||
"REVERT_HEAD",
|
||||
"BISECT_LOG",
|
||||
];
|
||||
|
||||
/// First sign of an unfinished operation in a git dir (`.git` or `.git/worktrees/<id>`).
|
||||
fn operation_in_progress(gitdir: &Path) -> Option<&'static str> {
|
||||
OPERATION_FILES
|
||||
.into_iter()
|
||||
.find(|f| gitdir.join(f).exists())
|
||||
}
|
||||
|
||||
/// Linked worktrees of the plain repo at `root`, or a refusal if one cannot be moved safely.
|
||||
fn linked_worktrees(root: &Path, git: &Git) -> Result<Vec<Linked>, MigrateError> {
|
||||
let out = git.run(&["worktree", "list", "--porcelain"])?;
|
||||
let mut linked = Vec::new();
|
||||
// The first block is the main worktree.
|
||||
for block in out.split("\n\n").skip(1).filter(|b| !b.trim().is_empty()) {
|
||||
let mut path = None;
|
||||
let mut branch = None;
|
||||
let (mut locked, mut prunable) = (false, false);
|
||||
for line in block.lines() {
|
||||
if let Some(p) = line.strip_prefix("worktree ") {
|
||||
path = Some(PathBuf::from(p));
|
||||
} else if let Some(b) = line.strip_prefix("branch refs/heads/") {
|
||||
branch = Some(b.to_string());
|
||||
} else if line == "locked" || line.starts_with("locked ") {
|
||||
locked = true;
|
||||
} else if line == "prunable" || line.starts_with("prunable ") {
|
||||
prunable = true;
|
||||
}
|
||||
}
|
||||
let Some(path) = path else { continue };
|
||||
let shown = path.display();
|
||||
if locked {
|
||||
return refuse(format!(
|
||||
"linked worktree {shown} is locked: unlock it first (git worktree unlock)"
|
||||
));
|
||||
}
|
||||
let Ok(old_path) = path.canonicalize() else {
|
||||
return refuse(format!(
|
||||
"linked worktree {shown} is missing on disk: restore it or run `git worktree prune`"
|
||||
));
|
||||
};
|
||||
if prunable {
|
||||
return refuse(format!(
|
||||
"linked worktree {shown} is prunable (broken link): fix it or run `git worktree prune`"
|
||||
));
|
||||
}
|
||||
if root.starts_with(&old_path) {
|
||||
return refuse(format!(
|
||||
"linked worktree {shown} contains the repository; not supported"
|
||||
));
|
||||
}
|
||||
let gitfile = old_path.join(".git");
|
||||
let orig_gitfile = fs::read_to_string(&gitfile).map_err(|e| {
|
||||
MigrateError::Refused(format!("cannot read {}: {e}", gitfile.display()))
|
||||
})?;
|
||||
let meta = orig_gitfile
|
||||
.trim()
|
||||
.strip_prefix("gitdir: ")
|
||||
.map(PathBuf::from)
|
||||
.filter(|m| m.is_absolute())
|
||||
.ok_or_else(|| {
|
||||
MigrateError::Refused(format!(
|
||||
"linked worktree {shown}: unsupported .git file (relative links?)"
|
||||
))
|
||||
})?;
|
||||
let meta = meta.canonicalize()?;
|
||||
let id = match (meta.parent(), meta.file_name()) {
|
||||
(Some(p), Some(id)) if p == root.join(".git").join("worktrees") => {
|
||||
id.to_string_lossy().into_owned()
|
||||
}
|
||||
_ => {
|
||||
return refuse(format!(
|
||||
"linked worktree {shown} does not belong to this repository's .git"
|
||||
));
|
||||
}
|
||||
};
|
||||
if let Some(f) = operation_in_progress(&meta) {
|
||||
return refuse(format!(
|
||||
"operation in progress ({f}) in linked worktree {shown}: finish or abort it first"
|
||||
));
|
||||
}
|
||||
if old_path.join(".gitmodules").exists() {
|
||||
return refuse(format!(
|
||||
"linked worktree {shown} has submodules; not supported yet"
|
||||
));
|
||||
}
|
||||
let orig_gitdir = fs::read_to_string(meta.join("gitdir"))?;
|
||||
linked.push(Linked {
|
||||
old_path,
|
||||
branch,
|
||||
id,
|
||||
orig_gitfile,
|
||||
orig_gitdir,
|
||||
});
|
||||
}
|
||||
Ok(linked)
|
||||
}
|
||||
|
||||
fn backup(
|
||||
@@ -221,7 +385,8 @@ fn backup(
|
||||
machine: &str,
|
||||
backup_dir: &Path,
|
||||
stamp: &str,
|
||||
) -> Result<(PathBuf, String), MigrateError> {
|
||||
linked: &[Linked],
|
||||
) -> Result<(PathBuf, String, Vec<PathBuf>), MigrateError> {
|
||||
// Check before creating anything so a refusal never leaves stray directories behind.
|
||||
if std::path::absolute(backup_dir)?.starts_with(root) {
|
||||
return refuse("backup directory must be outside the repository");
|
||||
@@ -231,6 +396,11 @@ fn backup(
|
||||
if backup_dir.starts_with(root) {
|
||||
return refuse("backup directory must be outside the repository");
|
||||
}
|
||||
for l in linked.iter().filter(|l| !l.old_path.starts_with(root)) {
|
||||
if backup_dir.starts_with(&l.old_path) {
|
||||
return refuse("backup directory must be outside the linked worktrees");
|
||||
}
|
||||
}
|
||||
let name = root
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
@@ -253,9 +423,43 @@ fn backup(
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
));
|
||||
}
|
||||
// Linked worktrees outside the repo dir are not in the tar above: back each one up too.
|
||||
let mut extra = Vec::new();
|
||||
for (i, l) in linked.iter().enumerate() {
|
||||
if l.old_path.starts_with(root) {
|
||||
continue;
|
||||
}
|
||||
let (Some(wp), Some(wn)) = (l.old_path.parent(), l.old_path.file_name()) else {
|
||||
continue;
|
||||
};
|
||||
let t = backup_dir.join(format!(
|
||||
"{name}-{stamp}-linked{i}-{}.tar",
|
||||
wn.to_string_lossy()
|
||||
));
|
||||
let out = Command::new("tar")
|
||||
.arg("-cf")
|
||||
.arg(&t)
|
||||
.arg("-C")
|
||||
.arg(wp)
|
||||
.arg(wn)
|
||||
.output()?;
|
||||
if !out.status.success() {
|
||||
let _ = fs::remove_file(&t);
|
||||
let _ = fs::remove_file(&tar);
|
||||
for e in &extra {
|
||||
let _ = fs::remove_file(e);
|
||||
}
|
||||
return refuse(format!(
|
||||
"tar backup of linked worktree {} failed: {}",
|
||||
l.old_path.display(),
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
));
|
||||
}
|
||||
extra.push(t);
|
||||
}
|
||||
let backup_ref = format!("refs/sync-backup/{machine}/{stamp}/add");
|
||||
git.run(&["update-ref", &backup_ref, "HEAD"])?;
|
||||
Ok((tar, backup_ref))
|
||||
Ok((tar, backup_ref, extra))
|
||||
}
|
||||
|
||||
fn migrate_inner(
|
||||
@@ -266,23 +470,37 @@ fn migrate_inner(
|
||||
inject: Option<Step>,
|
||||
) -> Result<Report, MigrateError> {
|
||||
let root = repo.canonicalize()?;
|
||||
let branch = preflight(&root)?;
|
||||
let (branch, linked) = preflight(&root)?;
|
||||
let git = Git::new(&root);
|
||||
let before = observe(&git)?;
|
||||
let (backup_tar, backup_ref) = backup(&root, &git, machine, backup_dir, stamp)?;
|
||||
let old_paths: Vec<PathBuf> = linked.iter().map(|l| l.old_path.clone()).collect();
|
||||
let before = observe(&git, &old_paths)?;
|
||||
let (backup_tar, backup_ref, linked_backups) =
|
||||
backup(&root, &git, machine, backup_dir, stamp, &linked)?;
|
||||
|
||||
let dir = dir_name(&branch, &[BARE, STAGE]);
|
||||
let mut p = Progress::default();
|
||||
match run_steps(&root, &branch, &dir, &before, &mut p, inject) {
|
||||
let mut p = Progress {
|
||||
orig_ids: list_ids(&root.join(".git")),
|
||||
..Progress::default()
|
||||
};
|
||||
match run_steps(&root, &branch, &dir, &linked, &before, &mut p, inject) {
|
||||
Ok(worktree) => Ok(Report {
|
||||
bare_dir: root.join(BARE),
|
||||
worktree,
|
||||
branch,
|
||||
backup_tar,
|
||||
backup_ref,
|
||||
linked: linked
|
||||
.iter()
|
||||
.map(|l| LinkedReport {
|
||||
old_path: l.old_path.clone(),
|
||||
path: l.new_path(&root, &dir),
|
||||
branch: l.branch.clone(),
|
||||
})
|
||||
.collect(),
|
||||
linked_backups,
|
||||
}),
|
||||
Err(cause) => {
|
||||
let rb = rollback(&root, &p);
|
||||
let rb = rollback(&root, &p, &linked);
|
||||
let (cause, rolled_back) = match rb {
|
||||
Ok(()) => (cause, true),
|
||||
Err(e) => (format!("{cause}; rollback error: {e}"), false),
|
||||
@@ -308,6 +526,30 @@ fn move_entries(from: &Path, to: &Path, skip: &[&str]) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn list_ids(gitdir: &Path) -> Vec<String> {
|
||||
fs::read_dir(gitdir.join("worktrees"))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Point every linked worktree's link files at the new locations.
|
||||
fn relink(root: &Path, dir: &str, linked: &[Linked]) -> io::Result<()> {
|
||||
let meta_root = root.join(BARE).join("worktrees");
|
||||
for l in linked {
|
||||
let new = l.new_path(root, dir);
|
||||
let meta = meta_root.join(&l.id);
|
||||
fs::write(new.join(".git"), format!("gitdir: {}\n", meta.display()))?;
|
||||
fs::write(
|
||||
meta.join("gitdir"),
|
||||
format!("{}\n", new.join(".git").display()),
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn hook(inject: Option<Step>, at: Step) -> Result<(), String> {
|
||||
if inject == Some(at) {
|
||||
Err(format!("injected failure after {at:?}"))
|
||||
@@ -320,6 +562,7 @@ fn run_steps(
|
||||
root: &Path,
|
||||
branch: &str,
|
||||
dir: &str,
|
||||
linked: &[Linked],
|
||||
before: &Observed,
|
||||
p: &mut Progress,
|
||||
inject: Option<Step>,
|
||||
@@ -366,7 +609,7 @@ fn run_steps(
|
||||
let meta = pointer
|
||||
.trim()
|
||||
.strip_prefix("gitdir: ")
|
||||
.map(PathBuf::from)
|
||||
.map(|m| wt.join(m))
|
||||
.ok_or("unexpected .git file in new worktree")?;
|
||||
p.wt_meta = Some(meta.clone());
|
||||
hook(inject, Step::WorktreeAdded)?;
|
||||
@@ -376,6 +619,11 @@ fn run_steps(
|
||||
move_entries(&stage, &wt, &[]).map_err(s)?;
|
||||
hook(inject, Step::Filled)?;
|
||||
|
||||
// 4b. Repair the links of the linked worktrees (nested ones moved with the files).
|
||||
p.relinking = true;
|
||||
relink(root, dir, linked).map_err(s)?;
|
||||
hook(inject, Step::Relinked)?;
|
||||
|
||||
// 5. Carry over the index so staged changes survive.
|
||||
let old_index = root.join(BARE).join("index");
|
||||
if old_index.exists() {
|
||||
@@ -385,12 +633,35 @@ fn run_steps(
|
||||
hook(inject, Step::IndexMoved)?;
|
||||
|
||||
// 6. Verify nothing observable changed.
|
||||
let after = observe(&Git::new(&wt)).map_err(s)?;
|
||||
let new_paths: Vec<PathBuf> = linked.iter().map(|l| l.new_path(root, dir)).collect();
|
||||
let listing = Git::new(&wt)
|
||||
.run(&["worktree", "list", "--porcelain"])
|
||||
.map_err(s)?;
|
||||
for np in &new_paths {
|
||||
if !listing
|
||||
.lines()
|
||||
.any(|l| l == format!("worktree {}", np.display()))
|
||||
{
|
||||
return Err(format!(
|
||||
"verification failed: linked worktree {} is not registered",
|
||||
np.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
if listing
|
||||
.lines()
|
||||
.any(|l| l == "prunable" || l.starts_with("prunable "))
|
||||
{
|
||||
return Err("verification failed: a linked worktree link is broken".into());
|
||||
}
|
||||
let after = observe(&Git::new(&wt), &new_paths).map_err(s)?;
|
||||
if &after != before {
|
||||
let what = if after.status != before.status {
|
||||
"status"
|
||||
} else if after.stash != before.stash {
|
||||
"stashes"
|
||||
} else if after.linked != before.linked {
|
||||
"linked worktrees"
|
||||
} else {
|
||||
"refs"
|
||||
};
|
||||
@@ -404,7 +675,7 @@ fn run_steps(
|
||||
Ok(wt)
|
||||
}
|
||||
|
||||
fn rollback(root: &Path, p: &Progress) -> Result<(), String> {
|
||||
fn rollback(root: &Path, p: &Progress, linked: &[Linked]) -> Result<(), String> {
|
||||
let stage = root.join(STAGE);
|
||||
let bare = root.join(BARE);
|
||||
if p.index_moved
|
||||
@@ -439,8 +710,13 @@ fn rollback(root: &Path, p: &Progress) -> Result<(), String> {
|
||||
}
|
||||
if p.git_moved {
|
||||
let g = Git::new(root);
|
||||
// Drop metadata of a half-created worktree (e.g. `worktree add` failed midway).
|
||||
let _ = g.probe(&["--git-dir", BARE, "worktree", "prune"]);
|
||||
// Drop metadata of a half-created worktree (e.g. `worktree add` failed midway). Never
|
||||
// `worktree prune` here: linked worktrees are temporarily at stale paths.
|
||||
for id in list_ids(&bare) {
|
||||
if !p.orig_ids.contains(&id) {
|
||||
fs::remove_dir_all(bare.join("worktrees").join(id)).map_err(s)?;
|
||||
}
|
||||
}
|
||||
let _ = fs::remove_dir(bare.join("worktrees"));
|
||||
g.run(&["--git-dir", BARE, "config", "core.bare", "false"])
|
||||
.map_err(s)?;
|
||||
@@ -454,5 +730,19 @@ fn rollback(root: &Path, p: &Progress) -> Result<(), String> {
|
||||
move_entries(&stage, root, &[]).map_err(s)?;
|
||||
fs::remove_dir(&stage).map_err(s)?;
|
||||
}
|
||||
if p.relinking {
|
||||
// Everything is back in place: restore the link files of the linked worktrees.
|
||||
for l in linked {
|
||||
fs::write(l.old_path.join(".git"), &l.orig_gitfile).map_err(s)?;
|
||||
fs::write(
|
||||
root.join(".git")
|
||||
.join("worktrees")
|
||||
.join(&l.id)
|
||||
.join("gitdir"),
|
||||
&l.orig_gitdir,
|
||||
)
|
||||
.map_err(s)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use crate::inspect::{facts, state};
|
||||
use crate::layout::dir_name;
|
||||
use crate::snapshot::ref_name;
|
||||
use crate::state::State;
|
||||
use std::collections::BTreeSet;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -94,10 +95,89 @@ pub fn push_snapshot(worktree: &Path, machine: &str, remote: &str) -> Result<(),
|
||||
.probe(&["symbolic-ref", "--short", "-q", "HEAD"])?
|
||||
.ok_or_else(|| GitError::Other("detached HEAD".into()))?;
|
||||
let r = ref_name(machine, &branch);
|
||||
g.run(&["push", "-q", "--force", remote, &format!("{r}:{r}")])?;
|
||||
g.run(&[
|
||||
"-c",
|
||||
"push.recurseSubmodules=no",
|
||||
"push",
|
||||
"-q",
|
||||
"--force",
|
||||
remote,
|
||||
&format!("{r}:{r}"),
|
||||
])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Deletes this machine's snapshot refs (`refs/sync/<machine>/*`, never anything else) from every
|
||||
/// push URL of `remote` and then locally; used when snapshots must no longer be published.
|
||||
/// Refs that exist only on the remote side are removed too. Each URL is pushed separately and
|
||||
/// counts as clean only when a fresh `ls-remote` shows none of this machine's refs; any other
|
||||
/// outcome (including "repository does not exist") is a failure that keeps the local refs so
|
||||
/// the next call retries. Returns the refs removed.
|
||||
pub fn purge_own_snapshots(
|
||||
gitdir: &Path,
|
||||
machine: &str,
|
||||
remote: &str,
|
||||
) -> Result<Vec<String>, GitError> {
|
||||
let g = Git::new(gitdir);
|
||||
let prefix = format!("refs/sync/{machine}/");
|
||||
let pattern = format!("{prefix}*");
|
||||
let own = |text: &str, refs: &mut BTreeSet<String>| {
|
||||
for l in text.lines() {
|
||||
if let Some(r) = l.split_whitespace().last()
|
||||
&& r.starts_with(&prefix)
|
||||
{
|
||||
refs.insert(r.to_string());
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut all = BTreeSet::new();
|
||||
own(
|
||||
&g.run(&["for-each-ref", "--format=%(refname)", &prefix])?,
|
||||
&mut all,
|
||||
);
|
||||
let urls = g.run(&["remote", "get-url", "--push", "--all", remote])?;
|
||||
let mut failure = None;
|
||||
for url in urls.lines().map(str::trim).filter(|u| !u.is_empty()) {
|
||||
let mut there = BTreeSet::new();
|
||||
match g.run(&["ls-remote", url, &pattern]) {
|
||||
Ok(t) => own(&t, &mut there),
|
||||
Err(e) => {
|
||||
failure.get_or_insert(e);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
all.extend(there.iter().cloned());
|
||||
if there.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut args = vec!["-c", "push.recurseSubmodules=no", "push", "-q", url];
|
||||
let specs: Vec<String> = there.iter().map(|r| format!(":{r}")).collect();
|
||||
args.extend(specs.iter().map(String::as_str));
|
||||
let pushed = g.run(&args);
|
||||
let mut left = BTreeSet::new();
|
||||
match g.run(&["ls-remote", url, &pattern]) {
|
||||
Ok(t) => own(&t, &mut left),
|
||||
Err(e) => {
|
||||
failure.get_or_insert(e);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if !left.is_empty() {
|
||||
failure.get_or_insert(pushed.err().unwrap_or_else(|| {
|
||||
GitError::Other(format!("{url}: snapshot refs still present after delete"))
|
||||
}));
|
||||
}
|
||||
}
|
||||
if let Some(e) = failure {
|
||||
return Err(e);
|
||||
}
|
||||
let local = g.run(&["for-each-ref", "--format=%(refname)", &prefix])?;
|
||||
for r in local.lines().filter(|r| r.starts_with(&prefix)) {
|
||||
g.run(&["update-ref", "-d", r])?;
|
||||
}
|
||||
Ok(all.into_iter().collect())
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Received {
|
||||
FastForwarded {
|
||||
@@ -347,11 +427,17 @@ pub fn archive_gone(root: &Path, machine: &str, stamp: &str) -> Result<Vec<Archi
|
||||
.map(|(b, _)| b)
|
||||
.collect();
|
||||
let wts = crate::inspect::worktrees(&bare)?;
|
||||
let canonical_root = root.canonicalize().ok();
|
||||
let mut out = Vec::new();
|
||||
for branch in gone {
|
||||
let Some(wt) = wts.iter().find(|w| w.branch.as_deref() == Some(branch)) else {
|
||||
continue;
|
||||
};
|
||||
// Only worktrees of the layout (`<root>/<dir>`) are ours to remove; a linked worktree
|
||||
// elsewhere (e.g. a sibling directory) is the user's.
|
||||
if wt.path.parent() != canonical_root.as_deref() {
|
||||
continue;
|
||||
}
|
||||
// Ignored files (.env, build output...) count as local work too.
|
||||
if !Git::new(&wt.path)
|
||||
.run(&["status", "--porcelain", "--ignored"])?
|
||||
|
||||
@@ -20,6 +20,10 @@ pub struct Options {
|
||||
pub offline: bool,
|
||||
/// Create worktrees for new remote branches and archive gone ones (bare layout only).
|
||||
pub materialize: bool,
|
||||
/// Take and push WIP snapshots. When false (private-only policy on a public or unknown
|
||||
/// repo, or `snapshots = "none"`) no `refs/sync/<machine>/*` ref is created or pushed;
|
||||
/// fetching, fast-forwarding and applying other machines' snapshots are unaffected.
|
||||
pub push_snapshots: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
@@ -110,7 +114,7 @@ fn sync_worktree(r: &mut WorktreeReport, branch: &str, o: &Options, fetched: boo
|
||||
}
|
||||
};
|
||||
// A clean worktree still refreshes an existing snapshot so a stale WIP never lingers.
|
||||
if dirty || has_ref {
|
||||
if o.push_snapshots && (dirty || has_ref) {
|
||||
match take(&path, &o.machine, &o.stamp) {
|
||||
Ok(Outcome::Created(s)) => {
|
||||
r.snapshot = Some("created");
|
||||
|
||||
@@ -170,19 +170,66 @@ fn refuses_unsafe_situations_without_touching_anything() {
|
||||
fs::write(subm.join(".gitmodules"), "").unwrap();
|
||||
assert!(refused(migrate(&subm, "m", &bk, "1")).contains("submodule"));
|
||||
|
||||
let multi = base.join("multi");
|
||||
let g = init(&multi);
|
||||
let locked = base.join("locked");
|
||||
let g = init(&locked);
|
||||
commit(&g, "a", "1");
|
||||
g.run(&[
|
||||
"worktree",
|
||||
"add",
|
||||
"-q",
|
||||
"-b",
|
||||
"x",
|
||||
base.join("extra").to_str().unwrap(),
|
||||
])
|
||||
.unwrap();
|
||||
assert!(refused(migrate(&multi, "m", &bk, "1")).contains("linked worktrees"));
|
||||
let lw = base.join("locked-wt");
|
||||
g.run(&["worktree", "add", "-q", "-b", "x", lw.to_str().unwrap()])
|
||||
.unwrap();
|
||||
g.run(&["worktree", "lock", lw.to_str().unwrap()]).unwrap();
|
||||
assert!(refused(migrate(&locked, "m", &bk, "1")).contains("locked"));
|
||||
assert!(locked.join(".git").is_dir(), "refusal touches nothing");
|
||||
|
||||
let prunable = base.join("prunable");
|
||||
let g = init(&prunable);
|
||||
commit(&g, "a", "1");
|
||||
let pw = base.join("prunable-wt");
|
||||
g.run(&["worktree", "add", "-q", "-b", "x", pw.to_str().unwrap()])
|
||||
.unwrap();
|
||||
fs::remove_dir_all(&pw).unwrap();
|
||||
assert!(refused(migrate(&prunable, "m", &bk, "1")).contains("missing"));
|
||||
|
||||
let busy = base.join("busy");
|
||||
let g = init(&busy);
|
||||
commit(&g, "a", "1");
|
||||
let bw = base.join("busy-wt");
|
||||
g.run(&["worktree", "add", "-q", "-b", "x", bw.to_str().unwrap()])
|
||||
.unwrap();
|
||||
let meta = fs::read_to_string(bw.join(".git")).unwrap();
|
||||
let meta = meta.trim().strip_prefix("gitdir: ").unwrap();
|
||||
fs::write(std::path::Path::new(meta).join("MERGE_HEAD"), "x").unwrap();
|
||||
let m = refused(migrate(&busy, "m", &bk, "1"));
|
||||
assert!(
|
||||
m.contains("in progress") && m.contains("linked worktree"),
|
||||
"{m}"
|
||||
);
|
||||
|
||||
let subw = base.join("subw");
|
||||
let g = init(&subw);
|
||||
commit(&g, "a", "1");
|
||||
let sw = base.join("subw-wt");
|
||||
g.run(&["worktree", "add", "-q", "-b", "x", sw.to_str().unwrap()])
|
||||
.unwrap();
|
||||
fs::write(sw.join(".gitmodules"), "").unwrap();
|
||||
assert!(refused(migrate(&subw, "m", &bk, "1")).contains("submodules"));
|
||||
let subm2 = base.join("subm2");
|
||||
let g = init(&subm2);
|
||||
commit(&g, "a", "1");
|
||||
let sw2 = base.join("subm2-wt");
|
||||
g.run(&["worktree", "add", "-q", "-b", "x", sw2.to_str().unwrap()])
|
||||
.unwrap();
|
||||
let meta = fs::read_to_string(sw2.join(".git")).unwrap();
|
||||
let meta = meta.trim().strip_prefix("gitdir: ").unwrap();
|
||||
fs::create_dir_all(std::path::Path::new(meta).join("modules/m")).unwrap();
|
||||
assert!(refused(migrate(&subm2, "m", &bk, "1")).contains("submodules"));
|
||||
|
||||
let rel = base.join("rel");
|
||||
let g = init(&rel);
|
||||
commit(&g, "a", "1");
|
||||
g.run(&["config", "worktree.useRelativePaths", "true"])
|
||||
.unwrap();
|
||||
assert!(refused(migrate(&rel, "m", &bk, "1")).contains("relative"));
|
||||
assert!(rel.join(".git").is_dir());
|
||||
|
||||
let done = base.join("done");
|
||||
let g = init(&done);
|
||||
@@ -209,3 +256,169 @@ fn refuses_unsafe_situations_without_touching_anything() {
|
||||
fs::create_dir(inside.join("sub")).unwrap();
|
||||
assert!(refused(migrate(&inside.join("sub"), "m", &bk, "1")).contains("plain clone"));
|
||||
}
|
||||
|
||||
/// Observable state of a worktree: HEAD, branch and `status --ignored`.
|
||||
fn wt_state(dir: &std::path::Path) -> String {
|
||||
let g = Git::new(dir);
|
||||
format!(
|
||||
"{}|{}|{}",
|
||||
g.run(&["rev-parse", "HEAD"]).unwrap(),
|
||||
g.probe(&["symbolic-ref", "-q", "HEAD"])
|
||||
.unwrap()
|
||||
.unwrap_or_default(),
|
||||
g.run(&["status", "--porcelain", "--ignored"]).unwrap()
|
||||
)
|
||||
}
|
||||
|
||||
/// A repo with a detached worktree nested in it and a dirty branch worktree next to it.
|
||||
fn repo_with_linked(
|
||||
base: &std::path::Path,
|
||||
) -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) {
|
||||
let repo = base.join("proj");
|
||||
let g = messy_repo(&repo);
|
||||
let nested = repo.join(".claude/worktrees/wt1");
|
||||
fs::create_dir_all(nested.parent().unwrap()).unwrap();
|
||||
g.run(&[
|
||||
"worktree",
|
||||
"add",
|
||||
"-q",
|
||||
"--detach",
|
||||
nested.to_str().unwrap(),
|
||||
])
|
||||
.unwrap();
|
||||
fs::write(nested.join("src/a.txt"), "nested edit\n").unwrap();
|
||||
fs::write(nested.join("nested-untracked.txt"), "n\n").unwrap();
|
||||
fs::write(nested.join("nested.env"), "ignored\n").unwrap();
|
||||
let outside = base.join("proj-feature");
|
||||
g.run(&[
|
||||
"worktree",
|
||||
"add",
|
||||
"-q",
|
||||
"-b",
|
||||
"feat/out",
|
||||
outside.to_str().unwrap(),
|
||||
])
|
||||
.unwrap();
|
||||
fs::write(outside.join("b.txt"), "outside edit\n").unwrap();
|
||||
fs::write(outside.join("new-staged.txt"), "s\n").unwrap();
|
||||
Git::new(&outside).run(&["add", "new-staged.txt"]).unwrap();
|
||||
fs::write(outside.join("out-untracked.txt"), "u\n").unwrap();
|
||||
fs::write(outside.join("out.env"), "ignored\n").unwrap();
|
||||
(repo, nested, outside)
|
||||
}
|
||||
|
||||
fn same_links(wt: &std::path::Path, bare: &std::path::Path) {
|
||||
let pointer = fs::read_to_string(wt.join(".git")).unwrap();
|
||||
let meta = std::path::PathBuf::from(pointer.trim().strip_prefix("gitdir: ").unwrap());
|
||||
assert!(meta.starts_with(bare.join("worktrees")), "{pointer}");
|
||||
let back = fs::read_to_string(meta.join("gitdir")).unwrap();
|
||||
assert_eq!(back.trim(), wt.join(".git").to_str().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migrates_with_nested_detached_and_outside_branch_worktrees() {
|
||||
let base = tmpdir("linked");
|
||||
let (repo, nested, outside) = repo_with_linked(&base);
|
||||
let (nested_before, outside_before) = (wt_state(&nested), wt_state(&outside));
|
||||
let main_before = wt_state(&repo);
|
||||
assert!(nested_before.contains("nested-untracked.txt"));
|
||||
|
||||
let r = migrate(&repo, "m", &base.join("bk"), "1").unwrap();
|
||||
|
||||
let root = repo.canonicalize().unwrap();
|
||||
let new_nested = root.join("main/.claude/worktrees/wt1");
|
||||
assert_eq!(names(&root), vec![".bare", "main"]);
|
||||
assert_eq!(r.linked.len(), 2);
|
||||
let find = |p: &std::path::Path| r.linked.iter().find(|l| l.path == p).unwrap();
|
||||
assert_eq!(find(&new_nested).branch, None);
|
||||
assert_eq!(
|
||||
find(&new_nested).old_path,
|
||||
root.join(".claude/worktrees/wt1")
|
||||
);
|
||||
let out_canon = outside.canonicalize().unwrap();
|
||||
assert_eq!(find(&out_canon).branch.as_deref(), Some("feat/out"));
|
||||
assert_eq!(find(&out_canon).old_path, out_canon);
|
||||
assert_eq!(
|
||||
r.linked_backups.len(),
|
||||
1,
|
||||
"outside worktree gets its own tar"
|
||||
);
|
||||
assert!(r.linked_backups[0].metadata().unwrap().len() > 0);
|
||||
|
||||
// Same observable state in all three worktrees, and links point both ways.
|
||||
assert_eq!(wt_state(&r.worktree), main_before);
|
||||
assert_eq!(wt_state(&new_nested), nested_before);
|
||||
assert_eq!(wt_state(&outside), outside_before);
|
||||
same_links(&new_nested, &r.bare_dir);
|
||||
same_links(&outside.canonicalize().unwrap(), &r.bare_dir);
|
||||
assert!(!root.join(".claude").exists());
|
||||
assert_eq!(
|
||||
fs::read_to_string(outside.join("b.txt")).unwrap(),
|
||||
"outside edit\n"
|
||||
);
|
||||
assert!(outside.join("out.env").exists());
|
||||
assert!(new_nested.join("nested.env").exists());
|
||||
|
||||
let list = Git::new(&r.worktree)
|
||||
.run(&["worktree", "list", "--porcelain"])
|
||||
.unwrap();
|
||||
assert!(list.contains(&format!("worktree {}", new_nested.display())));
|
||||
assert!(list.contains(&format!(
|
||||
"worktree {}",
|
||||
outside.canonicalize().unwrap().display()
|
||||
)));
|
||||
assert!(!list.contains("prunable"), "{list}");
|
||||
|
||||
// They are still usable: commit on the outside branch, status in the nested one.
|
||||
let og = Git::new(&outside);
|
||||
og.run(&["commit", "-qam", "more"]).unwrap();
|
||||
assert!(Git::new(&new_nested).run(&["status"]).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rollback_restores_linked_worktrees_at_every_step() {
|
||||
for step in [
|
||||
Step::Staged,
|
||||
Step::GitMoved,
|
||||
Step::WorktreeAdded,
|
||||
Step::Filled,
|
||||
Step::Relinked,
|
||||
Step::IndexMoved,
|
||||
Step::Verified,
|
||||
] {
|
||||
let base = tmpdir("rblinked");
|
||||
let (repo, nested, outside) = repo_with_linked(&base);
|
||||
let before = (wt_state(&repo), wt_state(&nested), wt_state(&outside));
|
||||
let files = (
|
||||
fs::read_to_string(nested.join(".git")).unwrap(),
|
||||
fs::read_to_string(outside.join(".git")).unwrap(),
|
||||
);
|
||||
let names_before = names(&repo);
|
||||
|
||||
let err = migrate_failing_after(&repo, "m", &base.join("bk"), "1", step).unwrap_err();
|
||||
let MigrateError::Failed { rolled_back, .. } = err else {
|
||||
panic!("{step:?}: expected Failed")
|
||||
};
|
||||
assert!(rolled_back, "{step:?}");
|
||||
|
||||
assert_eq!(names(&repo), names_before, "{step:?}");
|
||||
assert_eq!(
|
||||
(wt_state(&repo), wt_state(&nested), wt_state(&outside)),
|
||||
before,
|
||||
"{step:?}"
|
||||
);
|
||||
assert_eq!(fs::read_to_string(nested.join(".git")).unwrap(), files.0);
|
||||
assert_eq!(fs::read_to_string(outside.join(".git")).unwrap(), files.1);
|
||||
let g = Git::new(&repo);
|
||||
let list = g.run(&["worktree", "list", "--porcelain"]).unwrap();
|
||||
assert_eq!(list.matches("worktree ").count(), 3, "{step:?}: {list}");
|
||||
assert!(!list.contains("prunable"), "{step:?}: {list}");
|
||||
assert_eq!(
|
||||
fs::read_dir(repo.join(".git/worktrees")).unwrap().count(),
|
||||
2,
|
||||
"{step:?}: only the original worktree metadata remains"
|
||||
);
|
||||
// And a retry succeeds afterwards.
|
||||
migrate(&repo, "m", &base.join("bk"), "2").unwrap();
|
||||
}
|
||||
}
|
||||
@@ -382,6 +382,7 @@ fn archive_and_receive_in_one_pass_do_not_collide_on_backup_refs() {
|
||||
remote: "origin".into(),
|
||||
offline: false,
|
||||
materialize: true,
|
||||
push_snapshots: true,
|
||||
};
|
||||
w.g1.run(&["checkout", "-q", "-b", "feat/z"]).unwrap();
|
||||
commit(&w.g1, "z.txt", "z\n");
|
||||
|
||||
@@ -15,6 +15,7 @@ fn opts(machine: &str, stamp: &str) -> Options {
|
||||
remote: "origin".into(),
|
||||
offline: false,
|
||||
materialize: true,
|
||||
push_snapshots: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,3 +169,187 @@ fn staged_changes_block_adoption_so_the_index_is_never_reset() {
|
||||
assert_eq!(r.worktrees[0].state, State::BehindDirty);
|
||||
assert_eq!(gb.run(&["show", ":a.txt"]).unwrap(), "1\nstaged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn withheld_snapshots_are_neither_taken_nor_pushed_but_fast_forward_still_works() {
|
||||
let base = tmpdir("nosnap");
|
||||
let remote = base.join("r.git");
|
||||
Git::new(&base)
|
||||
.run(&[
|
||||
"init",
|
||||
"-q",
|
||||
"--bare",
|
||||
"-b",
|
||||
"main",
|
||||
remote.to_str().unwrap(),
|
||||
])
|
||||
.unwrap();
|
||||
let seed = init(&base.join("seed"));
|
||||
seed.run(&["remote", "add", "origin", remote.to_str().unwrap()])
|
||||
.unwrap();
|
||||
commit(&seed, "a.txt", "1\n");
|
||||
seed.run(&["push", "-q", "-u", "origin", "main"]).unwrap();
|
||||
let (_g, d) = clone(&base, &remote, "A");
|
||||
fs::write(d.join("a.txt"), "1\nsecret\n").unwrap();
|
||||
let o = Options {
|
||||
push_snapshots: false,
|
||||
..opts("A", "t1")
|
||||
};
|
||||
let r = sync_repo(&d, &o).unwrap();
|
||||
assert_eq!(r.worktrees[0].snapshot, None);
|
||||
let g = Git::new(&remote);
|
||||
assert!(g.run(&["for-each-ref", "refs/sync/"]).unwrap().is_empty());
|
||||
// Fast-forwarding keeps working.
|
||||
commit(&seed, "b.txt", "2\n");
|
||||
seed.run(&["push", "-q"]).unwrap();
|
||||
fs::write(d.join("a.txt"), "1\n").unwrap();
|
||||
let r = sync_repo(&d, &o).unwrap();
|
||||
assert!(matches!(
|
||||
r.worktrees[0].received,
|
||||
Some(Received::FastForwarded { .. })
|
||||
));
|
||||
assert!(d.join("b.txt").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migrated_repo_with_linked_worktrees_syncs_only_what_it_can() {
|
||||
use grove_core::migrate::migrate;
|
||||
let base = tmpdir("synclinked");
|
||||
let remote = base.join("r.git");
|
||||
Git::new(&base)
|
||||
.run(&[
|
||||
"init",
|
||||
"-q",
|
||||
"--bare",
|
||||
"-b",
|
||||
"main",
|
||||
remote.to_str().unwrap(),
|
||||
])
|
||||
.unwrap();
|
||||
let seed = init(&base.join("seed"));
|
||||
seed.run(&["remote", "add", "origin", remote.to_str().unwrap()])
|
||||
.unwrap();
|
||||
commit(&seed, "a.txt", "1\n");
|
||||
seed.run(&["push", "-q", "-u", "origin", "main"]).unwrap();
|
||||
seed.run(&["push", "-q", "origin", "main:feat/out"])
|
||||
.unwrap();
|
||||
let (ga, da) = clone(&base, &remote, "A");
|
||||
let nested = da.join(".claude/worktrees/wt1");
|
||||
ga.run(&[
|
||||
"worktree",
|
||||
"add",
|
||||
"-q",
|
||||
"--detach",
|
||||
nested.to_str().unwrap(),
|
||||
])
|
||||
.unwrap();
|
||||
let outside = base.join("A-feature");
|
||||
ga.run(&[
|
||||
"worktree",
|
||||
"add",
|
||||
"-q",
|
||||
"--track",
|
||||
"-b",
|
||||
"feat/out",
|
||||
outside.to_str().unwrap(),
|
||||
"origin/feat/out",
|
||||
])
|
||||
.unwrap();
|
||||
migrate(&da, "A", &base.join("bk"), "1").unwrap();
|
||||
let nested = da.join("main/.claude/worktrees/wt1");
|
||||
fs::write(nested.join("a.txt"), "detached edit\n").unwrap();
|
||||
fs::write(outside.join("a.txt"), "outside edit\n").unwrap();
|
||||
|
||||
let rep = sync_repo(&da, &opts("A", "t1")).unwrap();
|
||||
let find = |p: &Path| {
|
||||
rep.worktrees
|
||||
.iter()
|
||||
.find(|w| w.path == p.canonicalize().unwrap())
|
||||
.unwrap_or_else(|| panic!("{} not reported: {:?}", p.display(), rep.worktrees))
|
||||
};
|
||||
// Detached: reported, never snapshotted.
|
||||
let d = find(&nested);
|
||||
assert_eq!((d.branch.clone(), d.snapshot), (None, None));
|
||||
assert!(d.errors.is_empty(), "{:?}", d.errors);
|
||||
assert_eq!(d.state, State::Dirty);
|
||||
// Branch worktree elsewhere: synced under its own branch ref.
|
||||
let o = find(&outside);
|
||||
assert_eq!(o.snapshot, Some("created"));
|
||||
assert!(o.errors.is_empty(), "{:?}", o.errors);
|
||||
let bare = Git::new(da.join(".bare"));
|
||||
assert!(bare.run(&["rev-parse", "refs/sync/A/feat/out"]).is_ok());
|
||||
assert!(
|
||||
bare.probe(&["rev-parse", "-q", "--verify", "refs/sync/A/HEAD"])
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
|
||||
// Gone upstream + clean: a worktree outside the layout is never archived or removed.
|
||||
Git::new(&outside)
|
||||
.run(&["checkout", "-q", "--", "."])
|
||||
.unwrap();
|
||||
seed.run(&["push", "-q", "origin", "--delete", "feat/out"])
|
||||
.unwrap();
|
||||
let rep = sync_repo(&da, &opts("A", "t2")).unwrap();
|
||||
assert!(rep.archived.is_empty(), "{:?}", rep.archived);
|
||||
assert!(outside.join("a.txt").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn purge_removes_remote_only_own_refs_and_nothing_else() {
|
||||
use grove_core::receive::purge_own_snapshots;
|
||||
let base = tmpdir("purge");
|
||||
let remote = base.join("r.git");
|
||||
Git::new(&base)
|
||||
.run(&[
|
||||
"init",
|
||||
"-q",
|
||||
"--bare",
|
||||
"-b",
|
||||
"main",
|
||||
remote.to_str().unwrap(),
|
||||
])
|
||||
.unwrap();
|
||||
let seed = init(&base.join("seed"));
|
||||
seed.run(&["remote", "add", "origin", remote.to_str().unwrap()])
|
||||
.unwrap();
|
||||
commit(&seed, "a.txt", "1\n");
|
||||
seed.run(&["push", "-q", "-u", "origin", "main"]).unwrap();
|
||||
// Own refs: one with a local copy, one only on the remote. Plus another machine's ref.
|
||||
seed.run(&["push", "-q", "origin", "main:refs/sync/A/main"])
|
||||
.unwrap();
|
||||
seed.run(&["push", "-q", "origin", "main:refs/sync/A/feat/x"])
|
||||
.unwrap();
|
||||
seed.run(&["push", "-q", "origin", "main:refs/sync/B/main"])
|
||||
.unwrap();
|
||||
seed.run(&["update-ref", "refs/sync/A/main", "HEAD"])
|
||||
.unwrap();
|
||||
let done = purge_own_snapshots(seed.dir(), "A", "origin").unwrap();
|
||||
assert_eq!(done, vec!["refs/sync/A/feat/x", "refs/sync/A/main"]);
|
||||
let refs = Git::new(&remote)
|
||||
.run(&["for-each-ref", "--format=%(refname)"])
|
||||
.unwrap();
|
||||
assert_eq!(refs, "refs/heads/main\nrefs/sync/B/main");
|
||||
assert!(
|
||||
seed.run(&["for-each-ref", "refs/sync/A/"])
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
// A remote that cannot be reached is a failure and keeps the local refs.
|
||||
seed.run(&["update-ref", "refs/sync/A/main", "HEAD"])
|
||||
.unwrap();
|
||||
seed.run(&[
|
||||
"remote",
|
||||
"set-url",
|
||||
"origin",
|
||||
base.join("nope.git").to_str().unwrap(),
|
||||
])
|
||||
.unwrap();
|
||||
assert!(purge_own_snapshots(seed.dir(), "A", "origin").is_err());
|
||||
assert!(
|
||||
!seed
|
||||
.run(&["for-each-ref", "refs/sync/A/"])
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
@@ -15,6 +15,7 @@ path = "src/main.rs"
|
||||
[dependencies]
|
||||
anyhow = "1.0.104"
|
||||
grove-core = { version = "0.1.0", path = "../grove-core" }
|
||||
grove-providers = { version = "0.1.0", path = "../grove-providers" }
|
||||
notify = "8.2.2"
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
serde_json = "1.0.154"
|
||||
@@ -3,8 +3,9 @@
|
||||
//! so passes never overlap.
|
||||
|
||||
use crate::activity::{Activity, now_secs};
|
||||
use crate::discover::discover;
|
||||
use crate::discover::{discover, group_of};
|
||||
use crate::ipc;
|
||||
use crate::visibility::{RealForge, Visibility, snapshot_gate};
|
||||
use grove_core::config::Config;
|
||||
use grove_core::receive::Received;
|
||||
use grove_core::sync::{Options, sync_repo};
|
||||
@@ -24,6 +25,8 @@ pub struct Settings {
|
||||
pub socket: PathBuf,
|
||||
pub activity_log: Option<PathBuf>,
|
||||
pub remote: String,
|
||||
/// Where forge visibility answers are cached (`None` = in memory only).
|
||||
pub visibility_cache: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
@@ -34,6 +37,7 @@ impl Settings {
|
||||
socket: ipc::default_socket_path(),
|
||||
activity_log: Some(state.join("activity.jsonl")),
|
||||
remote: "origin".into(),
|
||||
visibility_cache: Some(state.join("visibility.json")),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,6 +57,10 @@ pub struct RepoStatus {
|
||||
pub last_error: Option<String>,
|
||||
pub worktrees: Vec<WtStatus>,
|
||||
pub failures: u32,
|
||||
/// Why WIP snapshots are not pushed for this repo (`None` = they are).
|
||||
pub snapshots_withheld: Option<String>,
|
||||
/// Last verdict of the snapshot gate (`None` = not evaluated yet).
|
||||
pub gate_allowed: Option<bool>,
|
||||
}
|
||||
|
||||
impl Default for RepoStatus {
|
||||
@@ -63,6 +71,8 @@ impl Default for RepoStatus {
|
||||
last_error: None,
|
||||
worktrees: Vec::new(),
|
||||
failures: 0,
|
||||
snapshots_withheld: None,
|
||||
gate_allowed: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -71,6 +81,8 @@ impl Default for RepoStatus {
|
||||
pub struct Shared {
|
||||
pub paused: bool,
|
||||
pub repos: BTreeMap<PathBuf, RepoStatus>,
|
||||
/// Plain clones in configured groups: ignored until migrated with `grove add`.
|
||||
pub not_migrated: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
pub enum Msg {
|
||||
@@ -231,9 +243,11 @@ impl Watch {
|
||||
}
|
||||
}
|
||||
|
||||
fn rescan(root: &Path, watch: &mut Watch, ctx: &Ctx) -> Vec<PathBuf> {
|
||||
let found = discover(root);
|
||||
fn rescan(root: &Path, groups: &[String], watch: &mut Watch, ctx: &Ctx) -> Vec<PathBuf> {
|
||||
let d = discover(root, groups);
|
||||
let found = d.managed;
|
||||
let mut shared = ctx.shared.lock().unwrap();
|
||||
shared.not_migrated = d.not_migrated;
|
||||
shared.repos.retain(|p, _| found.contains(p));
|
||||
for r in &found {
|
||||
shared.repos.entry(r.clone()).or_default();
|
||||
@@ -249,9 +263,10 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
||||
let debounce = Duration::from_millis(cfg.sync.snapshot_debounce_ms);
|
||||
let fetch_every = Duration::from_secs(cfg.sync.fetch_interval_s.max(1));
|
||||
let root = cfg.root_path();
|
||||
let groups: Vec<String> = cfg.groups.iter().map(|g| g.name.clone()).collect();
|
||||
let mut visibility = Visibility::load(st.visibility_cache.clone());
|
||||
let mut watch = make_watch(ctx.tx.clone(), cfg.sync.ignore_extra.clone(), &ctx);
|
||||
rescan(&root, &mut watch, &ctx);
|
||||
let materialize = cfg.groups.iter().all(|g| g.auto_materialize);
|
||||
rescan(&root, &groups, &mut watch, &ctx);
|
||||
|
||||
// due_at: when a repo should next be synced; backoff_until: earliest retry after failures.
|
||||
let mut due_at: HashMap<PathBuf, Instant> = HashMap::new();
|
||||
@@ -307,7 +322,7 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
||||
}
|
||||
let now = Instant::now();
|
||||
if now >= next_full {
|
||||
let found = rescan(&root, &mut watch, &ctx);
|
||||
let found = rescan(&root, &groups, &mut watch, &ctx);
|
||||
due_at.retain(|r, _| found.contains(r));
|
||||
for r in found {
|
||||
due_at.insert(r, now);
|
||||
@@ -330,7 +345,7 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
||||
// 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.
|
||||
let offline = backoff_until.get(&r).is_some_and(|u| *u > now);
|
||||
let failures = pass(&r, &cfg, &st, materialize, offline, &ctx);
|
||||
let failures = pass(&r, &cfg, &st, &mut visibility, offline, &ctx);
|
||||
if offline {
|
||||
continue;
|
||||
}
|
||||
@@ -354,18 +369,43 @@ fn pass(
|
||||
repo: &Path,
|
||||
cfg: &Config,
|
||||
st: &Settings,
|
||||
materialize: bool,
|
||||
visibility: &mut Visibility,
|
||||
offline: bool,
|
||||
ctx: &Ctx,
|
||||
) -> u32 {
|
||||
let name = repo.display().to_string();
|
||||
set_phase(ctx, repo, "syncing");
|
||||
let group = group_of(repo).unwrap_or_default();
|
||||
// `auto_materialize` is per group; a repo whose group is gone from the config keeps the default.
|
||||
let materialize = cfg
|
||||
.groups
|
||||
.iter()
|
||||
.find(|g| g.name == group)
|
||||
.is_none_or(|g| g.auto_materialize);
|
||||
// Offline there is no lookup: use the last verdict, and take no snapshot if there is none.
|
||||
let push_snapshots = if offline {
|
||||
ctx.shared
|
||||
.lock()
|
||||
.unwrap()
|
||||
.repos
|
||||
.get(repo)
|
||||
.is_some_and(|s| s.gate_allowed == Some(true))
|
||||
} else {
|
||||
let gate = snapshot_gate(cfg, repo, &st.remote, visibility, now_secs(), &RealForge);
|
||||
let allowed = gate.is_ok();
|
||||
note_snapshot_gate(ctx, repo, &name, gate.err());
|
||||
if !allowed {
|
||||
purge_snapshots(ctx, repo, &name, cfg, st);
|
||||
}
|
||||
allowed
|
||||
};
|
||||
let opts = Options {
|
||||
machine: cfg.machine.name.clone(),
|
||||
stamp: stamp(),
|
||||
remote: st.remote.clone(),
|
||||
offline,
|
||||
materialize,
|
||||
push_snapshots,
|
||||
};
|
||||
let result = sync_repo(repo, &opts);
|
||||
let mut shared = ctx.shared.lock().unwrap();
|
||||
@@ -451,6 +491,52 @@ fn pass(
|
||||
status.failures
|
||||
}
|
||||
|
||||
/// 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>) {
|
||||
let mut shared = ctx.shared.lock().unwrap();
|
||||
let status = shared.repos.entry(repo.to_path_buf()).or_default();
|
||||
status.gate_allowed = Some(withheld.is_none());
|
||||
if status.snapshots_withheld == withheld {
|
||||
return;
|
||||
}
|
||||
match &withheld {
|
||||
Some(why) => ctx.activity.log(
|
||||
"snapshots_withheld",
|
||||
Some(name),
|
||||
format!("WIP snapshots not pushed: {why}"),
|
||||
),
|
||||
None => ctx
|
||||
.activity
|
||||
.log("snapshots_enabled", Some(name), "WIP snapshots are pushed"),
|
||||
}
|
||||
status.snapshots_withheld = withheld;
|
||||
}
|
||||
|
||||
/// Snapshots are withheld: remove this machine's snapshot refs from the remote (they may have
|
||||
/// been pushed while the repo was still private) and locally. Only `refs/sync/<machine>/*`;
|
||||
/// never other machines' refs or branches. Does nothing when there are no local refs, and a
|
||||
/// failed deletion keeps them so the next pass retries.
|
||||
fn purge_snapshots(ctx: &Ctx, repo: &Path, name: &str, cfg: &Config, st: &Settings) {
|
||||
let gitdir = grove_core::sync::git_dir_for(repo);
|
||||
match grove_core::receive::purge_own_snapshots(&gitdir, &cfg.machine.name, &st.remote) {
|
||||
Ok(done) if done.is_empty() => {}
|
||||
Ok(done) => ctx.activity.log(
|
||||
"snapshots_purged",
|
||||
Some(name),
|
||||
format!(
|
||||
"WARNING: snapshots are no longer allowed; deleted {} snapshot ref(s) of this machine from the remote: {}",
|
||||
done.len(),
|
||||
done.join(", ")
|
||||
),
|
||||
),
|
||||
Err(e) => ctx.activity.log(
|
||||
"error",
|
||||
Some(name),
|
||||
format!("could not delete this machine's snapshot refs from the remote: {e}"),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_phase(ctx: &Ctx, repo: &Path, phase: &'static str) {
|
||||
if let Some(s) = ctx.shared.lock().unwrap().repos.get_mut(repo) {
|
||||
s.phase = phase;
|
||||
|
||||
@@ -1,10 +1,25 @@
|
||||
//! Finds the repos managed under the workspace root: `root/<repo>` or `root/<group>/<repo>`,
|
||||
//! where a repo has a `.bare` directory (bare + worktrees layout) or a `.git`.
|
||||
//! Finds the repos managed under the workspace root: `root/<group>/<repo>` for the configured
|
||||
//! groups, where the repo is in the bare + worktrees layout (has a `.bare` directory). Plain
|
||||
//! clones are never managed (they were not migrated with `grove add`); they are only reported.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn is_repo(p: &Path) -> bool {
|
||||
p.join(".bare").is_dir() || p.join(".git").exists()
|
||||
fn is_bare_layout(p: &Path) -> bool {
|
||||
p.join(".bare").is_dir()
|
||||
}
|
||||
|
||||
/// A linked worktree (`.git` file pointing into `<repo>/.git/worktrees/<id>`) belongs to the repo
|
||||
/// it was added from; treating it as a repo of its own would sync the same worktrees twice.
|
||||
fn is_linked_worktree(p: &Path) -> bool {
|
||||
std::fs::read_to_string(p.join(".git")).is_ok_and(|s| {
|
||||
s.trim()
|
||||
.strip_prefix("gitdir:")
|
||||
.is_some_and(|g| g.trim().contains("/worktrees/"))
|
||||
})
|
||||
}
|
||||
|
||||
fn is_plain_clone(p: &Path) -> bool {
|
||||
!is_bare_layout(p) && p.join(".git").exists() && !is_linked_worktree(p)
|
||||
}
|
||||
|
||||
fn subdirs(p: &Path) -> Vec<PathBuf> {
|
||||
@@ -20,16 +35,37 @@ fn subdirs(p: &Path) -> Vec<PathBuf> {
|
||||
v
|
||||
}
|
||||
|
||||
pub fn discover(root: &Path) -> Vec<PathBuf> {
|
||||
let mut out = Vec::new();
|
||||
for child in subdirs(root) {
|
||||
if is_repo(&child) {
|
||||
out.push(child);
|
||||
} else {
|
||||
out.extend(subdirs(&child).into_iter().filter(|g| is_repo(g)));
|
||||
/// What lives under the root, as far as the daemon is concerned.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct Discovery {
|
||||
/// Bare-layout repos in configured groups: these are synced.
|
||||
pub managed: Vec<PathBuf>,
|
||||
/// Plain clones in configured groups: ignored, reported as "not migrated".
|
||||
pub not_migrated: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
/// Looks only at `root/<group>/<repo>` for each name in `groups` (cheap: one `read_dir` per
|
||||
/// group). Directories that are not configured groups are never entered.
|
||||
pub fn discover(root: &Path, groups: &[String]) -> Discovery {
|
||||
let mut d = Discovery::default();
|
||||
let mut groups: Vec<&String> = groups.iter().collect();
|
||||
groups.sort();
|
||||
groups.dedup();
|
||||
for g in groups {
|
||||
for repo in subdirs(&root.join(g)) {
|
||||
if is_bare_layout(&repo) {
|
||||
d.managed.push(repo);
|
||||
} else if is_plain_clone(&repo) {
|
||||
d.not_migrated.push(repo);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
d
|
||||
}
|
||||
|
||||
/// The group a managed repo belongs to: the name of its parent directory.
|
||||
pub fn group_of(repo: &Path) -> Option<String> {
|
||||
Some(repo.parent()?.file_name()?.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -37,23 +73,38 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn finds_repos_at_depth_one_and_two_and_skips_hidden() {
|
||||
fn only_bare_layout_repos_in_configured_groups_are_managed() {
|
||||
let base = std::env::temp_dir().join(format!("grove-disc-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
for d in [
|
||||
"a/.git",
|
||||
"grp/b/.bare",
|
||||
"grp/plain",
|
||||
".hidden/.git",
|
||||
"c/inner/.git",
|
||||
"grp/migrated/.bare",
|
||||
"grp/plain/.git",
|
||||
"grp/.hidden/.bare",
|
||||
"grp/notarepo/x",
|
||||
"other/b/.bare",
|
||||
"other/c/.git",
|
||||
"rootclone/.git",
|
||||
"rootbare/.bare",
|
||||
".dot/b/.bare",
|
||||
"grp2/nested/deeper/.bare",
|
||||
"grp/migrated/main",
|
||||
] {
|
||||
std::fs::create_dir_all(base.join(d)).unwrap();
|
||||
}
|
||||
let found = discover(&base);
|
||||
assert_eq!(
|
||||
found,
|
||||
vec![base.join("a"), base.join("c/inner"), base.join("grp/b")]
|
||||
// A linked worktree sitting next to its repo is neither managed nor "not migrated".
|
||||
std::fs::create_dir_all(base.join("grp/migrated-feature")).unwrap();
|
||||
std::fs::write(
|
||||
base.join("grp/migrated-feature/.git"),
|
||||
"gitdir: /x/grp/migrated/.bare/worktrees/migrated-feature\n",
|
||||
)
|
||||
.unwrap();
|
||||
let found = discover(
|
||||
&base,
|
||||
&["grp".to_string(), "grp2".to_string(), "absent".into()],
|
||||
);
|
||||
assert_eq!(found.managed, vec![base.join("grp/migrated")]);
|
||||
assert_eq!(found.not_migrated, vec![base.join("grp/plain")]);
|
||||
assert_eq!(group_of(&base.join("grp/migrated")).as_deref(), Some("grp"));
|
||||
std::fs::remove_dir_all(&base).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -160,6 +160,7 @@ fn handle(req: &Request, ctx: &Ctx) -> Value {
|
||||
"last_sync": r.last_sync,
|
||||
"last_error": r.last_error,
|
||||
"failures": r.failures,
|
||||
"snapshots_withheld": r.snapshots_withheld,
|
||||
"worktrees": r.worktrees.iter()
|
||||
.map(|w| json!({"branch": w.branch, "state": w.state, "path": w.path}))
|
||||
.collect::<Vec<_>>(),
|
||||
@@ -167,7 +168,8 @@ fn handle(req: &Request, ctx: &Ctx) -> Value {
|
||||
})
|
||||
.collect();
|
||||
ok(
|
||||
json!({"machine": ctx.machine, "paused": s.paused, "now": now_secs(), "repos": repos}),
|
||||
json!({"machine": ctx.machine, "paused": s.paused, "now": now_secs(), "repos": repos,
|
||||
"not_migrated": s.not_migrated.iter().map(|p| p.display().to_string()).collect::<Vec<_>>()}),
|
||||
)
|
||||
}
|
||||
"pause" | "resume" => {
|
||||
|
||||
@@ -6,6 +6,7 @@ pub mod activity;
|
||||
pub mod daemon;
|
||||
pub mod discover;
|
||||
pub mod ipc;
|
||||
pub mod visibility;
|
||||
|
||||
pub use activity::{Activity, Event};
|
||||
pub use daemon::{Daemon, Settings};
|
||||
@@ -0,0 +1,803 @@
|
||||
//! Snapshot privacy: WIP snapshots hold uncommitted work, so under the default `private-only`
|
||||
//! policy they are pushed only when EVERY place the push can reach is known to be private: all
|
||||
//! push URLs of `origin` (pushurl, several urls, pushInsteadOf) and the repo's mirror targets
|
||||
//! configured for its group (forge-side push/pull mirrors copy `refs/sync/*` too). Anything
|
||||
//! unknown (no or several matching providers, no token, network error, odd answer) counts as
|
||||
//! public.
|
||||
//!
|
||||
//! Answers are cached in `<state dir>/visibility.json` (mode 0600). A "private" answer is trusted
|
||||
//! for [`PRIVATE_TTL`] only; failed lookups are retried at most every [`RETRY`] seconds.
|
||||
//! Residual risk: mirrors made by hand outside grove's config are not known to the daemon.
|
||||
|
||||
use grove_core::config::{Config, Provider as ProviderCfg, ProviderKind, SnapshotPolicy};
|
||||
use grove_core::git::Git;
|
||||
use grove_core::sync::git_dir_for;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// How long a "private" answer is trusted (a repo can be made public at any time).
|
||||
pub const PRIVATE_TTL: u64 = 3600;
|
||||
/// How long a "not private" answer (which only withholds) is trusted.
|
||||
pub const OTHER_TTL: u64 = 6 * 3600;
|
||||
/// Minimum wait before asking the forge again after a failed lookup.
|
||||
pub const RETRY: u64 = 300;
|
||||
|
||||
/// A parsed remote URL.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RepoId {
|
||||
pub host: String,
|
||||
/// Explicit port, if any.
|
||||
pub port: Option<u16>,
|
||||
/// `http`, `https` or `ssh` (scp-like URLs are `ssh`).
|
||||
pub scheme: String,
|
||||
/// Path segments before `owner` (a forge installed under a sub-path).
|
||||
pub prefix: Vec<String>,
|
||||
pub owner: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
/// Parses `https://host[:port]/owner/repo(.git)`, `ssh://git@host[:port]/owner/repo` and the
|
||||
/// scp-like `git@host:owner/repo.git`. The last two path segments are owner and name.
|
||||
pub fn parse_remote(url: &str) -> Option<RepoId> {
|
||||
let url = url.trim();
|
||||
let (scheme, authority, path) = match url.split_once("://") {
|
||||
Some((s, rest)) => {
|
||||
let (a, p) = rest.split_once('/')?;
|
||||
(s.to_ascii_lowercase(), a, p)
|
||||
}
|
||||
None => {
|
||||
let (a, p) = url.split_once(':')?;
|
||||
("ssh".to_string(), a, p)
|
||||
}
|
||||
};
|
||||
let hostport = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
|
||||
let (host, port) = match hostport.strip_prefix('[') {
|
||||
Some(v6) => {
|
||||
let (h, rest) = v6.split_once(']')?;
|
||||
(h, rest.strip_prefix(':').and_then(|p| p.parse().ok()))
|
||||
}
|
||||
None => match hostport.split_once(':') {
|
||||
Some((h, p)) if scheme != "ssh" || url.contains("://") => (h, p.parse().ok()),
|
||||
Some((h, _)) => (h, None),
|
||||
None => (hostport, None),
|
||||
},
|
||||
};
|
||||
let mut segs: Vec<&str> = path
|
||||
.split(['?', '#'])
|
||||
.next()?
|
||||
.split('/')
|
||||
.filter(|s| !s.is_empty())
|
||||
.collect();
|
||||
let last = segs.pop()?;
|
||||
let name = last.strip_suffix(".git").unwrap_or(last);
|
||||
let owner = segs.pop()?;
|
||||
if host.is_empty() || name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(RepoId {
|
||||
host: host.to_ascii_lowercase(),
|
||||
port,
|
||||
scheme,
|
||||
prefix: segs.iter().map(|s| s.to_string()).collect(),
|
||||
owner: owner.to_string(),
|
||||
name: name.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
fn default_port(scheme: &str) -> Option<u16> {
|
||||
match scheme {
|
||||
"http" => Some(80),
|
||||
"https" => Some(443),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the provider `cfg` serves the repo behind `id`: same host, same port (http/https
|
||||
/// only: an ssh port says nothing about the web port), and the provider's URL path is a prefix
|
||||
/// of the repo path (not checked for GitHub, whose API URL differs from its clone URL).
|
||||
fn serves(cfg: &ProviderCfg, id: &RepoId) -> bool {
|
||||
let url = cfg.url.as_deref().map(str::trim).filter(|u| !u.is_empty());
|
||||
let (scheme, authority, path) = match url {
|
||||
None => {
|
||||
return cfg.kind == ProviderKind::Github
|
||||
&& id.host == "github.com"
|
||||
&& (id.scheme == "ssh"
|
||||
|| id.port.is_none_or(|p| Some(p) == default_port(&id.scheme)));
|
||||
}
|
||||
Some(u) => match u.split_once("://") {
|
||||
Some((s, r)) => {
|
||||
let (a, p) = r.split_once('/').unwrap_or((r, ""));
|
||||
(s.to_ascii_lowercase(), a, p)
|
||||
}
|
||||
None => ("https".to_string(), u, ""),
|
||||
},
|
||||
};
|
||||
let hostport = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
|
||||
let (host, port) = match hostport.split_once(':') {
|
||||
Some((h, p)) => (h, p.parse::<u16>().ok()),
|
||||
None => (hostport, None),
|
||||
};
|
||||
let mut host = host.to_ascii_lowercase();
|
||||
if cfg.kind == ProviderKind::Github {
|
||||
host = host.strip_prefix("api.").unwrap_or(&host).to_string();
|
||||
}
|
||||
if host != id.host {
|
||||
return false;
|
||||
}
|
||||
if id.scheme != "ssh" {
|
||||
let mine = port.or(default_port(&scheme));
|
||||
let theirs = id.port.or(default_port(&id.scheme));
|
||||
if mine != theirs {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if cfg.kind == ProviderKind::Github || id.scheme == "ssh" {
|
||||
return true;
|
||||
}
|
||||
let want: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
|
||||
id.prefix.len() >= want.len() && id.prefix.iter().zip(&want).all(|(a, b)| a == b)
|
||||
}
|
||||
|
||||
/// The one configured provider (id and config) that serves `id`. Zero or several matches are an
|
||||
/// error: with several candidates the repo's visibility cannot be told.
|
||||
pub fn provider_for<'a>(
|
||||
cfg: &'a Config,
|
||||
id: &RepoId,
|
||||
) -> Result<(&'a str, &'a ProviderCfg), String> {
|
||||
let mut hits = cfg.providers.iter().filter(|(_, p)| serves(p, id));
|
||||
match (hits.next(), hits.next()) {
|
||||
(Some((i, p)), None) => Ok((i.as_str(), p)),
|
||||
(None, _) => Err(format!("no configured provider for host {}", id.host)),
|
||||
_ => Err(format!("several providers match host {}", id.host)),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Verdict {
|
||||
Private,
|
||||
Public,
|
||||
/// Could not be determined; treated as public. Carries the reason.
|
||||
Unknown(String),
|
||||
}
|
||||
|
||||
/// What a forge says about one repo.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Seen {
|
||||
Private,
|
||||
NotPrivate,
|
||||
/// 404: no such repo (or not visible to the token, so not public either).
|
||||
Absent,
|
||||
}
|
||||
|
||||
/// The forge lookups the daemon needs; faked in tests.
|
||||
pub trait Forge {
|
||||
fn seen(&self, id: &str, pc: &ProviderCfg, owner: &str, name: &str) -> Result<Seen, String>;
|
||||
/// The login the token belongs to (owner of repos without an `owners` entry).
|
||||
fn login(&self, id: &str, pc: &ProviderCfg) -> Result<String, String>;
|
||||
}
|
||||
|
||||
/// The real forges: token via `token::resolve` (grove login, Secret Service, tea/gh).
|
||||
pub struct RealForge;
|
||||
|
||||
impl RealForge {
|
||||
fn provider(id: &str, pc: &ProviderCfg) -> Result<Box<dyn grove_providers::Provider>, String> {
|
||||
let (token, _) = grove_providers::token::resolve(id, pc).map_err(|e| e.to_string())?;
|
||||
Ok(grove_providers::build(pc, token))
|
||||
}
|
||||
}
|
||||
|
||||
impl Forge for RealForge {
|
||||
fn seen(&self, id: &str, pc: &ProviderCfg, owner: &str, name: &str) -> Result<Seen, String> {
|
||||
match Self::provider(id, pc)?.get_repo(owner, name) {
|
||||
Ok(r) if r.private => Ok(Seen::Private),
|
||||
Ok(_) => Ok(Seen::NotPrivate),
|
||||
Err(grove_providers::Error::Api { status: 404, .. }) => Ok(Seen::Absent),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn login(&self, id: &str, pc: &ProviderCfg) -> Result<String, String> {
|
||||
Self::provider(id, pc)?
|
||||
.test_connection()
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
struct Entry {
|
||||
seen: Seen,
|
||||
checked: u64,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
/// A timestamp in the future (clock change, hand-edited file) counts as expired.
|
||||
fn fresh(&self, now: u64) -> bool {
|
||||
// Only a restrictive answer may live long; "private" and "absent" both permit pushes.
|
||||
let ttl = match self.seen {
|
||||
Seen::NotPrivate => OTHER_TTL,
|
||||
Seen::Private | Seen::Absent => PRIVATE_TTL,
|
||||
};
|
||||
self.checked <= now && now - self.checked < ttl
|
||||
}
|
||||
}
|
||||
|
||||
/// Visibility cache. Owned by the daemon's single worker thread.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Visibility {
|
||||
path: Option<PathBuf>,
|
||||
entries: BTreeMap<String, Entry>,
|
||||
failed: HashMap<String, (u64, String)>,
|
||||
logins: HashMap<String, String>,
|
||||
}
|
||||
|
||||
impl Visibility {
|
||||
/// Loads the cache from `path` (an unreadable or corrupt file is an empty cache).
|
||||
pub fn load(path: Option<PathBuf>) -> Visibility {
|
||||
let entries = path
|
||||
.as_deref()
|
||||
.and_then(|p| std::fs::read_to_string(p).ok())
|
||||
.and_then(|t| serde_json::from_str(&t).ok())
|
||||
.unwrap_or_default();
|
||||
Visibility {
|
||||
path,
|
||||
entries,
|
||||
..Visibility::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn save(&self) {
|
||||
use std::io::Write;
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
let Some(path) = &self.path else { return };
|
||||
if let Some(dir) = path.parent() {
|
||||
let _ = std::fs::create_dir_all(dir);
|
||||
}
|
||||
let tmp = path.with_extension("json.tmp");
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
let Ok(text) = serde_json::to_string_pretty(&self.entries) else {
|
||||
return;
|
||||
};
|
||||
let written = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.mode(0o600)
|
||||
.open(&tmp)
|
||||
.and_then(|mut f| f.write_all(text.as_bytes()));
|
||||
if written.is_ok() {
|
||||
let _ = std::fs::rename(&tmp, path);
|
||||
}
|
||||
}
|
||||
|
||||
/// What the forge says about `owner/name` on provider `pid`, from the cache or the forge.
|
||||
fn seen(
|
||||
&mut self,
|
||||
pid: &str,
|
||||
pc: &ProviderCfg,
|
||||
owner: &str,
|
||||
name: &str,
|
||||
now: u64,
|
||||
forge: &dyn Forge,
|
||||
) -> Result<Seen, String> {
|
||||
let url = pc.url.as_deref().unwrap_or_default().trim_end_matches('/');
|
||||
let key = format!("{pid}|{url}|{owner}/{name}").to_ascii_lowercase();
|
||||
if let Some(e) = self.entries.get(&key)
|
||||
&& e.fresh(now)
|
||||
{
|
||||
return Ok(e.seen);
|
||||
}
|
||||
if let Some((at, why)) = self.failed.get(&key)
|
||||
&& at.saturating_sub(0) <= now
|
||||
&& now - at < RETRY
|
||||
{
|
||||
return Err(why.clone());
|
||||
}
|
||||
match forge.seen(pid, pc, owner, name) {
|
||||
Ok(seen) => {
|
||||
self.failed.remove(&key);
|
||||
self.entries.insert(key, Entry { seen, checked: now });
|
||||
self.save();
|
||||
Ok(seen)
|
||||
}
|
||||
Err(why) => {
|
||||
let why = format!("lookup on {pid:?} failed: {why}");
|
||||
self.failed.insert(key, (now, why.clone()));
|
||||
Err(why)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Visibility of the repo behind one push URL.
|
||||
pub fn check_url(&mut self, cfg: &Config, url: &str, now: u64, forge: &dyn Forge) -> Verdict {
|
||||
let Some(id) = parse_remote(url) else {
|
||||
return Verdict::Unknown("push URL not understood".into());
|
||||
};
|
||||
let (pid, pc) = match provider_for(cfg, &id) {
|
||||
Ok(x) => x,
|
||||
Err(e) => return Verdict::Unknown(e),
|
||||
};
|
||||
match self.seen(pid, pc, &id.owner, &id.name, now, forge) {
|
||||
Ok(Seen::Private) => Verdict::Private,
|
||||
Ok(Seen::NotPrivate) => Verdict::Public,
|
||||
Ok(Seen::Absent) => Verdict::Unknown(format!("repo not found on {pid:?}")),
|
||||
Err(why) => Verdict::Unknown(why),
|
||||
}
|
||||
}
|
||||
|
||||
/// Mirror target `name` on provider `pid`: `Ok` when it is private or does not exist.
|
||||
fn check_mirror(
|
||||
&mut self,
|
||||
cfg: &Config,
|
||||
group: &str,
|
||||
pid: &str,
|
||||
name: &str,
|
||||
now: u64,
|
||||
forge: &dyn Forge,
|
||||
) -> Result<(), String> {
|
||||
let pc = cfg
|
||||
.providers
|
||||
.get(pid)
|
||||
.ok_or_else(|| format!("unknown mirror provider {pid:?}"))?;
|
||||
let owner = match cfg
|
||||
.groups
|
||||
.iter()
|
||||
.find(|g| g.name == group)
|
||||
.and_then(|g| g.owner(pid))
|
||||
{
|
||||
Some(o) => o.to_string(),
|
||||
None => match self.logins.get(pid) {
|
||||
Some(l) => l.clone(),
|
||||
None => {
|
||||
let l = forge
|
||||
.login(pid, pc)
|
||||
.map_err(|e| format!("mirror on {pid:?}: cannot get login: {e}"))?;
|
||||
self.logins.insert(pid.to_string(), l.clone());
|
||||
l
|
||||
}
|
||||
},
|
||||
};
|
||||
match self.seen(pid, pc, &owner, name, now, forge) {
|
||||
Ok(Seen::NotPrivate) => Err(format!("mirror {pid}:{owner}/{name} is public")),
|
||||
Ok(_) => Ok(()),
|
||||
Err(why) => Err(format!("mirror {pid}:{owner}/{name}: {why}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Policy decision: `Ok(())` to push snapshots, `Err(reason)` to withhold them. Unknown
|
||||
/// visibility counts as public.
|
||||
pub fn decide(policy: SnapshotPolicy, verdict: impl FnOnce() -> Verdict) -> Result<(), String> {
|
||||
match policy {
|
||||
SnapshotPolicy::All => Ok(()),
|
||||
SnapshotPolicy::None => Err("snapshots = \"none\"".into()),
|
||||
SnapshotPolicy::PrivateOnly => match verdict() {
|
||||
Verdict::Private => Ok(()),
|
||||
Verdict::Public => Err("repo is public (snapshots = \"private-only\")".into()),
|
||||
Verdict::Unknown(why) => Err(format!(
|
||||
"visibility unknown, treated as public ({why}; snapshots = \"private-only\")"
|
||||
)),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Where `git push <remote>` goes: `git remote get-url --push --all` honours `pushurl`, several
|
||||
/// urls and `pushInsteadOf`.
|
||||
fn push_urls(repo: &Path, remote: &str) -> Vec<String> {
|
||||
Git::new(git_dir_for(repo))
|
||||
.run(&["remote", "get-url", "--push", "--all", remote])
|
||||
.map(|o| o.lines().map(|l| l.trim().to_string()).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether the daemon may push WIP snapshots of `repo` (a bare-layout repo in a group).
|
||||
pub fn snapshot_gate(
|
||||
cfg: &Config,
|
||||
repo: &Path,
|
||||
remote: &str,
|
||||
vis: &mut Visibility,
|
||||
now: u64,
|
||||
forge: &dyn Forge,
|
||||
) -> Result<(), String> {
|
||||
let group = crate::discover::group_of(repo).unwrap_or_default();
|
||||
let mut name = None;
|
||||
decide(cfg.snapshot_policy(&group), || {
|
||||
let urls = push_urls(repo, remote);
|
||||
if urls.is_empty() {
|
||||
return Verdict::Unknown(format!("no push URL for {remote}"));
|
||||
}
|
||||
for u in &urls {
|
||||
match vis.check_url(cfg, u, now, forge) {
|
||||
Verdict::Private => {}
|
||||
other => return other,
|
||||
}
|
||||
}
|
||||
name = parse_remote(&urls[0]).map(|i| i.name);
|
||||
Verdict::Private
|
||||
})?;
|
||||
if cfg.snapshot_policy(&group) != SnapshotPolicy::PrivateOnly {
|
||||
return Ok(());
|
||||
}
|
||||
// Forge-side mirrors copy refs/sync/* to their targets, which must be private too.
|
||||
let Some(name) = name else {
|
||||
return Err("repo name unknown".into());
|
||||
};
|
||||
let Some(g) = cfg.groups.iter().find(|g| g.name == group) else {
|
||||
return Ok(());
|
||||
};
|
||||
let mut targets: Vec<String> = [g.route(true), g.route(false)]
|
||||
.into_iter()
|
||||
.flat_map(|r| r.mirror_to)
|
||||
.collect();
|
||||
targets.sort();
|
||||
targets.dedup();
|
||||
for pid in targets {
|
||||
vis.check_mirror(cfg, &group, &pid, &name, now, forge)
|
||||
.map_err(|e| format!("{e} (snapshots = \"private-only\")"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::{Cell, RefCell};
|
||||
|
||||
/// Scripted forge: answers by `owner/name` (lowercase); anything else is an error.
|
||||
#[derive(Default)]
|
||||
struct Fake {
|
||||
repos: HashMap<String, Result<Seen, String>>,
|
||||
calls: Cell<u32>,
|
||||
asked: RefCell<Vec<String>>,
|
||||
}
|
||||
|
||||
impl Fake {
|
||||
fn with(mut self, key: &str, v: Result<Seen, &str>) -> Fake {
|
||||
self.repos.insert(key.into(), v.map_err(str::to_string));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Forge for Fake {
|
||||
fn seen(&self, id: &str, _: &ProviderCfg, owner: &str, name: &str) -> Result<Seen, String> {
|
||||
self.calls.set(self.calls.get() + 1);
|
||||
let key = format!("{owner}/{name}").to_ascii_lowercase();
|
||||
self.asked.borrow_mut().push(format!("{id}:{key}"));
|
||||
self.repos
|
||||
.get(&key)
|
||||
.cloned()
|
||||
.unwrap_or(Err("no such fake".into()))
|
||||
}
|
||||
fn login(&self, _: &str, _: &ProviderCfg) -> Result<String, String> {
|
||||
Ok("me".into())
|
||||
}
|
||||
}
|
||||
|
||||
fn cfg() -> Config {
|
||||
Config::parse(
|
||||
r#"
|
||||
[machine]
|
||||
name = "m"
|
||||
[root]
|
||||
path = "/x"
|
||||
[providers.gitea]
|
||||
kind = "gitea"
|
||||
url = "https://Git.Example.com:3000/"
|
||||
[providers.github]
|
||||
kind = "github"
|
||||
[[groups]]
|
||||
name = "priv"
|
||||
primary = "gitea"
|
||||
[[groups]]
|
||||
name = "all"
|
||||
primary = "gitea"
|
||||
snapshots = "all"
|
||||
[[groups]]
|
||||
name = "off"
|
||||
primary = "gitea"
|
||||
snapshots = "none"
|
||||
[[groups]]
|
||||
name = "mir"
|
||||
primary = "gitea"
|
||||
mirror_to = ["github"]
|
||||
owners = { github = "gh-org" }
|
||||
"#,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_remote_url_forms() {
|
||||
let r = |s: &str| parse_remote(s).unwrap();
|
||||
let a = r("https://github.com/Org/repo.git");
|
||||
assert_eq!(
|
||||
(a.host.as_str(), a.owner.as_str(), a.name.as_str()),
|
||||
("github.com", "Org", "repo")
|
||||
);
|
||||
assert_eq!(a.port, None);
|
||||
let b = r("git@GitHub.com:Org/repo.git");
|
||||
assert_eq!(
|
||||
(b.host.as_str(), b.scheme.as_str(), b.port),
|
||||
("github.com", "ssh", None)
|
||||
);
|
||||
let c = r("ssh://git@git.example.com:2222/o/r");
|
||||
assert_eq!((c.host.as_str(), c.port), ("git.example.com", Some(2222)));
|
||||
let d = r("https://u:p@h.io:3000/sub/o/r.git/");
|
||||
assert_eq!(
|
||||
(d.port, d.prefix.clone(), d.owner.as_str()),
|
||||
(Some(3000), vec!["sub".to_string()], "o")
|
||||
);
|
||||
assert!(parse_remote("/local/path/repo.git").is_none());
|
||||
assert!(parse_remote("https://host/onlyone").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_providers_by_host_port_and_path_prefix() {
|
||||
let c = cfg();
|
||||
let m = |u: &str| provider_for(&c, &parse_remote(u).unwrap()).map(|(i, _)| i.to_string());
|
||||
assert_eq!(m("https://git.example.com:3000/o/r").unwrap(), "gitea");
|
||||
assert_eq!(m("ssh://git@git.example.com:22/o/r").unwrap(), "gitea");
|
||||
assert_eq!(m("git@git.example.com:o/r.git").unwrap(), "gitea");
|
||||
assert!(m("https://git.example.com/o/r").is_err(), "other web port");
|
||||
assert_eq!(m("https://github.com/o/r").unwrap(), "github");
|
||||
assert_eq!(m("git@github.com:o/r.git").unwrap(), "github");
|
||||
assert!(m("https://gitlab.com/o/r").is_err());
|
||||
|
||||
let sub = Config::parse(
|
||||
"[machine]\nname=\"m\"\n[root]\npath=\"/x\"\n[providers.a]\nkind=\"gitea\"\nurl=\"https://h.io/a\"\n[providers.b]\nkind=\"gitea\"\nurl=\"https://h.io/b\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
let m = |u: &str| provider_for(&sub, &parse_remote(u).unwrap()).map(|(i, _)| i.to_string());
|
||||
assert_eq!(m("https://h.io/a/o/r").unwrap(), "a");
|
||||
assert_eq!(m("https://h.io/b/o/r").unwrap(), "b");
|
||||
assert!(m("https://h.io/o/r").is_err());
|
||||
|
||||
// Two providers for the same host: ambiguous, so unknown.
|
||||
let dup = Config::parse(
|
||||
"[machine]\nname=\"m\"\n[root]\npath=\"/x\"\n[providers.a]\nkind=\"gitea\"\nurl=\"https://h.io\"\n[providers.b]\nkind=\"forgejo\"\nurl=\"https://h.io\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
let e = provider_for(&dup, &parse_remote("https://h.io/o/r").unwrap()).unwrap_err();
|
||||
assert!(e.contains("several"));
|
||||
let mut v = Visibility::default();
|
||||
let fake = Fake::default().with("o/r", Ok(Seen::Private));
|
||||
assert!(matches!(
|
||||
v.check_url(&dup, "https://h.io/o/r", 0, &fake),
|
||||
Verdict::Unknown(_)
|
||||
));
|
||||
assert_eq!(fake.calls.get(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_visibility_is_public_and_withholds_snapshots() {
|
||||
let c = cfg();
|
||||
let mut v = Visibility::default();
|
||||
let boom = Fake::default();
|
||||
for url in [
|
||||
"https://gitlab.com/o/r.git",
|
||||
"/some/path",
|
||||
"https://github.com/o/r",
|
||||
] {
|
||||
let verdict = v.check_url(&c, url, 1000, &boom);
|
||||
assert!(matches!(verdict, Verdict::Unknown(_)), "{url}: {verdict:?}");
|
||||
assert!(decide(SnapshotPolicy::PrivateOnly, || verdict).is_err());
|
||||
}
|
||||
let f = Fake::default()
|
||||
.with("o/pub", Ok(Seen::NotPrivate))
|
||||
.with("o/priv", Ok(Seen::Private))
|
||||
.with("o/gone", Ok(Seen::Absent));
|
||||
let p = v.check_url(&c, "https://github.com/o/pub", 1000, &f);
|
||||
assert_eq!(p, Verdict::Public);
|
||||
assert!(decide(SnapshotPolicy::PrivateOnly, || p).is_err());
|
||||
let q = v.check_url(&c, "https://github.com/o/priv", 1000, &f);
|
||||
assert_eq!(q, Verdict::Private);
|
||||
assert!(decide(SnapshotPolicy::PrivateOnly, || q).is_ok());
|
||||
assert!(matches!(
|
||||
v.check_url(&c, "https://github.com/o/gone", 1000, &f),
|
||||
Verdict::Unknown(_)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn policies_all_and_none_do_not_consult_the_forge() {
|
||||
let boom = || panic!("must not look up visibility");
|
||||
assert!(decide(SnapshotPolicy::All, boom).is_ok());
|
||||
assert!(decide(SnapshotPolicy::None, boom).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn private_answers_expire_after_an_hour_and_failures_are_throttled() {
|
||||
let c = cfg();
|
||||
let mut v = Visibility::default();
|
||||
let f = Fake::default().with("o/r", Ok(Seen::Private));
|
||||
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 + PRIVATE_TTL - 1, &f),
|
||||
Verdict::Private
|
||||
);
|
||||
assert_eq!(f.calls.get(), 1);
|
||||
assert_eq!(
|
||||
v.check_url(&c, url, 100 + PRIVATE_TTL, &f),
|
||||
Verdict::Private
|
||||
);
|
||||
assert_eq!(f.calls.get(), 2);
|
||||
// A timestamp from the future is expired.
|
||||
assert_eq!(v.check_url(&c, url, 50, &f), Verdict::Private);
|
||||
assert_eq!(f.calls.get(), 3);
|
||||
// A "not private" answer is kept longer.
|
||||
let f2 = Fake::default().with("o/p", Ok(Seen::NotPrivate));
|
||||
v.check_url(&c, "https://github.com/o/p", 0, &f2);
|
||||
v.check_url(&c, "https://github.com/o/p", OTHER_TTL - 1, &f2);
|
||||
assert_eq!(f2.calls.get(), 1);
|
||||
// An "absent" mirror answer permits pushing, so it gets the short TTL.
|
||||
let f3 = Fake::default().with("o/a", Ok(Seen::Absent));
|
||||
v.check_url(&c, "https://github.com/o/a", 0, &f3);
|
||||
v.check_url(&c, "https://github.com/o/a", PRIVATE_TTL, &f3);
|
||||
assert_eq!(f3.calls.get(), 2);
|
||||
// After the TTL a failing refresh does not fall back to the stale answer.
|
||||
let bad = Fake::default().with("o/r", Err("down"));
|
||||
let t = 100 + 10 * PRIVATE_TTL;
|
||||
assert!(matches!(v.check_url(&c, url, t, &bad), Verdict::Unknown(_)));
|
||||
assert!(matches!(
|
||||
v.check_url(&c, url, t + 1, &bad),
|
||||
Verdict::Unknown(_)
|
||||
));
|
||||
assert_eq!(bad.calls.get(), 1, "retry is throttled");
|
||||
assert!(matches!(
|
||||
v.check_url(&c, url, t + RETRY, &bad),
|
||||
Verdict::Unknown(_)
|
||||
));
|
||||
assert_eq!(bad.calls.get(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cache_keys_include_provider_and_are_case_normalised() {
|
||||
let c = cfg();
|
||||
let mut v = Visibility::default();
|
||||
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, "git@github.com:o/r", 0, &f);
|
||||
assert_eq!(f.calls.get(), 1);
|
||||
v.check_url(&c, "https://git.example.com:3000/o/r", 0, &f);
|
||||
assert_eq!(
|
||||
f.calls.get(),
|
||||
2,
|
||||
"same owner/name on another provider is another entry"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cache_persists_in_the_state_dir_with_mode_0600() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = std::env::temp_dir().join(format!("grove-vis-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let file = dir.join("visibility.json");
|
||||
let c = cfg();
|
||||
let f = Fake::default().with("o/r", Ok(Seen::NotPrivate));
|
||||
let mut v = Visibility::load(Some(file.clone()));
|
||||
assert_eq!(
|
||||
v.check_url(&c, "https://github.com/o/r", 50, &f),
|
||||
Verdict::Public
|
||||
);
|
||||
let mode = std::fs::metadata(&file).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(mode, 0o600);
|
||||
let never = Fake::default();
|
||||
let mut again = Visibility::load(Some(file));
|
||||
assert_eq!(
|
||||
again.check_url(&c, "https://github.com/o/r", 60, &never),
|
||||
Verdict::Public
|
||||
);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
fn mk(base: &Path, group: &str, urls: &[&str], push: &[&str]) -> PathBuf {
|
||||
let repo = base.join(group).join("r");
|
||||
let bare = repo.join(".bare");
|
||||
std::fs::create_dir_all(&bare).unwrap();
|
||||
let g = Git::new(&bare);
|
||||
g.run(&["init", "-q", "--bare"]).unwrap();
|
||||
for (i, u) in urls.iter().enumerate() {
|
||||
if i == 0 {
|
||||
g.run(&["remote", "add", "origin", u]).unwrap();
|
||||
} else {
|
||||
g.run(&["remote", "set-url", "--add", "origin", u]).unwrap();
|
||||
}
|
||||
}
|
||||
for u in push {
|
||||
g.run(&["remote", "set-url", "--push", "--add", "origin", u])
|
||||
.unwrap();
|
||||
}
|
||||
repo
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gate_uses_group_policy_and_every_push_url() {
|
||||
let c = cfg();
|
||||
let base = std::env::temp_dir().join(format!("grove-gate-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let f = Fake::default()
|
||||
.with("o/r", Ok(Seen::Private))
|
||||
.with("o/open", Ok(Seen::NotPrivate));
|
||||
let mut v = Visibility::default();
|
||||
let gate = |repo: &Path, v: &mut Visibility| snapshot_gate(&c, repo, "origin", v, 0, &f);
|
||||
let ok = "https://git.example.com:3000/o/r.git";
|
||||
assert!(gate(&mk(&base, "priv", &[ok], &[]), &mut v).is_ok());
|
||||
assert!(gate(&mk(&base, "off", &[ok], &[]), &mut v).is_err());
|
||||
assert!(
|
||||
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).
|
||||
let e = gate(
|
||||
&mk(&base, "priv2", &[ok], &["https://github.com/o/open"]),
|
||||
&mut v,
|
||||
);
|
||||
assert!(e.is_err());
|
||||
// Private-only without any remote: unknown, withheld.
|
||||
let bare = base.join("priv/none/.bare");
|
||||
std::fs::create_dir_all(&bare).unwrap();
|
||||
Git::new(&bare).run(&["init", "-q", "--bare"]).unwrap();
|
||||
assert!(
|
||||
gate(&base.join("priv/none"), &mut v)
|
||||
.unwrap_err()
|
||||
.contains("unknown")
|
||||
);
|
||||
std::fs::remove_dir_all(&base).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gate_checks_all_push_urls_and_push_instead_of() {
|
||||
let c = cfg();
|
||||
let base = std::env::temp_dir().join(format!("grove-gate2-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let f = Fake::default()
|
||||
.with("o/r", Ok(Seen::Private))
|
||||
.with("o/open", Ok(Seen::NotPrivate));
|
||||
let mut v = Visibility::default();
|
||||
let ok = "https://git.example.com:3000/o/r.git";
|
||||
let open = "https://github.com/o/open";
|
||||
// Group "priv": private fetch URL + public pushurl => withheld; both private => allowed.
|
||||
let both = mk(&base, "priv", &[ok], &[ok, "https://github.com/o/r"]);
|
||||
assert!(snapshot_gate(&c, &both, "origin", &mut v, 0, &f).is_ok());
|
||||
std::fs::remove_dir_all(base.join("priv")).unwrap();
|
||||
let leaky = mk(&base, "priv", &[ok, open], &[]);
|
||||
let e = snapshot_gate(&c, &leaky, "origin", &mut v, 0, &f).unwrap_err();
|
||||
assert!(e.contains("public"), "{e}");
|
||||
// pushInsteadOf rewrites the push URL to a public repo.
|
||||
let g = Git::new(leaky.join(".bare"));
|
||||
g.run(&["remote", "set-url", "--delete", "origin", open])
|
||||
.unwrap();
|
||||
assert!(snapshot_gate(&c, &leaky, "origin", &mut v, 0, &f).is_ok());
|
||||
g.run(&["config", &format!("url.{open}.pushInsteadOf"), ok])
|
||||
.unwrap();
|
||||
assert!(snapshot_gate(&c, &leaky, "origin", &mut v, 0, &f).is_err());
|
||||
std::fs::remove_dir_all(&base).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gate_requires_mirror_targets_to_be_private_or_absent() {
|
||||
let c = cfg();
|
||||
let base = std::env::temp_dir().join(format!("grove-gate3-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let repo = mk(&base, "mir", &["https://git.example.com:3000/o/r.git"], &[]);
|
||||
let gate = |f: &Fake| {
|
||||
let mut v = Visibility::default();
|
||||
snapshot_gate(&c, &repo, "origin", &mut v, 0, f)
|
||||
};
|
||||
let base_f = || Fake::default().with("o/r", Ok(Seen::Private));
|
||||
// No mirror (404): fine. Mirror owner comes from `owners`.
|
||||
let f = base_f().with("gh-org/r", Ok(Seen::Absent));
|
||||
assert!(gate(&f).is_ok());
|
||||
assert!(f.asked.borrow().iter().any(|a| a == "github:gh-org/r"));
|
||||
assert!(gate(&base_f().with("gh-org/r", Ok(Seen::Private))).is_ok());
|
||||
let e = gate(&base_f().with("gh-org/r", Ok(Seen::NotPrivate))).unwrap_err();
|
||||
assert!(e.contains("mirror") && e.contains("public"), "{e}");
|
||||
let e = gate(&base_f().with("gh-org/r", Err("down"))).unwrap_err();
|
||||
assert!(e.contains("mirror"), "{e}");
|
||||
std::fs::remove_dir_all(&base).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -68,14 +68,40 @@ fn world(tag: &str, machines: &[&str]) -> World {
|
||||
for m in machines {
|
||||
let dir = base.join(m);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
git(&dir, &["clone", "-q", remote.to_str().unwrap(), "repo"]);
|
||||
bare_layout(&dir.join("g/repo"), &remote);
|
||||
}
|
||||
World { base, remote }
|
||||
}
|
||||
|
||||
/// A bare + worktrees repo (`.bare`, worktree `main`) cloned from `remote`, as `grove add` leaves it.
|
||||
fn bare_layout(repo: &Path, remote: &Path) {
|
||||
fs::create_dir_all(repo).unwrap();
|
||||
git(
|
||||
repo,
|
||||
&["clone", "-q", "--bare", remote.to_str().unwrap(), ".bare"],
|
||||
);
|
||||
let bare = repo.join(".bare");
|
||||
git(
|
||||
&bare,
|
||||
&[
|
||||
"config",
|
||||
"remote.origin.fetch",
|
||||
"+refs/heads/*:refs/remotes/origin/*",
|
||||
],
|
||||
);
|
||||
git(&bare, &["fetch", "-q", "origin"]);
|
||||
git(&bare, &["worktree", "add", "-q", "../main", "main"]);
|
||||
git(
|
||||
&repo.join("main"),
|
||||
&["branch", "-q", "--set-upstream-to=origin/main", "main"],
|
||||
);
|
||||
}
|
||||
|
||||
const GROUP: &str = "[providers.p]\nkind = \"gitea\"\nurl = \"https://git.example.invalid\"\n[[groups]]\nname = \"g\"\nprimary = \"p\"\n";
|
||||
|
||||
fn config(w: &World, machine: &str, debounce_ms: u64, fetch_s: u64) -> Config {
|
||||
Config::parse(&format!(
|
||||
"[machine]\nname = \"{machine}\"\n[root]\npath = \"{}\"\n[sync]\nsnapshot_debounce_ms = {debounce_ms}\nfetch_interval_s = {fetch_s}\n",
|
||||
"[machine]\nname = \"{machine}\"\n[root]\npath = \"{}\"\n{GROUP}[sync]\nsnapshots = \"all\"\nsnapshot_debounce_ms = {debounce_ms}\nfetch_interval_s = {fetch_s}\n",
|
||||
w.base.join(machine).display()
|
||||
))
|
||||
.unwrap()
|
||||
@@ -86,6 +112,7 @@ fn settings(w: &World, machine: &str) -> Settings {
|
||||
socket: w.base.join(format!("{machine}.sock")),
|
||||
activity_log: Some(w.base.join(format!("{machine}.jsonl"))),
|
||||
remote: "origin".into(),
|
||||
visibility_cache: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,20 +125,20 @@ fn edit_on_a_shows_up_on_b() {
|
||||
let w = world("converge", &["pca", "pcb"]);
|
||||
let a = start(&w, "pca");
|
||||
let b = start(&w, "pcb");
|
||||
let file_a = w.base.join("pca/repo/new.txt");
|
||||
let file_a = w.base.join("pca/g/repo/main/new.txt");
|
||||
fs::write(&file_a, "hello\n").unwrap();
|
||||
fs::write(w.base.join("pca/repo/a.txt"), "one\nedited\n").unwrap();
|
||||
let on_b = w.base.join("pcb/repo/new.txt");
|
||||
fs::write(w.base.join("pca/g/repo/main/a.txt"), "one\nedited\n").unwrap();
|
||||
let on_b = w.base.join("pcb/g/repo/main/new.txt");
|
||||
wait_until("new.txt on B", 30, || {
|
||||
fs::read_to_string(&on_b).is_ok_and(|s| s == "hello\n")
|
||||
});
|
||||
assert_eq!(
|
||||
fs::read_to_string(w.base.join("pcb/repo/a.txt")).unwrap(),
|
||||
fs::read_to_string(w.base.join("pcb/g/repo/main/a.txt")).unwrap(),
|
||||
"one\nedited\n"
|
||||
);
|
||||
// The user's branch on A was never touched by the daemon.
|
||||
assert_eq!(
|
||||
git(&w.base.join("pca/repo"), &["log", "--oneline"])
|
||||
git(&w.base.join("pca/g/repo/main"), &["log", "--oneline"])
|
||||
.lines()
|
||||
.count(),
|
||||
1
|
||||
@@ -125,12 +152,12 @@ fn committed_work_fast_forwards_the_other_machine() {
|
||||
let w = world("ff", &["pca", "pcb"]);
|
||||
let a = start(&w, "pca");
|
||||
let b = start(&w, "pcb");
|
||||
let ra = w.base.join("pca/repo");
|
||||
let ra = w.base.join("pca/g/repo/main");
|
||||
fs::write(ra.join("c.txt"), "committed\n").unwrap();
|
||||
git(&ra, &["add", "-A"]);
|
||||
git(&ra, &["commit", "-qm", "c"]);
|
||||
git(&ra, &["push", "-q", "origin", "main"]);
|
||||
let rb = w.base.join("pcb/repo");
|
||||
let rb = w.base.join("pcb/g/repo/main");
|
||||
wait_until("B fast-forwarded", 30, || rb.join("c.txt").exists());
|
||||
wait_until("B synced", 30, || {
|
||||
git(&rb, &["status", "--porcelain"]).is_empty()
|
||||
@@ -156,7 +183,7 @@ fn ipc_status_pause_resume_log_and_subscribe() {
|
||||
let unknown = ipc::request(&sock, &json!({"v":1,"cmd":"nope"})).unwrap();
|
||||
assert_eq!(unknown["ok"], false);
|
||||
|
||||
let repo = w.base.join("pca/repo");
|
||||
let repo = w.base.join("pca/g/repo/main");
|
||||
wait_until("status lists the repo", 10, || {
|
||||
let s = ipc::request(&sock, &json!({"v":1,"cmd":"status"})).unwrap();
|
||||
s["data"]["repos"].as_array().is_some_and(|r| r.len() == 1)
|
||||
@@ -234,12 +261,12 @@ fn second_daemon_on_same_socket_is_refused_and_stale_socket_is_reused() {
|
||||
#[test]
|
||||
fn killing_the_daemon_loses_nothing_and_a_restart_recovers() {
|
||||
let w = world("crash", &["pca"]);
|
||||
let repo = w.base.join("pca/repo");
|
||||
let repo = w.base.join("pca/g/repo/main");
|
||||
let cfg_path = w.base.join("config.toml");
|
||||
fs::write(
|
||||
&cfg_path,
|
||||
format!(
|
||||
"[machine]\nname = \"pca\"\n[root]\npath = \"{}\"\n[sync]\nsnapshot_debounce_ms = 50\nfetch_interval_s = 1\n",
|
||||
"[machine]\nname = \"pca\"\n[root]\npath = \"{}\"\n{GROUP}[sync]\nsnapshots = \"all\"\nsnapshot_debounce_ms = 50\nfetch_interval_s = 1\n",
|
||||
w.base.join("pca").display()
|
||||
),
|
||||
)
|
||||
@@ -269,7 +296,7 @@ fn killing_the_daemon_loses_nothing_and_a_restart_recovers() {
|
||||
"precious\n"
|
||||
);
|
||||
assert!(
|
||||
!repo.join(".git/index.lock").exists(),
|
||||
!repo.join("../.bare/worktrees/main/index.lock").exists(),
|
||||
"stale index.lock after kill"
|
||||
);
|
||||
git(&repo, &["fsck", "--no-dangling"]);
|
||||
@@ -292,8 +319,8 @@ fn work_in_progress_then_committed_on_a_leaves_b_clean() {
|
||||
let w = world("wipcommit", &["pca", "pcb"]);
|
||||
let a = start(&w, "pca");
|
||||
let b = start(&w, "pcb");
|
||||
let ra = w.base.join("pca/repo");
|
||||
let rb = w.base.join("pcb/repo");
|
||||
let ra = w.base.join("pca/g/repo/main");
|
||||
let rb = w.base.join("pcb/g/repo/main");
|
||||
fs::write(ra.join("w.txt"), "wip\n").unwrap();
|
||||
wait_until("WIP on B", 30, || rb.join("w.txt").exists());
|
||||
git(&ra, &["add", "-A"]);
|
||||
@@ -322,7 +349,7 @@ fn paused_daemon_does_not_spin() {
|
||||
fs::write(
|
||||
&cfg_path,
|
||||
format!(
|
||||
"[machine]\nname = \"pca\"\n[root]\npath = \"{}\"\n[sync]\nsnapshot_debounce_ms = 50\nfetch_interval_s = 1\n",
|
||||
"[machine]\nname = \"pca\"\n[root]\npath = \"{}\"\n{GROUP}[sync]\nsnapshots = \"all\"\nsnapshot_debounce_ms = 50\nfetch_interval_s = 1\n",
|
||||
w.base.join("pca").display()
|
||||
),
|
||||
)
|
||||
@@ -356,7 +383,7 @@ fn sync_accepts_a_non_canonical_repo_path_and_unknown_repos_are_rejected() {
|
||||
let st = settings(&w, "pca");
|
||||
let sock = st.socket.clone();
|
||||
let d = Daemon::start(config(&w, "pca", 200, 60), st).unwrap();
|
||||
let repo = w.base.join("pca/repo");
|
||||
let repo = w.base.join("pca/g/repo");
|
||||
wait_until("repo listed", 10, || {
|
||||
ipc::request(&sock, &json!({"v":1,"cmd":"status"})).unwrap()["data"]["repos"]
|
||||
.as_array()
|
||||
@@ -369,3 +396,134 @@ fn sync_accepts_a_non_canonical_repo_path_and_unknown_repos_are_rejected() {
|
||||
assert_eq!(bad["ok"], false);
|
||||
d.shutdown();
|
||||
}
|
||||
|
||||
fn status(sock: &Path) -> serde_json::Value {
|
||||
ipc::request(sock, &json!({"v":1,"cmd":"status"})).unwrap()["data"].clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_clones_and_non_group_dirs_are_ignored_and_reported() {
|
||||
let w = world("scope", &["pca"]);
|
||||
let root = w.base.join("pca");
|
||||
// A plain clone in the group, and a bare-layout repo in a directory that is no group.
|
||||
git(
|
||||
&root.join("g"),
|
||||
&["clone", "-q", w.remote.to_str().unwrap(), "plain"],
|
||||
);
|
||||
bare_layout(&root.join("nogroup/repo"), &w.remote);
|
||||
// Local work in the plain clone and the non-group repo must stay untouched and unsnapshotted.
|
||||
fs::write(root.join("g/plain/wip.txt"), "x\n").unwrap();
|
||||
fs::write(root.join("nogroup/repo/main/wip.txt"), "x\n").unwrap();
|
||||
let st = settings(&w, "pca");
|
||||
let sock = st.socket.clone();
|
||||
let d = Daemon::start(config(&w, "pca", 100, 1), st).unwrap();
|
||||
wait_until("managed repo listed", 10, || {
|
||||
status(&sock)["repos"]
|
||||
.as_array()
|
||||
.is_some_and(|r| r.len() == 1)
|
||||
});
|
||||
wait_until("plain clone reported", 10, || {
|
||||
status(&sock)["not_migrated"] == json!([root.join("g/plain").display().to_string()])
|
||||
});
|
||||
std::thread::sleep(Duration::from_secs(3));
|
||||
let s = status(&sock);
|
||||
assert_eq!(
|
||||
s["repos"][0]["path"],
|
||||
root.join("g/repo").display().to_string()
|
||||
);
|
||||
assert!(git(&root.join("g/plain"), &["for-each-ref", "refs/sync/"]).is_empty());
|
||||
assert!(
|
||||
git(
|
||||
&root.join("nogroup/repo/main"),
|
||||
&["for-each-ref", "refs/sync/"]
|
||||
)
|
||||
.is_empty()
|
||||
);
|
||||
assert!(git(&w.remote, &["for-each-ref", "refs/sync/"]).is_empty());
|
||||
d.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn private_only_withholds_snapshots_when_visibility_is_unknown() {
|
||||
let w = world("private", &["pca"]);
|
||||
// The provider host does not resolve and the origin is a local path: visibility is unknown.
|
||||
let text = format!(
|
||||
"[machine]\nname = \"pca\"\n[root]\npath = \"{}\"\n{GROUP}[sync]\nsnapshot_debounce_ms = 100\nfetch_interval_s = 1\n",
|
||||
w.base.join("pca").display()
|
||||
);
|
||||
let cfg = Config::parse(&text).unwrap();
|
||||
assert_eq!(
|
||||
cfg.sync.snapshots,
|
||||
grove_core::config::SnapshotPolicy::PrivateOnly
|
||||
);
|
||||
let st = settings(&w, "pca");
|
||||
let sock = st.socket.clone();
|
||||
let d = Daemon::start(cfg, st).unwrap();
|
||||
let repo = w.base.join("pca/g/repo/main");
|
||||
fs::write(repo.join("secret.txt"), "wip\n").unwrap();
|
||||
wait_until("withheld reported", 15, || {
|
||||
status(&sock)["repos"][0]["snapshots_withheld"]
|
||||
.as_str()
|
||||
.is_some_and(|m| m.contains("treated as public"))
|
||||
});
|
||||
std::thread::sleep(Duration::from_secs(2));
|
||||
assert!(git(&repo, &["for-each-ref", "refs/sync/"]).is_empty());
|
||||
assert!(git(&w.remote, &["for-each-ref", "refs/sync/"]).is_empty());
|
||||
let log = ipc::request(&sock, &json!({"v":1,"cmd":"log","limit":100})).unwrap();
|
||||
assert!(log["data"].to_string().contains("snapshots_withheld"));
|
||||
d.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_materialize_is_decided_per_group() {
|
||||
let w = world("nomat", &["pca"]);
|
||||
let text = format!(
|
||||
"[machine]\nname = \"pca\"\n[root]\npath = \"{}\"\n[providers.p]\nkind = \"gitea\"\n[[groups]]\nname = \"g\"\nprimary = \"p\"\n[[groups]]\nname = \"h\"\nprimary = \"p\"\nauto_materialize = false\n[sync]\nsnapshots = \"all\"\nfetch_interval_s = 1\n",
|
||||
w.base.join("pca").display()
|
||||
);
|
||||
let seed = w.base.join("seed");
|
||||
git(&seed, &["checkout", "-q", "-b", "feat/new"]);
|
||||
git(&seed, &["push", "-q", "origin", "feat/new"]);
|
||||
let st = settings(&w, "pca");
|
||||
let d = Daemon::start(Config::parse(&text).unwrap(), st).unwrap();
|
||||
let bare = w.base.join("pca/g/repo/.bare");
|
||||
// Another group turns materializing off; this repo's group keeps the default.
|
||||
wait_until("worktree for the new branch", 15, || {
|
||||
git(&bare, &["branch", "-r"]).contains("origin/feat/new")
|
||||
&& w.base.join("pca/g/repo/feat-new").exists()
|
||||
});
|
||||
d.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshots_already_pushed_are_deleted_when_they_become_withheld() {
|
||||
let w = world("purge", &["pca"]);
|
||||
let repo = w.base.join("pca/g/repo/main");
|
||||
// This machine pushed a snapshot earlier; another machine has one too.
|
||||
git(&repo, &["update-ref", "refs/sync/pca/main", "HEAD"]);
|
||||
git(
|
||||
&repo,
|
||||
&[
|
||||
"push",
|
||||
"-q",
|
||||
"origin",
|
||||
"refs/sync/pca/main:refs/sync/pca/main",
|
||||
],
|
||||
);
|
||||
git(&repo, &["push", "-q", "origin", "HEAD:refs/sync/pcb/main"]);
|
||||
let text = format!(
|
||||
"[machine]\nname = \"pca\"\n[root]\npath = \"{}\"\n{GROUP}[sync]\nfetch_interval_s = 1\n",
|
||||
w.base.join("pca").display()
|
||||
);
|
||||
let d = Daemon::start(Config::parse(&text).unwrap(), settings(&w, "pca")).unwrap();
|
||||
wait_until("own snapshot deleted remotely", 15, || {
|
||||
!git(&w.remote, &["for-each-ref", "refs/sync/pca/"]).contains("refs/sync/pca/main")
|
||||
});
|
||||
d.shutdown();
|
||||
let refs = git(&w.remote, &["for-each-ref", "--format=%(refname)"]);
|
||||
assert!(refs.contains("refs/sync/pcb/main"), "{refs}");
|
||||
assert!(refs.contains("refs/heads/main"), "{refs}");
|
||||
assert!(git(&repo, &["for-each-ref", "refs/sync/pca/"]).is_empty());
|
||||
let log = fs::read_to_string(w.base.join("pca.jsonl")).unwrap();
|
||||
assert!(log.contains("snapshots_purged"), "{log}");
|
||||
}
|
||||
@@ -55,6 +55,17 @@ impl Provider for Gitea {
|
||||
.ok_or_else(|| Error::Other("response has no login".into()))
|
||||
}
|
||||
|
||||
fn get_repo(&self, owner: &str, name: &str) -> Result<RemoteRepo> {
|
||||
let v = self
|
||||
.http
|
||||
.ok("GET", &format!("/repos/{owner}/{name}"), None)?;
|
||||
// `repo` defaults a missing flag to public; for a visibility check that must be an error.
|
||||
if !v["private"].is_boolean() {
|
||||
return Err(Error::Other("response has no `private` flag".into()));
|
||||
}
|
||||
Ok(repo(&v))
|
||||
}
|
||||
|
||||
fn list_repos(&self) -> Result<Vec<RemoteRepo>> {
|
||||
let mut out = Vec::new();
|
||||
for page in 1..=200 {
|
||||
|
||||
@@ -54,6 +54,25 @@ impl Provider for GitHub {
|
||||
.ok_or_else(|| Error::Other("response has no login".into()))
|
||||
}
|
||||
|
||||
fn get_repo(&self, owner: &str, name: &str) -> Result<RemoteRepo> {
|
||||
let v = self
|
||||
.http
|
||||
.ok("GET", &format!("/repos/{owner}/{name}"), None)?;
|
||||
// `repo` defaults a missing flag to public; for a visibility check that must be an error.
|
||||
if !v["private"].is_boolean() {
|
||||
return Err(Error::Other("response has no `private` flag".into()));
|
||||
}
|
||||
let mut r = repo(&v);
|
||||
// `internal` repos (GitHub Enterprise) have `private: true` but are readable by the
|
||||
// whole enterprise: only an explicit "private" counts as private.
|
||||
// Without the field we cannot tell private from internal: refuse to guess.
|
||||
let vis = v["visibility"]
|
||||
.as_str()
|
||||
.ok_or_else(|| Error::Other("response has no `visibility` field".into()))?;
|
||||
r.private = vis == "private";
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
fn list_repos(&self) -> Result<Vec<RemoteRepo>> {
|
||||
let mut out = Vec::new();
|
||||
for page in 1..=200 {
|
||||
|
||||
@@ -104,6 +104,8 @@ pub trait Provider {
|
||||
fn capabilities(&self) -> Capabilities;
|
||||
/// Verifies the token and returns the authenticated login.
|
||||
fn test_connection(&self) -> Result<String>;
|
||||
/// One repo's metadata (notably its visibility): `GET /repos/{owner}/{repo}`.
|
||||
fn get_repo(&self, owner: &str, name: &str) -> Result<RemoteRepo>;
|
||||
fn list_repos(&self) -> Result<Vec<RemoteRepo>>;
|
||||
fn create_repo(&self, new: &NewRepo) -> Result<RemoteRepo>;
|
||||
fn configure_mirror(&self, owner: &str, repo: &str, spec: &MirrorSpec) -> Result<()>;
|
||||
|
||||
@@ -318,3 +318,53 @@ fn falls_back_to_tea_and_gh_logins() {
|
||||
assert!(token::resolve(&id, &github).is_err());
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_repo_reports_visibility_on_both_forges() {
|
||||
let (url, rx) = mock(vec![
|
||||
(
|
||||
200,
|
||||
r#"{"name":"r","private":true,"clone_url":"u","default_branch":"main","owner":{"login":"o"}}"#,
|
||||
),
|
||||
(404, r#"{"message":"not found"}"#),
|
||||
(200, r#"{"name":"r","owner":{"login":"o"}}"#),
|
||||
]);
|
||||
let g = Gitea::new(ProviderKind::Gitea, &url, "t".into());
|
||||
let r = g.get_repo("o", "r").unwrap();
|
||||
assert!(r.private);
|
||||
assert!(rx.recv().unwrap().starts_with("GET /api/v1/repos/o/r "));
|
||||
assert!(matches!(
|
||||
g.get_repo("o", "gone").unwrap_err(),
|
||||
Error::Api { status: 404, .. }
|
||||
));
|
||||
rx.recv().unwrap();
|
||||
// A reply without the flag is an error, never "public by default".
|
||||
assert!(g.get_repo("o", "r").is_err());
|
||||
|
||||
let (url, rx) = mock(vec![(
|
||||
200,
|
||||
r#"{"name":"r","private":false,"visibility":"public","clone_url":"u","default_branch":"main","owner":{"login":"o"}}"#,
|
||||
)]);
|
||||
let gh = GitHub::new(&url, "t".into());
|
||||
assert!(!gh.get_repo("o", "r").unwrap().private);
|
||||
assert!(rx.recv().unwrap().starts_with("GET /repos/o/r "));
|
||||
|
||||
// No `visibility` field: unknown, never guessed from `private`.
|
||||
let (url, _rx) = mock(vec![(
|
||||
200,
|
||||
r#"{"name":"r","private":true,"owner":{"login":"o"}}"#,
|
||||
)]);
|
||||
assert!(GitHub::new(&url, "t".into()).get_repo("o", "r").is_err());
|
||||
|
||||
// An internal repo reports `private: true` but is not private.
|
||||
let (url, _rx) = mock(vec![(
|
||||
200,
|
||||
r#"{"name":"r","private":true,"visibility":"internal","owner":{"login":"o"}}"#,
|
||||
)]);
|
||||
assert!(
|
||||
!GitHub::new(&url, "t".into())
|
||||
.get_repo("o", "r")
|
||||
.unwrap()
|
||||
.private
|
||||
);
|
||||
}
|
||||
@@ -64,7 +64,8 @@ enum Cmd {
|
||||
#[arg(long)]
|
||||
backup_dir: Option<PathBuf>,
|
||||
},
|
||||
/// Run one full sync pass on the repo at PATH
|
||||
/// Run one full sync pass on the repo at PATH (pushes WIP snapshots whatever the
|
||||
/// `snapshots` policy says; only the daemon enforces it)
|
||||
Sync {
|
||||
#[arg(default_value = ".")]
|
||||
path: PathBuf,
|
||||
@@ -212,6 +213,15 @@ fn daemon(action: &DaemonCmd) -> Result<()> {
|
||||
if let Some(e) = r["last_error"].as_str() {
|
||||
println!(" error: {e}");
|
||||
}
|
||||
if let Some(why) = r["snapshots_withheld"].as_str() {
|
||||
println!(" snapshots withheld: {why}");
|
||||
}
|
||||
}
|
||||
for p in d["not_migrated"].as_array().into_iter().flatten() {
|
||||
println!(
|
||||
"{} [ignored] not migrated (run grove add)",
|
||||
p.as_str().unwrap_or("?")
|
||||
);
|
||||
}
|
||||
}
|
||||
DaemonCmd::Pause => {
|
||||
@@ -305,6 +315,19 @@ fn main() -> Result<()> {
|
||||
r.backup_tar.display(),
|
||||
r.backup_ref
|
||||
);
|
||||
for b in &r.linked_backups {
|
||||
println!("backup: {} (linked worktree)", b.display());
|
||||
}
|
||||
if !r.linked.is_empty() {
|
||||
println!("linked worktrees kept:");
|
||||
for l in &r.linked {
|
||||
println!(
|
||||
" {} ({})",
|
||||
l.path.display(),
|
||||
l.branch.as_deref().unwrap_or("detached")
|
||||
);
|
||||
}
|
||||
}
|
||||
println!("note: shells whose cwd was inside the old checkout must `cd` again");
|
||||
Ok(())
|
||||
}
|
||||
@@ -318,7 +341,13 @@ fn main() -> Result<()> {
|
||||
stamp: stamp(),
|
||||
remote: "origin".into(),
|
||||
offline: *offline,
|
||||
materialize: true,
|
||||
materialize: path
|
||||
.canonicalize()
|
||||
.ok()
|
||||
.and_then(|p| grove_daemon::discover::group_of(&p))
|
||||
.and_then(|g| cfg.groups.iter().find(|x| x.name == g))
|
||||
.is_none_or(|g| g.auto_materialize),
|
||||
push_snapshots: true,
|
||||
},
|
||||
)?;
|
||||
print_report(&rep)
|
||||
@@ -533,6 +562,16 @@ fn doctor(cfg_arg: &Option<PathBuf>) -> Result<()> {
|
||||
Err(e) => line(None, format!("provider {id:?}: {e}")),
|
||||
}
|
||||
}
|
||||
let names: Vec<String> = c.groups.iter().map(|g| g.name.clone()).collect();
|
||||
for p in grove_daemon::discover::discover(&root, &names).not_migrated {
|
||||
line(
|
||||
None,
|
||||
format!(
|
||||
"{}: not migrated (run grove add); the daemon ignores it",
|
||||
p.display()
|
||||
),
|
||||
);
|
||||
}
|
||||
for g in &c.groups {
|
||||
let gdir = root.join(&g.name);
|
||||
let Ok(rd) = std::fs::read_dir(&gdir) else {
|
||||
|
||||
@@ -132,6 +132,7 @@ pub fn init(path: &Path, a: InitArgs, force: bool) -> Result<Config> {
|
||||
mirror_to: vec![],
|
||||
layout: Layout::BareWorktrees,
|
||||
auto_materialize: true,
|
||||
snapshots: None,
|
||||
owners: Default::default(),
|
||||
public: None,
|
||||
}],
|
||||
|
||||
+30
-1
@@ -59,7 +59,7 @@ they may only contain letters, digits, `-` and `_`.
|
||||
|
||||
- Real two-PC validation by the author (acceptance criterion of this phase).
|
||||
- Daemon, file watching, scheduling, IPC (Phase 2). Locking against concurrent user git commands.
|
||||
- Migration of repos with submodules or existing linked worktrees; `new` and provider code (Phase 4).
|
||||
- Migration of repos with submodules; `new` and provider code (Phase 4).
|
||||
- Resolve actions for `Diverged` (Phase 5): today it is only detected and left intact.
|
||||
|
||||
## Validation on the real Gitea (2026-11-16)
|
||||
@@ -88,3 +88,32 @@ pass until that machine syncs again.
|
||||
`clone_bare_layout` created worktrees without upstream tracking, so `Diverged` and `Behind` were
|
||||
reported as `Synced` on repos cloned by grove itself. Fixed: every local branch with an `origin/<br>`
|
||||
counterpart gets `--set-upstream-to` before worktrees are materialized (asserted in `tests/registry.rs`).
|
||||
|
||||
## Linked worktrees (`git worktree add`)
|
||||
|
||||
`grove add` accepts repos that already have linked worktrees:
|
||||
|
||||
- Linked worktrees nested inside the repo (e.g. `.claude/worktrees/<name>`, often detached) move with
|
||||
the main checkout into `<repo>/<branch-dir>/...`. Ones outside the repo directory (e.g. a sibling
|
||||
`Repo-feature` dir) stay where they are.
|
||||
- The two link files of each (`<wt>/.git` and `.bare/worktrees/<id>/gitdir`) are rewritten to the new
|
||||
absolute paths; the result is verified (`git worktree list` shows every worktree, none prunable, and
|
||||
HEAD/branch/`status --ignored` of each are identical to before).
|
||||
- Backup: the repo tar covers nested worktrees; each outside worktree gets its own tar
|
||||
(`<repo>-<stamp>-linked<N>-<name>.tar`, listed in the report). Rollback also restores the link files.
|
||||
- Refused up front (nothing touched): a linked worktree that is locked, missing/prunable, has an
|
||||
operation in progress (rebase/merge/cherry-pick/revert/bisect), uses relative `.git` links, or
|
||||
contains the repo itself.
|
||||
- `grove add` prints each linked worktree with its branch or `detached`.
|
||||
|
||||
Sync behaviour with worktrees that are not at `<repo>/<branch-dir>`:
|
||||
|
||||
- Detached worktrees are reported but never snapshotted (a snapshot ref is per branch).
|
||||
- Branch worktrees elsewhere are synced like any other, under `refs/sync/<machine>/<branch>`.
|
||||
- `materialize` skips branches that already have a worktree anywhere; `archive_gone` only removes
|
||||
worktrees directly under the repo dir, never ones elsewhere.
|
||||
- The daemon's discovery ignores linked worktrees (`.git` file pointing into `.../worktrees/<id>`), so
|
||||
a sibling worktree is not synced as a second repo.
|
||||
- Known limit: a nested linked worktree is an embedded repo for the main worktree's snapshot, so it is
|
||||
recorded as a gitlink (same limitation as nested untracked repos); its own content is not synced
|
||||
through the main worktree's snapshot.
|
||||
+4
-3
@@ -5,8 +5,9 @@ is `grove_core::sync::sync_repo`, the same code the CLI runs. The daemon only de
|
||||
|
||||
## Behaviour
|
||||
|
||||
- **Repos**: every directory `root/<repo>` or `root/<group>/<repo>` that has a `.bare` or `.git`
|
||||
(dot-directories skipped). Rediscovered at every full pass, so new repos are picked up.
|
||||
- **Repos**: bare-layout repos (`.bare`) at `root/<group>/<repo>` for configured groups only; see
|
||||
`docs/phase6.md` (Daemon scope and snapshot privacy). Rediscovered at every full pass, so new repos
|
||||
are picked up.
|
||||
- **Watching**: inotify (crate `notify`), recursive per repo. Changes under `.git`, `.bare`,
|
||||
`.grove-stage` and anything matching `sync.ignore_extra` (exact component name or `*suffix`) are
|
||||
ignored. If a watch cannot be set (typically `ENOSPC`, raise `fs.inotify.max_user_watches`) it is
|
||||
@@ -58,7 +59,7 @@ socket is refused; a stale socket file left by a crash is replaced.
|
||||
|
||||
JSON lines in `<state dir>/activity.jsonl` (rotated at 5 MiB to `.jsonl.1`), the last 500 events in
|
||||
memory, and live via `subscribe`. Kinds: `start`, `stop`, `snapshot`, `fast_forward`, `applied`,
|
||||
`declined`, `state` (worktree state changed), `materialized`, `archived`, `error`, `watch_error`,
|
||||
`declined`, `snapshots_withheld`, `snapshots_enabled`, `snapshots_purged`, `state` (worktree state changed), `materialized`, `archived`, `error`, `watch_error`,
|
||||
`pause`, `resume`.
|
||||
|
||||
## CLI
|
||||
|
||||
+82
-1
@@ -61,4 +61,85 @@ is the broad-scope `tea`/`gh` token; use `grove login` with a narrower token to
|
||||
## Not verified
|
||||
|
||||
- Pull mirror creation on the real Gitea and push to a real GitHub org (mock-tested only).
|
||||
- The daemon still syncs every repo under `root.path`, whether or not its directory is a group.
|
||||
- Daemon scope and snapshot privacy (below) are verified with local bare remotes and mocks only, not against a real forge.
|
||||
|
||||
## Daemon scope and snapshot privacy
|
||||
|
||||
### Scope
|
||||
|
||||
`groved` manages only repos in the bare + worktrees layout (a `.bare` directory) at
|
||||
`<root>/<group>/<repo>` for groups present in the config. Everything else under the root is
|
||||
ignored: plain clones (never migrated with `grove add`), directories that are not configured
|
||||
groups, repos directly under the root. Ignored plain clones inside a configured group are listed as
|
||||
"not migrated (run grove add)" by `grove daemon status` and `grove doctor`. Discovery reads one
|
||||
directory per configured group, so it stays cheap.
|
||||
|
||||
**Breaking change:** group names must now be plain directory names (non-empty, no `/`, no leading
|
||||
`.`); a config with other names no longer loads.
|
||||
|
||||
### Snapshot policy
|
||||
|
||||
WIP snapshots (`refs/sync/<machine>/<branch>`) contain uncommitted work, so on a public repo anyone
|
||||
could read them. New key, global default under `[sync]` and optional override per group:
|
||||
|
||||
```toml
|
||||
[sync]
|
||||
snapshots = "private-only" # default: "private-only" | "all" | "none"
|
||||
|
||||
[[groups]]
|
||||
name = "Zenvairo"
|
||||
primary = "gitea"
|
||||
snapshots = "all" # optional per-group override
|
||||
```
|
||||
|
||||
- `private-only`: push snapshots only when the forge says the repo is private.
|
||||
- `all`: always push. `none`: never push.
|
||||
- When snapshots are withheld the daemon neither takes nor pushes them for that repo. Fetching, fast
|
||||
forwarding and applying other machines' snapshots are unaffected. The reason shows in
|
||||
`grove daemon status` ("snapshots withheld: ...") and once per change in the daemon log
|
||||
(`snapshots_withheld` / `snapshots_enabled`).
|
||||
- `grove sync` (manual) still pushes snapshots regardless of this setting.
|
||||
|
||||
### How visibility is resolved
|
||||
|
||||
Under `private-only` snapshots are pushed only if **every place the push reaches** is known to be
|
||||
private:
|
||||
|
||||
1. Every push URL of `origin` (`git remote get-url --push --all origin`, so `pushurl`, several
|
||||
urls and `pushInsteadOf` count). Each is matched to exactly one configured provider by host,
|
||||
port (http/https; an ssh port is ignored) and the provider URL's path prefix; zero or several
|
||||
matching providers mean unknown. The token comes from `token::resolve` (tea/gh fallback) and the
|
||||
lookup is `GET /repos/{owner}/{repo}` (`Provider::get_repo`). On GitHub only
|
||||
`visibility = "private"` counts (internal repos do not; a reply without the field is unknown); on Gitea only `private: true`.
|
||||
2. The group's mirror targets for the same repo name: every provider in `mirror_to` of the group's
|
||||
private and public routes, under the group's `owners` entry or else the token's login. Gitea
|
||||
push/pull mirrors copy `refs/sync/*`. A mirror that exists and is not private, or a failed
|
||||
lookup, withholds; a 404 (no mirror) is fine.
|
||||
|
||||
Answers are cached in `<state dir>/visibility.json` (mode 0600), keyed by provider id, provider URL, owner
|
||||
and name (lowercase, no `.git`). A "private" answer is trusted for 1 hour (a repo can be made public at
|
||||
any time) and so is an "absent" mirror answer; only "not private" (which merely withholds) is kept 6 hours, a cache timestamp in the future counts as expired, and an
|
||||
expired entry is never reused when the refresh fails. A failed lookup is retried at most every 5
|
||||
minutes. Unknown counts as **public**: no or several matching providers, no token, network error,
|
||||
404 on the repo itself, a reply without the `private` flag, no push URL. Offline (backoff) passes do
|
||||
no lookup: they use the last verdict, and take no snapshot when there is none.
|
||||
|
||||
When snapshots are withheld, the daemon deletes this machine's snapshot refs
|
||||
(`refs/sync/<machine>/*` only, never other machines' refs or branches). It lists them on every
|
||||
push URL with `ls-remote` (so refs without a local copy are found too), pushes the deletions per
|
||||
URL, and counts a URL as clean only when a fresh `ls-remote` shows none left; only then are the
|
||||
local copies removed. It logs `snapshots_purged` as a warning; any failure (also a server saying
|
||||
the repository does not exist) is logged as `error` and retried on the next pass. Git runs with
|
||||
`LC_ALL=C`, and snapshot pushes use `push.recurseSubmodules=no`.
|
||||
|
||||
Residual risks: when matching a provider, an ssh URL's port is ignored (it says nothing about the
|
||||
web port), so two forges on one host that differ only by port cannot be told apart by an ssh remote;
|
||||
and mirrors made by hand outside grove's config (a push mirror set up in the forge UI,
|
||||
a second remote) are unknown to the daemon. Use `snapshots = "none"` for repos where that matters.
|
||||
|
||||
### auto_materialize
|
||||
|
||||
`auto_materialize` (default `true`) makes the daemon create a worktree directory for every remote
|
||||
branch of a repo, including long-merged ones, and archive worktrees whose branch is gone. It is
|
||||
decided **per group** (it used to apply only when every group enabled it): set
|
||||
`auto_materialize = false` in a group to stop that for its repos. The default is unchanged.
|
||||
Reference in new issue
Block a user