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:
dasemuandClaude Sonnet 5.5 committed 2026-11-16 17:14:29 +01:00
1 parent 990f155f65
commit 9e69b60e89
9 files changed
+704 -48

No files matched your search

+58 -8
View File
@@ -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::{Visibility, forge_fetch, 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,8 @@ 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>,
}
impl Default for RepoStatus {
@@ -63,6 +69,7 @@ impl Default for RepoStatus {
last_error: None,
worktrees: Vec::new(),
failures: 0,
snapshots_withheld: None,
}
}
}
@@ -71,6 +78,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 +240,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 +260,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 +319,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 +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);
// 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 +366,36 @@ 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);
// 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 {
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 +481,26 @@ 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();
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) {
if let Some(s) = ctx.shared.lock().unwrap().repos.get_mut(repo) {
s.phase = phase;
+55 -22
View File
@@ -1,10 +1,15 @@
//! 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()
}
fn is_plain_clone(p: &Path) -> bool {
!is_bare_layout(p) && p.join(".git").exists()
}
fn subdirs(p: &Path) -> Vec<PathBuf> {
@@ -20,16 +25,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 +63,30 @@ 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",
] {
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")]
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();
}
}
+3 -1
View File
@@ -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" => {
+1
View File
@@ -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};
+423
View File
@@ -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();
}
}