mirror of
https://github.com/Dasemu/Grove.git
synced 2026-11-27 07:46:13 +00:00
feat(daemon): manage only bare-layout repos in configured groups, gate snapshots by visibility
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
990f155f65
commit
9e69b60e89
9 files changed
+704
-48
No files matched your search
Generated
+1
@@ -1178,6 +1178,7 @@ version = "0.1.0"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"grove-core",
|
"grove-core",
|
||||||
|
"grove-providers",
|
||||||
"notify",
|
"notify",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ path = "src/main.rs"
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
anyhow = "1.0.104"
|
anyhow = "1.0.104"
|
||||||
grove-core = { version = "0.1.0", path = "../grove-core" }
|
grove-core = { version = "0.1.0", path = "../grove-core" }
|
||||||
|
grove-providers = { version = "0.1.0", path = "../grove-providers" }
|
||||||
notify = "8.2.2"
|
notify = "8.2.2"
|
||||||
serde = { version = "1.0.229", features = ["derive"] }
|
serde = { version = "1.0.229", features = ["derive"] }
|
||||||
serde_json = "1.0.154"
|
serde_json = "1.0.154"
|
||||||
@@ -3,8 +3,9 @@
|
|||||||
//! so passes never overlap.
|
//! so passes never overlap.
|
||||||
|
|
||||||
use crate::activity::{Activity, now_secs};
|
use crate::activity::{Activity, now_secs};
|
||||||
use crate::discover::discover;
|
use crate::discover::{discover, group_of};
|
||||||
use crate::ipc;
|
use crate::ipc;
|
||||||
|
use crate::visibility::{Visibility, forge_fetch, snapshot_gate};
|
||||||
use grove_core::config::Config;
|
use grove_core::config::Config;
|
||||||
use grove_core::receive::Received;
|
use grove_core::receive::Received;
|
||||||
use grove_core::sync::{Options, sync_repo};
|
use grove_core::sync::{Options, sync_repo};
|
||||||
@@ -24,6 +25,8 @@ pub struct Settings {
|
|||||||
pub socket: PathBuf,
|
pub socket: PathBuf,
|
||||||
pub activity_log: Option<PathBuf>,
|
pub activity_log: Option<PathBuf>,
|
||||||
pub remote: String,
|
pub remote: String,
|
||||||
|
/// Where forge visibility answers are cached (`None` = in memory only).
|
||||||
|
pub visibility_cache: Option<PathBuf>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Settings {
|
impl Settings {
|
||||||
@@ -34,6 +37,7 @@ impl Settings {
|
|||||||
socket: ipc::default_socket_path(),
|
socket: ipc::default_socket_path(),
|
||||||
activity_log: Some(state.join("activity.jsonl")),
|
activity_log: Some(state.join("activity.jsonl")),
|
||||||
remote: "origin".into(),
|
remote: "origin".into(),
|
||||||
|
visibility_cache: Some(state.join("visibility.json")),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -53,6 +57,8 @@ pub struct RepoStatus {
|
|||||||
pub last_error: Option<String>,
|
pub last_error: Option<String>,
|
||||||
pub worktrees: Vec<WtStatus>,
|
pub worktrees: Vec<WtStatus>,
|
||||||
pub failures: u32,
|
pub failures: u32,
|
||||||
|
/// Why WIP snapshots are not pushed for this repo (`None` = they are).
|
||||||
|
pub snapshots_withheld: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for RepoStatus {
|
impl Default for RepoStatus {
|
||||||
@@ -63,6 +69,7 @@ impl Default for RepoStatus {
|
|||||||
last_error: None,
|
last_error: None,
|
||||||
worktrees: Vec::new(),
|
worktrees: Vec::new(),
|
||||||
failures: 0,
|
failures: 0,
|
||||||
|
snapshots_withheld: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -71,6 +78,8 @@ impl Default for RepoStatus {
|
|||||||
pub struct Shared {
|
pub struct Shared {
|
||||||
pub paused: bool,
|
pub paused: bool,
|
||||||
pub repos: BTreeMap<PathBuf, RepoStatus>,
|
pub repos: BTreeMap<PathBuf, RepoStatus>,
|
||||||
|
/// Plain clones in configured groups: ignored until migrated with `grove add`.
|
||||||
|
pub not_migrated: Vec<PathBuf>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub enum Msg {
|
pub enum Msg {
|
||||||
@@ -231,9 +240,11 @@ impl Watch {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn rescan(root: &Path, watch: &mut Watch, ctx: &Ctx) -> Vec<PathBuf> {
|
fn rescan(root: &Path, groups: &[String], watch: &mut Watch, ctx: &Ctx) -> Vec<PathBuf> {
|
||||||
let found = discover(root);
|
let d = discover(root, groups);
|
||||||
|
let found = d.managed;
|
||||||
let mut shared = ctx.shared.lock().unwrap();
|
let mut shared = ctx.shared.lock().unwrap();
|
||||||
|
shared.not_migrated = d.not_migrated;
|
||||||
shared.repos.retain(|p, _| found.contains(p));
|
shared.repos.retain(|p, _| found.contains(p));
|
||||||
for r in &found {
|
for r in &found {
|
||||||
shared.repos.entry(r.clone()).or_default();
|
shared.repos.entry(r.clone()).or_default();
|
||||||
@@ -249,9 +260,10 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
|||||||
let debounce = Duration::from_millis(cfg.sync.snapshot_debounce_ms);
|
let debounce = Duration::from_millis(cfg.sync.snapshot_debounce_ms);
|
||||||
let fetch_every = Duration::from_secs(cfg.sync.fetch_interval_s.max(1));
|
let fetch_every = Duration::from_secs(cfg.sync.fetch_interval_s.max(1));
|
||||||
let root = cfg.root_path();
|
let root = cfg.root_path();
|
||||||
|
let groups: Vec<String> = cfg.groups.iter().map(|g| g.name.clone()).collect();
|
||||||
|
let mut visibility = Visibility::load(st.visibility_cache.clone());
|
||||||
let mut watch = make_watch(ctx.tx.clone(), cfg.sync.ignore_extra.clone(), &ctx);
|
let mut watch = make_watch(ctx.tx.clone(), cfg.sync.ignore_extra.clone(), &ctx);
|
||||||
rescan(&root, &mut watch, &ctx);
|
rescan(&root, &groups, &mut watch, &ctx);
|
||||||
let materialize = cfg.groups.iter().all(|g| g.auto_materialize);
|
|
||||||
|
|
||||||
// due_at: when a repo should next be synced; backoff_until: earliest retry after failures.
|
// due_at: when a repo should next be synced; backoff_until: earliest retry after failures.
|
||||||
let mut due_at: HashMap<PathBuf, Instant> = HashMap::new();
|
let mut due_at: HashMap<PathBuf, Instant> = HashMap::new();
|
||||||
@@ -307,7 +319,7 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
|||||||
}
|
}
|
||||||
let now = Instant::now();
|
let now = Instant::now();
|
||||||
if now >= next_full {
|
if now >= next_full {
|
||||||
let found = rescan(&root, &mut watch, &ctx);
|
let found = rescan(&root, &groups, &mut watch, &ctx);
|
||||||
due_at.retain(|r, _| found.contains(r));
|
due_at.retain(|r, _| found.contains(r));
|
||||||
for r in found {
|
for r in found {
|
||||||
due_at.insert(r, now);
|
due_at.insert(r, now);
|
||||||
@@ -330,7 +342,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);
|
// While backing off after a failure, still snapshot local work (no network needed);
|
||||||
// the network is retried at the first pass after the backoff expires.
|
// the network is retried at the first pass after the backoff expires.
|
||||||
let offline = backoff_until.get(&r).is_some_and(|u| *u > now);
|
let offline = backoff_until.get(&r).is_some_and(|u| *u > now);
|
||||||
let failures = pass(&r, &cfg, &st, materialize, offline, &ctx);
|
let failures = pass(&r, &cfg, &st, &mut visibility, offline, &ctx);
|
||||||
if offline {
|
if offline {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -354,18 +366,36 @@ fn pass(
|
|||||||
repo: &Path,
|
repo: &Path,
|
||||||
cfg: &Config,
|
cfg: &Config,
|
||||||
st: &Settings,
|
st: &Settings,
|
||||||
materialize: bool,
|
visibility: &mut Visibility,
|
||||||
offline: bool,
|
offline: bool,
|
||||||
ctx: &Ctx,
|
ctx: &Ctx,
|
||||||
) -> u32 {
|
) -> u32 {
|
||||||
let name = repo.display().to_string();
|
let name = repo.display().to_string();
|
||||||
set_phase(ctx, repo, "syncing");
|
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);
|
||||||
|
// No lookup needed offline: nothing is pushed in such a pass anyway.
|
||||||
|
let gate = if offline {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
snapshot_gate(cfg, repo, &st.remote, visibility, now_secs(), &forge_fetch)
|
||||||
|
};
|
||||||
|
let push_snapshots = gate.is_ok();
|
||||||
|
if !offline {
|
||||||
|
note_snapshot_gate(ctx, repo, &name, gate.err());
|
||||||
|
}
|
||||||
let opts = Options {
|
let opts = Options {
|
||||||
machine: cfg.machine.name.clone(),
|
machine: cfg.machine.name.clone(),
|
||||||
stamp: stamp(),
|
stamp: stamp(),
|
||||||
remote: st.remote.clone(),
|
remote: st.remote.clone(),
|
||||||
offline,
|
offline,
|
||||||
materialize,
|
materialize,
|
||||||
|
push_snapshots,
|
||||||
};
|
};
|
||||||
let result = sync_repo(repo, &opts);
|
let result = sync_repo(repo, &opts);
|
||||||
let mut shared = ctx.shared.lock().unwrap();
|
let mut shared = ctx.shared.lock().unwrap();
|
||||||
@@ -451,6 +481,26 @@ fn pass(
|
|||||||
status.failures
|
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();
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
fn set_phase(ctx: &Ctx, repo: &Path, phase: &'static str) {
|
fn set_phase(ctx: &Ctx, repo: &Path, phase: &'static str) {
|
||||||
if let Some(s) = ctx.shared.lock().unwrap().repos.get_mut(repo) {
|
if let Some(s) = ctx.shared.lock().unwrap().repos.get_mut(repo) {
|
||||||
s.phase = phase;
|
s.phase = phase;
|
||||||
|
|||||||
@@ -1,10 +1,15 @@
|
|||||||
//! Finds the repos managed under the workspace root: `root/<repo>` or `root/<group>/<repo>`,
|
//! Finds the repos managed under the workspace root: `root/<group>/<repo>` for the configured
|
||||||
//! where a repo has a `.bare` directory (bare + worktrees layout) or a `.git`.
|
//! 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};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
fn is_repo(p: &Path) -> bool {
|
fn is_bare_layout(p: &Path) -> bool {
|
||||||
p.join(".bare").is_dir() || p.join(".git").exists()
|
p.join(".bare").is_dir()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_plain_clone(p: &Path) -> bool {
|
||||||
|
!is_bare_layout(p) && p.join(".git").exists()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn subdirs(p: &Path) -> Vec<PathBuf> {
|
fn subdirs(p: &Path) -> Vec<PathBuf> {
|
||||||
@@ -20,16 +25,37 @@ fn subdirs(p: &Path) -> Vec<PathBuf> {
|
|||||||
v
|
v
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn discover(root: &Path) -> Vec<PathBuf> {
|
/// What lives under the root, as far as the daemon is concerned.
|
||||||
let mut out = Vec::new();
|
#[derive(Debug, Default, PartialEq, Eq)]
|
||||||
for child in subdirs(root) {
|
pub struct Discovery {
|
||||||
if is_repo(&child) {
|
/// Bare-layout repos in configured groups: these are synced.
|
||||||
out.push(child);
|
pub managed: Vec<PathBuf>,
|
||||||
} else {
|
/// Plain clones in configured groups: ignored, reported as "not migrated".
|
||||||
out.extend(subdirs(&child).into_iter().filter(|g| is_repo(g)));
|
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)]
|
#[cfg(test)]
|
||||||
@@ -37,23 +63,30 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
#[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 base = std::env::temp_dir().join(format!("grove-disc-{}", std::process::id()));
|
||||||
let _ = std::fs::remove_dir_all(&base);
|
let _ = std::fs::remove_dir_all(&base);
|
||||||
for d in [
|
for d in [
|
||||||
"a/.git",
|
"grp/migrated/.bare",
|
||||||
"grp/b/.bare",
|
"grp/plain/.git",
|
||||||
"grp/plain",
|
"grp/.hidden/.bare",
|
||||||
".hidden/.git",
|
"grp/notarepo/x",
|
||||||
"c/inner/.git",
|
"other/b/.bare",
|
||||||
|
"other/c/.git",
|
||||||
|
"rootclone/.git",
|
||||||
|
"rootbare/.bare",
|
||||||
|
".dot/b/.bare",
|
||||||
|
"grp2/nested/deeper/.bare",
|
||||||
] {
|
] {
|
||||||
std::fs::create_dir_all(base.join(d)).unwrap();
|
std::fs::create_dir_all(base.join(d)).unwrap();
|
||||||
}
|
}
|
||||||
let found = discover(&base);
|
let found = discover(
|
||||||
assert_eq!(
|
&base,
|
||||||
found,
|
&["grp".to_string(), "grp2".to_string(), "absent".into()],
|
||||||
vec![base.join("a"), base.join("c/inner"), base.join("grp/b")]
|
|
||||||
);
|
);
|
||||||
|
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();
|
std::fs::remove_dir_all(&base).unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -160,6 +160,7 @@ fn handle(req: &Request, ctx: &Ctx) -> Value {
|
|||||||
"last_sync": r.last_sync,
|
"last_sync": r.last_sync,
|
||||||
"last_error": r.last_error,
|
"last_error": r.last_error,
|
||||||
"failures": r.failures,
|
"failures": r.failures,
|
||||||
|
"snapshots_withheld": r.snapshots_withheld,
|
||||||
"worktrees": r.worktrees.iter()
|
"worktrees": r.worktrees.iter()
|
||||||
.map(|w| json!({"branch": w.branch, "state": w.state, "path": w.path}))
|
.map(|w| json!({"branch": w.branch, "state": w.state, "path": w.path}))
|
||||||
.collect::<Vec<_>>(),
|
.collect::<Vec<_>>(),
|
||||||
@@ -167,7 +168,8 @@ fn handle(req: &Request, ctx: &Ctx) -> Value {
|
|||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
ok(
|
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" => {
|
"pause" | "resume" => {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ pub mod activity;
|
|||||||
pub mod daemon;
|
pub mod daemon;
|
||||||
pub mod discover;
|
pub mod discover;
|
||||||
pub mod ipc;
|
pub mod ipc;
|
||||||
|
pub mod visibility;
|
||||||
|
|
||||||
pub use activity::{Activity, Event};
|
pub use activity::{Activity, Event};
|
||||||
pub use daemon::{Daemon, Settings};
|
pub use daemon::{Daemon, Settings};
|
||||||
@@ -0,0 +1,423 @@
|
|||||||
|
//! Snapshot privacy: WIP snapshots hold uncommitted work, so under the default `private-only`
|
||||||
|
//! policy they are pushed only to repos the forge reports as private. Anything unknown (no
|
||||||
|
//! matching provider, no token, network error, odd answer) is treated as public.
|
||||||
|
//!
|
||||||
|
//! Answers are cached in `<state dir>/visibility.json` and refreshed every [`TTL`] seconds;
|
||||||
|
//! failed lookups are retried at most every [`RETRY`] seconds.
|
||||||
|
|
||||||
|
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 successful answer is trusted.
|
||||||
|
pub const TTL: u64 = 6 * 3600;
|
||||||
|
/// Minimum wait before asking the forge again after a failed lookup.
|
||||||
|
pub const RETRY: u64 = 300;
|
||||||
|
|
||||||
|
/// Host (lowercase, no port) and `owner/name` of a remote URL.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct RepoId {
|
||||||
|
pub host: 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 (authority, path) = match url.split_once("://") {
|
||||||
|
Some((_, rest)) => rest.split_once('/')?,
|
||||||
|
None => url.split_once(':')?,
|
||||||
|
};
|
||||||
|
let host = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
|
||||||
|
let host = match host.strip_prefix('[') {
|
||||||
|
Some(v6) => v6.split(']').next()?, // [::1]:22
|
||||||
|
None => host.split(':').next()?,
|
||||||
|
};
|
||||||
|
let mut segs: Vec<&str> = path
|
||||||
|
.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(),
|
||||||
|
owner: owner.to_string(),
|
||||||
|
name: name.to_string(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Host (lowercase, no port) a provider answers for. GitHub without a URL is `github.com`; a
|
||||||
|
/// leading `api.` is dropped so API URLs map to the clone host.
|
||||||
|
fn provider_host(cfg: &ProviderCfg) -> Option<String> {
|
||||||
|
let url = cfg.url.as_deref().map(str::trim).filter(|u| !u.is_empty());
|
||||||
|
let Some(url) = url else {
|
||||||
|
return (cfg.kind == ProviderKind::Github).then(|| "github.com".to_string());
|
||||||
|
};
|
||||||
|
let rest = url.split_once("://").map_or(url, |(_, r)| r);
|
||||||
|
let auth = rest.split(['/', '?', '#']).next()?;
|
||||||
|
let auth = auth.rsplit_once('@').map_or(auth, |(_, h)| h);
|
||||||
|
let host = auth.split(':').next()?.to_ascii_lowercase();
|
||||||
|
let host = match cfg.kind {
|
||||||
|
ProviderKind::Github => host.strip_prefix("api.").unwrap_or(&host).to_string(),
|
||||||
|
_ => host,
|
||||||
|
};
|
||||||
|
(!host.is_empty()).then_some(host)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The configured provider (id and config) that serves `host`.
|
||||||
|
pub fn provider_for<'a>(cfg: &'a Config, host: &str) -> Option<(&'a str, &'a ProviderCfg)> {
|
||||||
|
cfg.providers
|
||||||
|
.iter()
|
||||||
|
.find(|(_, p)| provider_host(p).as_deref() == Some(host))
|
||||||
|
.map(|(id, p)| (id.as_str(), p))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub enum Verdict {
|
||||||
|
Private,
|
||||||
|
Public,
|
||||||
|
/// Could not be determined; treated as public. Carries the reason.
|
||||||
|
Unknown(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
struct Entry {
|
||||||
|
private: bool,
|
||||||
|
checked: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Asks the forge whether `owner/name` is private: `(provider id, provider config, owner, name)`.
|
||||||
|
pub type Fetch<'a> = &'a dyn Fn(&str, &ProviderCfg, &str, &str) -> Result<bool, String>;
|
||||||
|
|
||||||
|
/// The real lookup: token via `token::resolve` (grove login, Secret Service, tea/gh), then
|
||||||
|
/// `GET /repos/{owner}/{repo}`.
|
||||||
|
pub fn forge_fetch(id: &str, pc: &ProviderCfg, owner: &str, name: &str) -> Result<bool, String> {
|
||||||
|
let (token, _) = grove_providers::token::resolve(id, pc).map_err(|e| e.to_string())?;
|
||||||
|
let p = grove_providers::build(pc, token);
|
||||||
|
p.get_repo(owner, name)
|
||||||
|
.map(|r| r.private)
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
failed: HashMap::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save(&self) {
|
||||||
|
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");
|
||||||
|
if let Ok(text) = serde_json::to_string_pretty(&self.entries)
|
||||||
|
&& std::fs::write(&tmp, text).is_ok()
|
||||||
|
{
|
||||||
|
let _ = std::fs::rename(&tmp, path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Visibility of the repo behind `origin_url`, from the cache or the forge.
|
||||||
|
pub fn check(&mut self, cfg: &Config, origin_url: &str, now: u64, fetch: Fetch) -> Verdict {
|
||||||
|
let Some(id) = parse_remote(origin_url) else {
|
||||||
|
return Verdict::Unknown("origin URL not understood".into());
|
||||||
|
};
|
||||||
|
let Some((pid, pc)) = provider_for(cfg, &id.host) else {
|
||||||
|
return Verdict::Unknown(format!("no configured provider for host {}", id.host));
|
||||||
|
};
|
||||||
|
let key = format!("{}/{}/{}", id.host, id.owner, id.name).to_ascii_lowercase();
|
||||||
|
let verdict = |private| {
|
||||||
|
if private {
|
||||||
|
Verdict::Private
|
||||||
|
} else {
|
||||||
|
Verdict::Public
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Some(e) = self.entries.get(&key)
|
||||||
|
&& now.saturating_sub(e.checked) < TTL
|
||||||
|
{
|
||||||
|
return verdict(e.private);
|
||||||
|
}
|
||||||
|
if let Some((at, why)) = self.failed.get(&key)
|
||||||
|
&& now.saturating_sub(*at) < RETRY
|
||||||
|
{
|
||||||
|
return Verdict::Unknown(why.clone());
|
||||||
|
}
|
||||||
|
match fetch(pid, pc, &id.owner, &id.name) {
|
||||||
|
Ok(private) => {
|
||||||
|
self.failed.remove(&key);
|
||||||
|
self.entries.insert(
|
||||||
|
key,
|
||||||
|
Entry {
|
||||||
|
private,
|
||||||
|
checked: now,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
self.save();
|
||||||
|
verdict(private)
|
||||||
|
}
|
||||||
|
Err(why) => {
|
||||||
|
let why = format!("lookup on {pid:?} failed: {why}");
|
||||||
|
self.failed.insert(key, (now, why.clone()));
|
||||||
|
Verdict::Unknown(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\")"
|
||||||
|
)),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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,
|
||||||
|
fetch: Fetch,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let group = crate::discover::group_of(repo).unwrap_or_default();
|
||||||
|
decide(cfg.snapshot_policy(&group), || {
|
||||||
|
let url = Git::new(git_dir_for(repo))
|
||||||
|
.probe(&["config", "--get", &format!("remote.{remote}.url")])
|
||||||
|
.ok()
|
||||||
|
.flatten();
|
||||||
|
match url {
|
||||||
|
Some(u) => vis.check(cfg, &u, now, fetch),
|
||||||
|
None => Verdict::Unknown(format!("no {remote} remote")),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::cell::Cell;
|
||||||
|
|
||||||
|
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"
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_remote_url_forms() {
|
||||||
|
let id = |h: &str, o: &str, n: &str| {
|
||||||
|
Some(RepoId {
|
||||||
|
host: h.into(),
|
||||||
|
owner: o.into(),
|
||||||
|
name: n.into(),
|
||||||
|
})
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
parse_remote("https://github.com/Org/repo.git"),
|
||||||
|
id("github.com", "Org", "repo")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
parse_remote("git@GitHub.com:Org/repo.git"),
|
||||||
|
id("github.com", "Org", "repo")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
parse_remote("ssh://git@git.example.com:2222/o/r"),
|
||||||
|
id("git.example.com", "o", "r")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
parse_remote("https://u:p@h.io:3000/sub/o/r.git/"),
|
||||||
|
id("h.io", "o", "r")
|
||||||
|
);
|
||||||
|
assert_eq!(parse_remote("/local/path/repo.git"), None);
|
||||||
|
assert_eq!(parse_remote("https://host/onlyone"), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn matches_providers_by_host() {
|
||||||
|
let c = cfg();
|
||||||
|
assert_eq!(provider_for(&c, "git.example.com").unwrap().0, "gitea");
|
||||||
|
assert_eq!(provider_for(&c, "github.com").unwrap().0, "github");
|
||||||
|
assert!(provider_for(&c, "gitlab.com").is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unknown_visibility_is_public_and_withholds_snapshots() {
|
||||||
|
let c = cfg();
|
||||||
|
let mut v = Visibility::default();
|
||||||
|
let boom = |_: &str, _: &ProviderCfg, _: &str, _: &str| Err("no token".to_string());
|
||||||
|
// Unmatched host, unparsable URL and a failing lookup are all "unknown".
|
||||||
|
for url in [
|
||||||
|
"https://gitlab.com/o/r.git",
|
||||||
|
"/some/path",
|
||||||
|
"https://github.com/o/r",
|
||||||
|
] {
|
||||||
|
let verdict = v.check(&c, url, 1000, &boom);
|
||||||
|
assert!(matches!(verdict, Verdict::Unknown(_)), "{url}: {verdict:?}");
|
||||||
|
assert!(decide(SnapshotPolicy::PrivateOnly, || verdict).is_err());
|
||||||
|
}
|
||||||
|
// Public and private answers.
|
||||||
|
let public = |_: &str, _: &ProviderCfg, _: &str, _: &str| Ok(false);
|
||||||
|
let private = |_: &str, _: &ProviderCfg, _: &str, _: &str| Ok(true);
|
||||||
|
let p = v.check(&c, "https://github.com/o/pub", 1000, &public);
|
||||||
|
assert_eq!(p, Verdict::Public);
|
||||||
|
assert!(decide(SnapshotPolicy::PrivateOnly, || p).is_err());
|
||||||
|
let q = v.check(&c, "https://github.com/o/priv", 1000, &private);
|
||||||
|
assert_eq!(q, Verdict::Private);
|
||||||
|
assert!(decide(SnapshotPolicy::PrivateOnly, || q).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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 answers_are_cached_until_the_ttl_and_failures_are_throttled() {
|
||||||
|
let c = cfg();
|
||||||
|
let mut v = Visibility::default();
|
||||||
|
let calls = Cell::new(0);
|
||||||
|
let ok = |_: &str, _: &ProviderCfg, _: &str, _: &str| {
|
||||||
|
calls.set(calls.get() + 1);
|
||||||
|
Ok(true)
|
||||||
|
};
|
||||||
|
let url = "https://github.com/o/r";
|
||||||
|
assert_eq!(v.check(&c, url, 0, &ok), Verdict::Private);
|
||||||
|
assert_eq!(v.check(&c, url, TTL - 1, &ok), Verdict::Private);
|
||||||
|
assert_eq!(calls.get(), 1);
|
||||||
|
assert_eq!(v.check(&c, url, TTL, &ok), Verdict::Private);
|
||||||
|
assert_eq!(calls.get(), 2);
|
||||||
|
// After the TTL a failing refresh does not fall back to the stale answer.
|
||||||
|
let fails = Cell::new(0);
|
||||||
|
let bad = |_: &str, _: &ProviderCfg, _: &str, _: &str| {
|
||||||
|
fails.set(fails.get() + 1);
|
||||||
|
Err("down".to_string())
|
||||||
|
};
|
||||||
|
let t = 2 * TTL;
|
||||||
|
assert!(matches!(v.check(&c, url, t, &bad), Verdict::Unknown(_)));
|
||||||
|
assert!(matches!(v.check(&c, url, t + 1, &bad), Verdict::Unknown(_)));
|
||||||
|
assert_eq!(fails.get(), 1, "retry is throttled");
|
||||||
|
assert!(matches!(
|
||||||
|
v.check(&c, url, t + RETRY, &bad),
|
||||||
|
Verdict::Unknown(_)
|
||||||
|
));
|
||||||
|
assert_eq!(fails.get(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cache_persists_in_the_state_dir() {
|
||||||
|
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 public = |_: &str, _: &ProviderCfg, _: &str, _: &str| Ok(false);
|
||||||
|
let mut v = Visibility::load(Some(file.clone()));
|
||||||
|
assert_eq!(
|
||||||
|
v.check(&c, "https://github.com/o/r", 50, &public),
|
||||||
|
Verdict::Public
|
||||||
|
);
|
||||||
|
let never = |_: &str, _: &ProviderCfg, _: &str, _: &str| Err("unused".to_string());
|
||||||
|
let mut again = Visibility::load(Some(file));
|
||||||
|
assert_eq!(
|
||||||
|
again.check(&c, "https://github.com/o/r", 60, &never),
|
||||||
|
Verdict::Public
|
||||||
|
);
|
||||||
|
std::fs::remove_dir_all(&dir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn gate_uses_the_group_policy_and_the_origin_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 mk = |group: &str, url: Option<&str>| {
|
||||||
|
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();
|
||||||
|
if let Some(u) = url {
|
||||||
|
g.run(&["remote", "add", "origin", u]).unwrap();
|
||||||
|
}
|
||||||
|
repo
|
||||||
|
};
|
||||||
|
let private = |_: &str, _: &ProviderCfg, _: &str, _: &str| Ok(true);
|
||||||
|
let mut v = Visibility::default();
|
||||||
|
let url = Some("https://git.example.com:3000/o/r.git");
|
||||||
|
let gate =
|
||||||
|
|repo: &Path, v: &mut Visibility| snapshot_gate(&c, repo, "origin", v, 0, &private);
|
||||||
|
assert!(gate(&mk("priv", url), &mut v).is_ok());
|
||||||
|
assert!(gate(&mk("off", url), &mut v).is_err());
|
||||||
|
assert!(gate(&mk("all", Some("https://unknown.example/o/r")), &mut v).is_ok());
|
||||||
|
// Private-only without an origin remote: unknown, withheld.
|
||||||
|
std::fs::remove_dir_all(base.join("priv")).unwrap();
|
||||||
|
mk("priv", None);
|
||||||
|
assert!(
|
||||||
|
gate(&base.join("priv/r"), &mut v)
|
||||||
|
.unwrap_err()
|
||||||
|
.contains("unknown")
|
||||||
|
);
|
||||||
|
std::fs::remove_dir_all(&base).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -68,14 +68,40 @@ fn world(tag: &str, machines: &[&str]) -> World {
|
|||||||
for m in machines {
|
for m in machines {
|
||||||
let dir = base.join(m);
|
let dir = base.join(m);
|
||||||
fs::create_dir_all(&dir).unwrap();
|
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 }
|
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 {
|
fn config(w: &World, machine: &str, debounce_ms: u64, fetch_s: u64) -> Config {
|
||||||
Config::parse(&format!(
|
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()
|
w.base.join(machine).display()
|
||||||
))
|
))
|
||||||
.unwrap()
|
.unwrap()
|
||||||
@@ -86,6 +112,7 @@ fn settings(w: &World, machine: &str) -> Settings {
|
|||||||
socket: w.base.join(format!("{machine}.sock")),
|
socket: w.base.join(format!("{machine}.sock")),
|
||||||
activity_log: Some(w.base.join(format!("{machine}.jsonl"))),
|
activity_log: Some(w.base.join(format!("{machine}.jsonl"))),
|
||||||
remote: "origin".into(),
|
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 w = world("converge", &["pca", "pcb"]);
|
||||||
let a = start(&w, "pca");
|
let a = start(&w, "pca");
|
||||||
let b = start(&w, "pcb");
|
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(&file_a, "hello\n").unwrap();
|
||||||
fs::write(w.base.join("pca/repo/a.txt"), "one\nedited\n").unwrap();
|
fs::write(w.base.join("pca/g/repo/main/a.txt"), "one\nedited\n").unwrap();
|
||||||
let on_b = w.base.join("pcb/repo/new.txt");
|
let on_b = w.base.join("pcb/g/repo/main/new.txt");
|
||||||
wait_until("new.txt on B", 30, || {
|
wait_until("new.txt on B", 30, || {
|
||||||
fs::read_to_string(&on_b).is_ok_and(|s| s == "hello\n")
|
fs::read_to_string(&on_b).is_ok_and(|s| s == "hello\n")
|
||||||
});
|
});
|
||||||
assert_eq!(
|
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"
|
"one\nedited\n"
|
||||||
);
|
);
|
||||||
// The user's branch on A was never touched by the daemon.
|
// The user's branch on A was never touched by the daemon.
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
git(&w.base.join("pca/repo"), &["log", "--oneline"])
|
git(&w.base.join("pca/g/repo/main"), &["log", "--oneline"])
|
||||||
.lines()
|
.lines()
|
||||||
.count(),
|
.count(),
|
||||||
1
|
1
|
||||||
@@ -125,12 +152,12 @@ fn committed_work_fast_forwards_the_other_machine() {
|
|||||||
let w = world("ff", &["pca", "pcb"]);
|
let w = world("ff", &["pca", "pcb"]);
|
||||||
let a = start(&w, "pca");
|
let a = start(&w, "pca");
|
||||||
let b = start(&w, "pcb");
|
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();
|
fs::write(ra.join("c.txt"), "committed\n").unwrap();
|
||||||
git(&ra, &["add", "-A"]);
|
git(&ra, &["add", "-A"]);
|
||||||
git(&ra, &["commit", "-qm", "c"]);
|
git(&ra, &["commit", "-qm", "c"]);
|
||||||
git(&ra, &["push", "-q", "origin", "main"]);
|
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 fast-forwarded", 30, || rb.join("c.txt").exists());
|
||||||
wait_until("B synced", 30, || {
|
wait_until("B synced", 30, || {
|
||||||
git(&rb, &["status", "--porcelain"]).is_empty()
|
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();
|
let unknown = ipc::request(&sock, &json!({"v":1,"cmd":"nope"})).unwrap();
|
||||||
assert_eq!(unknown["ok"], false);
|
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, || {
|
wait_until("status lists the repo", 10, || {
|
||||||
let s = ipc::request(&sock, &json!({"v":1,"cmd":"status"})).unwrap();
|
let s = ipc::request(&sock, &json!({"v":1,"cmd":"status"})).unwrap();
|
||||||
s["data"]["repos"].as_array().is_some_and(|r| r.len() == 1)
|
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]
|
#[test]
|
||||||
fn killing_the_daemon_loses_nothing_and_a_restart_recovers() {
|
fn killing_the_daemon_loses_nothing_and_a_restart_recovers() {
|
||||||
let w = world("crash", &["pca"]);
|
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");
|
let cfg_path = w.base.join("config.toml");
|
||||||
fs::write(
|
fs::write(
|
||||||
&cfg_path,
|
&cfg_path,
|
||||||
format!(
|
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()
|
w.base.join("pca").display()
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
@@ -269,7 +296,7 @@ fn killing_the_daemon_loses_nothing_and_a_restart_recovers() {
|
|||||||
"precious\n"
|
"precious\n"
|
||||||
);
|
);
|
||||||
assert!(
|
assert!(
|
||||||
!repo.join(".git/index.lock").exists(),
|
!repo.join("../.bare/worktrees/main/index.lock").exists(),
|
||||||
"stale index.lock after kill"
|
"stale index.lock after kill"
|
||||||
);
|
);
|
||||||
git(&repo, &["fsck", "--no-dangling"]);
|
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 w = world("wipcommit", &["pca", "pcb"]);
|
||||||
let a = start(&w, "pca");
|
let a = start(&w, "pca");
|
||||||
let b = start(&w, "pcb");
|
let b = start(&w, "pcb");
|
||||||
let ra = w.base.join("pca/repo");
|
let ra = w.base.join("pca/g/repo/main");
|
||||||
let rb = w.base.join("pcb/repo");
|
let rb = w.base.join("pcb/g/repo/main");
|
||||||
fs::write(ra.join("w.txt"), "wip\n").unwrap();
|
fs::write(ra.join("w.txt"), "wip\n").unwrap();
|
||||||
wait_until("WIP on B", 30, || rb.join("w.txt").exists());
|
wait_until("WIP on B", 30, || rb.join("w.txt").exists());
|
||||||
git(&ra, &["add", "-A"]);
|
git(&ra, &["add", "-A"]);
|
||||||
@@ -322,7 +349,7 @@ fn paused_daemon_does_not_spin() {
|
|||||||
fs::write(
|
fs::write(
|
||||||
&cfg_path,
|
&cfg_path,
|
||||||
format!(
|
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()
|
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 st = settings(&w, "pca");
|
||||||
let sock = st.socket.clone();
|
let sock = st.socket.clone();
|
||||||
let d = Daemon::start(config(&w, "pca", 200, 60), st).unwrap();
|
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, || {
|
wait_until("repo listed", 10, || {
|
||||||
ipc::request(&sock, &json!({"v":1,"cmd":"status"})).unwrap()["data"]["repos"]
|
ipc::request(&sock, &json!({"v":1,"cmd":"status"})).unwrap()["data"]["repos"]
|
||||||
.as_array()
|
.as_array()
|
||||||
@@ -369,3 +396,101 @@ fn sync_accepts_a_non_canonical_repo_path_and_unknown_repos_are_rejected() {
|
|||||||
assert_eq!(bad["ok"], false);
|
assert_eq!(bad["ok"], false);
|
||||||
d.shutdown();
|
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();
|
||||||
|
}
|
||||||
@@ -212,6 +212,15 @@ fn daemon(action: &DaemonCmd) -> Result<()> {
|
|||||||
if let Some(e) = r["last_error"].as_str() {
|
if let Some(e) = r["last_error"].as_str() {
|
||||||
println!(" error: {e}");
|
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 => {
|
DaemonCmd::Pause => {
|
||||||
@@ -319,6 +328,7 @@ fn main() -> Result<()> {
|
|||||||
remote: "origin".into(),
|
remote: "origin".into(),
|
||||||
offline: *offline,
|
offline: *offline,
|
||||||
materialize: true,
|
materialize: true,
|
||||||
|
push_snapshots: true,
|
||||||
},
|
},
|
||||||
)?;
|
)?;
|
||||||
print_report(&rep)
|
print_report(&rep)
|
||||||
@@ -533,6 +543,16 @@ fn doctor(cfg_arg: &Option<PathBuf>) -> Result<()> {
|
|||||||
Err(e) => line(None, format!("provider {id:?}: {e}")),
|
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 {
|
for g in &c.groups {
|
||||||
let gdir = root.join(&g.name);
|
let gdir = root.join(&g.name);
|
||||||
let Ok(rd) = std::fs::read_dir(&gdir) else {
|
let Ok(rd) = std::fs::read_dir(&gdir) else {
|
||||||
|
|||||||
Reference in new issue
Block a user