1use std::path::{Component, Path, PathBuf};
55
56use serde::Deserialize;
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Default)]
59#[serde(rename_all = "lowercase")]
60pub enum Share {
61 #[default]
63 Team,
64 Local,
66}
67
68#[derive(Debug, Clone, Deserialize)]
69pub struct Entry {
70 pub name: String,
71 pub paths: Vec<String>,
72 #[serde(default)]
73 pub share: Share,
74 #[serde(default)]
77 pub experts: Vec<ExpertSource>,
78 #[serde(default)]
82 pub relay: Option<String>,
83 #[serde(default)]
87 pub mode: Option<String>,
88 #[serde(default)]
93 pub budget: Option<serde_json::Value>,
94 #[serde(default)]
101 pub risk: Option<serde_json::Value>,
102}
103
104impl Entry {
105 #[must_use]
107 pub fn budget(&self) -> Option<f64> {
108 self.budget.as_ref()?.as_f64().filter(|b| *b > 0.0)
109 }
110
111 #[must_use]
113 pub fn risk(&self) -> Option<f64> {
114 self.risk.as_ref()?.as_f64().filter(|r| (0.0..=1.0).contains(r))
115 }
116}
117
118#[derive(Debug, Clone, Deserialize)]
122pub struct ExpertSource {
123 pub name: String,
124 pub repo: String,
125 #[serde(rename = "match", default)]
126 pub matches: Vec<String>,
127 #[serde(default)]
130 pub drone: bool,
131}
132
133impl ExpertSource {
134 pub fn path(&self) -> PathBuf {
136 expand(&self.repo)
137 }
138}
139
140impl Config {
141 pub fn experts_for(&self, cwd: &str) -> Vec<&ExpertSource> {
144 let Route::Collective { name, .. } = route(Some(self), cwd, Path::new("/")) else { return Vec::new() };
145 let Some(c) = self.collectives.iter().find(|c| c.name == name) else { return Vec::new() };
146 c.experts.iter().filter(|e| self.may_consult(&c.name, e)).collect()
147 }
148
149 pub fn may_consult(&self, collective: &str, e: &ExpertSource) -> bool {
155 let p = e.path();
156 let real = p.canonicalize().ok();
157 std::iter::once(p).chain(real).all(|p| {
158 if self.off.iter().any(|o| inside(&normal(&p), o).is_some()) {
159 return false;
160 }
161 !matches!(route(Some(self), &p.to_string_lossy(), Path::new("/")),
162 Route::Collective { name, share: Share::Local, .. } if name != collective)
163 })
164 }
165}
166
167#[derive(Debug, Clone, Deserialize)]
168pub struct Config {
169 #[serde(default = "off")]
171 pub default: String,
172 #[serde(default)]
174 pub off: Vec<String>,
175 #[serde(default)]
176 pub collectives: Vec<Entry>,
177 #[serde(default, deserialize_with = "engineers")]
179 pub engineers: Vec<Engineer>,
180 #[serde(default)]
182 pub personal: Option<String>,
183}
184
185fn engineers<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<Engineer>, D::Error> {
187 Vec::<Engineer>::deserialize(d).map_err(|e| serde::de::Error::custom(format!("engineers: {e}")))
188}
189
190#[derive(Debug, Clone, Deserialize)]
192#[serde(deny_unknown_fields)]
193pub struct Engineer {
194 pub name: String,
195 pub emails: Vec<String>,
196}
197
198#[derive(Debug, Clone, Default, PartialEq, Eq)]
201pub struct Aliases {
202 by_email: std::collections::HashMap<String, String>,
203}
204
205impl Aliases {
206 pub fn new(engineers: &[Engineer]) -> Aliases {
207 let by_email = engineers.iter().flat_map(|e| e.emails.iter().map(move |m| (m.trim().to_lowercase(), e.name.trim().to_string()))).collect();
208 Aliases { by_email }
209 }
210
211 pub fn canon(&self, email: &str) -> String {
214 let key = email.trim().to_lowercase();
215 self.by_email.get(&key).cloned().unwrap_or(key)
216 }
217
218 pub fn display(&self, email: &str) -> String {
220 self.by_email.get(&email.trim().to_lowercase()).cloned().unwrap_or_else(|| email.to_string())
221 }
222
223 pub fn same(&self, a: &str, b: &str) -> bool {
225 self.canon(a) == self.canon(b)
226 }
227}
228
229impl Config {
230 pub fn aliases(&self) -> Aliases {
231 Aliases::new(&self.engineers)
232 }
233}
234
235pub fn aliases() -> &'static Aliases {
239 static A: std::sync::OnceLock<Aliases> = std::sync::OnceLock::new();
240 A.get_or_init(|| {
241 if cfg!(test) {
242 return Aliases::default();
243 }
244 load().ok().flatten().map(|c| c.aliases()).unwrap_or_default()
245 })
246}
247
248fn off() -> String {
249 "off".into()
250}
251
252#[derive(Debug, Clone, PartialEq, Eq)]
253pub enum Route {
254 Off,
256 Collective {
257 name: String,
258 home: PathBuf,
259 share: Share,
260 },
261}
262
263pub fn config_path() -> PathBuf {
264 std::env::var("BORG_CONFIG")
265 .map(PathBuf::from)
266 .unwrap_or_else(|_| PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(".config/borg/collectives.json"))
267}
268
269pub fn load() -> Result<Option<Config>, String> {
272 load_from(&config_path())
273}
274
275pub fn load_from(p: &Path) -> Result<Option<Config>, String> {
277 match std::fs::read_to_string(p) {
278 Ok(t) => {
279 let cfg: Config = serde_json::from_str(&t).map_err(|e| format!("{}: {e}", p.display()))?;
280 cfg.check().map_err(|e| format!("{}: {e}", p.display()))?;
281 Ok(Some(cfg))
282 }
283 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
284 Err(e) => Err(format!("{}: {e}", p.display())),
285 }
286}
287
288impl Config {
289 pub fn check(&self) -> Result<(), String> {
291 if let Some(p) = &self.personal
292 && !self.collectives.iter().any(|c| &c.name == p && c.share == Share::Local)
293 {
294 return Err(format!("personal: {p:?} is not a collective with \"share\": \"local\""));
295 }
296 let mut seen: std::collections::HashMap<String, &str> = std::collections::HashMap::new();
297 for c in &self.collectives {
298 if let Some(other) = seen.insert(store_name(&c.name).to_lowercase(), &c.name) {
299 return Err(format!("collectives {other:?} and {:?} would share one store; rename one", c.name));
300 }
301 }
302 let mut names = std::collections::HashSet::new();
303 let mut owner: std::collections::HashMap<String, &str> = std::collections::HashMap::new();
304 for e in &self.engineers {
305 if e.name.trim().is_empty() {
306 return Err("engineers: an entry has no name".into());
307 }
308 if !names.insert(e.name.trim().to_lowercase()) {
309 return Err(format!("engineers: {:?} is listed twice; merge the entries", e.name));
310 }
311 if e.emails.is_empty() {
312 return Err(format!("engineers: {:?} lists no emails", e.name));
313 }
314 for m in e.emails.iter().map(|m| m.trim().to_lowercase()) {
315 if m.is_empty() {
316 return Err(format!("engineers: {:?} lists an empty email", e.name));
317 }
318 if let Some(other) = owner.insert(m.clone(), &e.name).filter(|o| *o != e.name) {
319 return Err(format!("engineers: {m} is listed under both {other:?} and {:?}", e.name));
320 }
321 }
322 }
323 Ok(())
324 }
325}
326
327pub(crate) fn expand(p: &str) -> PathBuf {
328 match p.strip_prefix("~/") {
329 Some(rest) => PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(rest),
330 None if p == "~" => PathBuf::from(std::env::var("HOME").unwrap_or_default()),
331 None => PathBuf::from(p),
332 }
333}
334
335pub(crate) fn normal(p: &Path) -> Vec<String> {
337 let mut out: Vec<String> = Vec::new();
338 for c in p.components() {
339 match c {
340 Component::ParentDir => {
341 out.pop();
342 }
343 Component::Normal(s) => out.push(s.to_string_lossy().into_owned()),
344 _ => {}
345 }
346 }
347 out
348}
349
350pub(crate) fn inside(path: &[String], prefix: &str) -> Option<usize> {
352 let pre = normal(&expand(prefix));
353 (!pre.is_empty() && path.len() >= pre.len() && path[..pre.len()] == pre[..]).then_some(pre.len())
354}
355
356fn store_name(name: &str) -> String {
359 let safe: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect();
360 if safe == name && !safe.is_empty() {
361 return safe;
362 }
363 let h = name.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ b as u64).wrapping_mul(0x0100_0000_01b3));
366 format!("{safe}-{:08x}", h as u32 ^ (h >> 32) as u32)
367}
368
369pub fn store(base: &Path, name: &str) -> PathBuf {
371 base.join("collectives").join(store_name(name))
372}
373
374pub fn root_of(home: &Path) -> PathBuf {
376 match home.parent() {
377 Some(p) if p.file_name().is_some_and(|n| n == "collectives") => p.parent().map_or_else(|| home.to_path_buf(), Path::to_path_buf),
378 _ => home.to_path_buf(),
379 }
380}
381
382pub fn personal_store(cfg: Option<&Config>, home: &Path) -> Option<PathBuf> {
386 let cfg = cfg?;
387 let base = root_of(home);
388 let local: Vec<&Entry> = cfg.collectives.iter().filter(|c| c.share == Share::Local).collect();
389 let pick = match &cfg.personal {
390 Some(name) => local.iter().find(|c| &c.name == name).copied(),
391 None if local.len() == 1 => local.first().copied(),
392 None => None,
393 }?;
394 Some(store(&base, &pick.name))
395}
396
397pub fn local_owner_of<'a>(cfg: Option<&'a Config>, home: &Path, base: &Path) -> Option<&'a str> {
400 cfg?.collectives.iter().find(|c| c.share == Share::Local && store(base, &c.name) == home).map(|c| c.name.as_str())
401}
402
403fn within(cwd: &str) -> impl Fn(&str) -> Option<usize> {
407 let lexical = expand(cwd);
408 let paths: Vec<Vec<String>> = std::iter::once(normal(&lexical)).chain(lexical.canonicalize().ok().map(|p| normal(&p))).collect();
409 move |prefix: &str| {
410 let real = expand(prefix).canonicalize().ok().map(|p| p.to_string_lossy().into_owned());
411 let prefixes = std::iter::once(prefix.to_string()).chain(real);
412 prefixes.filter_map(|pre| paths.iter().filter_map(|p| inside(p, &pre)).max()).max()
413 }
414}
415
416pub fn route(cfg: Option<&Config>, cwd: &str, base: &Path) -> Route {
418 let Some(cfg) = cfg else {
419 return Route::Collective { name: "default".into(), home: base.to_path_buf(), share: Share::Team };
420 };
421 if cwd.trim().is_empty() {
422 return Route::Off; }
424 let within = within(cwd);
425 if cfg.off.iter().any(|p| within(p).is_some()) {
426 return Route::Off;
427 }
428 let best = cfg.collectives.iter().filter_map(|c| c.paths.iter().filter_map(|p| within(p)).max().map(|n| (n, c))).max_by_key(|(n, _)| *n).map(|(_, c)| c);
429 let chosen = best.or_else(|| cfg.collectives.iter().find(|c| c.name == cfg.default && cfg.default != "off"));
430 match chosen {
431 Some(c) => Route::Collective { name: c.name.clone(), home: store(base, &c.name), share: c.share },
432 None => Route::Off,
433 }
434}
435
436pub fn may_sync(r: &Route) -> bool {
439 matches!(r, Route::Collective { share: Share::Team, .. })
440}
441
442#[cfg(test)]
443mod tests {
444 use super::*;
445
446 fn cfg(json: &str) -> Config {
447 serde_json::from_str(json).unwrap()
448 }
449
450 const CFG: &str = r#"{ "default": "off",
451 "off": ["/home/u/private/diary"],
452 "collectives": [
453 { "name": "work", "paths": ["/home/u/work-repos"], "share": "team" },
454 { "name": "private", "paths": ["/home/u/private"], "share": "local" },
455 { "name": "libs", "paths": ["/home/u/work-repos/shared-libs"] } ] }"#;
456
457 fn name(r: &Route) -> &str {
458 match r {
459 Route::Off => "off",
460 Route::Collective { name, .. } => name,
461 }
462 }
463
464 #[test]
465 fn routes_by_longest_whole_component_prefix() {
466 let c = cfg(CFG);
467 let base = Path::new("/b");
468 assert_eq!(name(&route(Some(&c), "/home/u/work-repos/harbor_orion/src", base)), "work");
469 assert_eq!(name(&route(Some(&c), "/home/u/work-repos/shared-libs/x", base)), "libs", "longest prefix wins");
470 assert_eq!(name(&route(Some(&c), "/home/u/work", base)), "off", "no partial component match");
471 assert_eq!(name(&route(Some(&c), "/home/u/work-repos-old/x", base)), "off", "work-repos-old is not work-repos");
472 assert_eq!(name(&route(Some(&c), "/home/u/private/finances", base)), "private");
473 assert_eq!(name(&route(Some(&c), "/home/u/work-repos/../private/x", base)), "private", "normalised before matching");
474 }
475
476 #[test]
477 fn a_symlink_and_its_target_route_alike() {
478 let root = std::env::temp_dir().join(format!("borg-route-link-{}", std::process::id()));
481 let _ = std::fs::remove_dir_all(&root);
482 std::fs::create_dir_all(root.join("real/work/secret/x")).unwrap();
483 std::os::unix::fs::symlink(root.join("real"), root.join("link")).unwrap();
484 let (real, link) = (root.join("real").display().to_string(), root.join("link").display().to_string());
485 let c = cfg(&format!(
486 r#"{{ "default": "off", "off": ["{link}/work/secret"], "collectives": [ {{ "name": "work", "paths": ["{real}/work"], "share": "team" }} ] }}"#
487 ));
488 let base = Path::new("/b");
489 assert_eq!(route(Some(&c), &format!("{real}/work/secret/x"), base), Route::Off, "an off path written through the link");
490 assert_eq!(route(Some(&c), &format!("{link}/work/secret/x"), base), Route::Off);
491 assert_eq!(name(&route(Some(&c), &format!("{link}/work"), base)), "work", "a cwd reported through the link");
492 let _ = std::fs::remove_dir_all(root);
493 }
494
495 #[test]
496 fn off_wins_and_unknown_is_off() {
497 let c = cfg(CFG);
498 let base = Path::new("/b");
499 assert_eq!(route(Some(&c), "/home/u/private/diary/2026", base), Route::Off, "off beats the private collective above it");
500 assert_eq!(route(Some(&c), "/somewhere/else", base), Route::Off, "default off");
501 assert_eq!(route(Some(&c), "", base), Route::Off, "no cwd: never guess");
502 let d = cfg(r#"{ "default": "work", "collectives": [ { "name": "work", "paths": ["/w"] } ] }"#);
503 assert_eq!(name(&route(Some(&d), "/somewhere/else", base)), "work");
504 }
505
506 #[test]
507 fn stores_are_separate_and_local_never_syncs() {
508 let c = cfg(CFG);
509 let base = Path::new("/b");
510 let corp = route(Some(&c), "/home/u/work-repos/a", base);
511 let private = route(Some(&c), "/home/u/private/a", base);
512 let (Route::Collective { home: h1, .. }, Route::Collective { home: h2, .. }) = (&corp, &private) else { panic!() };
513 assert_ne!(h1, h2);
514 assert_eq!(h2, &PathBuf::from("/b/collectives/private"));
515 assert!(may_sync(&corp));
516 assert!(!may_sync(&private), "a local collective never leaves the machine");
517 assert!(!may_sync(&Route::Off));
518 }
519
520 #[test]
521 fn similar_names_get_separate_stores() {
522 let c = cfg(r#"{ "collectives": [
523 { "name": "my team", "paths": ["/l"], "share": "local" },
524 { "name": "my_team", "paths": ["/t"], "share": "team" } ] }"#);
525 let base = Path::new("/b");
526 let (Route::Collective { home: local, .. }, Route::Collective { home: team, .. }) = (route(Some(&c), "/l/x", base), route(Some(&c), "/t/x", base))
527 else {
528 panic!()
529 };
530 assert_ne!(local, team, "a local collective never shares a store with a team one");
531 assert_eq!(team, PathBuf::from("/b/collectives/my_team"), "safe names keep their store");
532 assert!(local.to_string_lossy().starts_with("/b/collectives/my_team-"));
533 assert_ne!(store_name("a.b"), store_name("a_b"));
534 assert_ne!(store_name("équipe"), store_name("_quipe"));
535 assert_eq!(store_name("a.b"), store_name("a.b"), "stable");
536 assert!(c.check().is_ok());
537 assert_eq!(local_owner_of(Some(&c), &team, base), None);
538 assert_eq!(local_owner_of(Some(&c), &local, base), Some("my team"));
539 }
540
541 #[test]
542 fn a_config_whose_collectives_share_a_store_is_rejected() {
543 for json in [
544 r#"{ "collectives": [ { "name": "x", "paths": ["/a"], "share": "local" }, { "name": "x", "paths": ["/b"] } ] }"#,
545 r#"{ "collectives": [ { "name": "Team", "paths": ["/a"], "share": "local" }, { "name": "team", "paths": ["/b"] } ] }"#,
546 ] {
547 assert!(cfg(json).check().unwrap_err().contains("share one store"), "{json}");
548 let p = std::env::temp_dir().join(format!("borg-collective-dup-{}.json", std::process::id()));
549 std::fs::write(&p, json).unwrap();
550 assert!(load_from(&p).is_err(), "load rejects it, so everything routes off");
551 let _ = std::fs::remove_file(&p);
552 }
553 }
554
555 #[test]
556 fn expert_repos_behind_the_boundary_are_never_consulted() {
557 let c = cfg(r#"{ "default": "off", "off": ["/home/u/secret"],
558 "collectives": [
559 { "name": "work", "paths": ["/home/u/work"], "share": "team", "experts": [
560 { "name": "open", "repo": "/home/u/src/flowlib" },
561 { "name": "mine", "repo": "/home/u/work/sdk" },
562 { "name": "offrepo", "repo": "/home/u/secret/sdk" },
563 { "name": "privaterepo", "repo": "/home/u/private/flowlib" },
564 { "name": "sneaky", "repo": "/home/u/work/../private/x" } ] },
565 { "name": "private", "paths": ["/home/u/private"], "share": "local", "experts": [
566 { "name": "own", "repo": "/home/u/private/flowlib" },
567 { "name": "team", "repo": "/home/u/work/sdk" },
568 { "name": "off", "repo": "/home/u/secret/sdk" } ] } ] }"#);
569 let names = |cwd: &str| c.experts_for(cwd).iter().map(|e| e.name.clone()).collect::<Vec<_>>();
570 assert_eq!(names("/home/u/work/app"), ["open", "mine"], "off and local-private expert repos are dropped");
571 assert_eq!(names("/home/u/private/app"), ["own", "team"], "a local collective may read its own and team repos, never off ones");
572 assert!(names("/home/u/secret/app").is_empty());
573 let d = std::env::temp_dir().canonicalize().unwrap().join(format!("borg-collective-link-{}", std::process::id()));
575 let _ = std::fs::remove_dir_all(&d);
576 std::fs::create_dir_all(d.join("secret/sdk")).unwrap();
577 std::os::unix::fs::symlink(d.join("secret/sdk"), d.join("link")).unwrap();
578 let c = cfg(&format!(
579 r#"{{ "off": ["{0}/secret"], "collectives": [ {{ "name": "t", "paths": ["/w"], "experts": [ {{ "name": "x", "repo": "{0}/link" }} ] }} ] }}"#,
580 d.display()
581 ));
582 assert!(c.experts_for("/w/app").is_empty(), "a symlink into an off path");
583 let _ = std::fs::remove_dir_all(&d);
584 }
585
586 #[test]
587 fn engineers_map_aliases_case_insensitively() {
588 let c = cfg(r#"{ "engineers": [ { "name": "dana", "emails": ["Dana.Example@corp.example", "da@home.example"] } ] }"#);
589 assert!(c.check().is_ok());
590 let a = c.aliases();
591 assert_eq!(a.canon("dana.example@CORP.example"), "dana");
592 assert_eq!(a.canon(" da@home.example "), "dana");
593 assert!(a.same("Dana.Example@corp.example", "da@home.example"));
594 assert_eq!(a.canon("Ann@X"), "ann@x", "unlisted emails still compare case-insensitively");
595 assert_eq!(a.display("Ann@X"), "Ann@X", "and display as written");
596 assert_eq!(a.display("DA@home.example"), "dana");
597 assert_eq!(a.canon(""), "");
598 assert_eq!(cfg(CFG).aliases(), Aliases::default(), "absent section: no aliases");
599 }
600
601 #[test]
602 fn an_invalid_engineers_section_is_rejected_at_load() {
603 for (json, why) in [
604 (r#"{ "engineers": [ { "name": "", "emails": ["a@x"] } ] }"#, "has no name"),
605 (r#"{ "engineers": [ { "name": "a", "emails": [] } ] }"#, "lists no emails"),
606 (r#"{ "engineers": [ { "name": "a", "emails": ["a@x", " "] } ] }"#, "empty email"),
607 (r#"{ "engineers": [ { "name": "a", "emails": ["a@x"] }, { "name": "A", "emails": ["b@x"] } ] }"#, "listed twice"),
608 (r#"{ "engineers": [ { "name": "a", "emails": ["a@x"] }, { "name": "b", "emails": ["A@X"] } ] }"#, "listed under both"),
609 (r#"{ "engineers": [ { "name": "a", "email": ["a@x"] } ] }"#, "unknown field"),
610 (r#"{ "engineers": { "name": "a" } }"#, "invalid type"),
611 ] {
612 let p = std::env::temp_dir().join(format!("borg-collective-eng-{}.json", std::process::id()));
613 std::fs::write(&p, json).unwrap();
614 let e = load_from(&p).unwrap_err();
615 assert!(e.contains(why) && e.contains(&p.display().to_string()), "{json}: {e}");
616 let _ = std::fs::remove_file(&p);
617 }
618 }
619
620 #[test]
621 fn no_config_keeps_one_default_collective() {
622 let r = route(None, "/anything", Path::new("/b"));
623 assert_eq!(r, Route::Collective { name: "default".into(), home: PathBuf::from("/b"), share: Share::Team });
624 }
625}