Skip to main content

specfold_core/config/
clone_path.rs

1//! A path inside a public repository mapped to a private spec root (roots.toml), named the way
2//! the spec root names it: below the `[public]` path the repository is a copy of.
3
4use super::{Config, private_root};
5use crate::workspace::vcs;
6use std::path::{Path, PathBuf};
7
8/// Where a path outside the spec root lands.
9#[derive(Debug, PartialEq, Eq)]
10pub enum ClonePath {
11    /// Not inside a repository mapped to this spec root.
12    Outside,
13    /// The spec-root-relative path, below the public path the repository is a copy of.
14    Mapped(String),
15    /// Inside the mapped repository, but no public path of the spec root is named for it.
16    Unmapped {
17        /// The mapped repository.
18        clone: PathBuf,
19        /// The path relative to that repository.
20        rel: String,
21    },
22}
23
24/// Locates `abs` (absolute, symbolic links resolved) when it lies in a repository that the
25/// user-level roots.toml maps to `cfg.spec_home`.
26pub fn locate(cfg: &Config, abs: &Path) -> ClonePath {
27    match clone_of(cfg, abs) {
28        Some(clone) => locate_in(cfg, &clone, abs),
29        None => ClonePath::Outside,
30    }
31}
32
33/// The repository holding `abs` (its canonical root) when roots.toml maps it to `cfg.spec_home`.
34pub fn clone_of(cfg: &Config, abs: &Path) -> Option<PathBuf> {
35    let clone = existing_ancestor(abs).and_then(|d| vcs::git_root(&d)).and_then(|c| c.canonicalize().ok())?;
36    let m = private_root::mapping(&clone)?;
37    (m.spec.canonicalize().ok() == cfg.spec_home.canonicalize().ok()).then_some(clone)
38}
39
40/// `abs` inside `clone`, a repository [`clone_of`] found, named the way the spec root names it.
41pub fn locate_in(cfg: &Config, clone: &Path, abs: &Path) -> ClonePath {
42    let Some(m) = private_root::mapping(clone) else { return ClonePath::Outside };
43    let Some(rel) = crate::paths::rel_of(clone, abs) else { return ClonePath::Outside };
44    let clone = clone.to_path_buf();
45    match public_path(cfg, &clone, m.public.as_deref()) {
46        Some(p) if rel.is_empty() => ClonePath::Mapped(p),
47        Some(p) => ClonePath::Mapped(format!("{p}/{rel}")),
48        None => ClonePath::Unmapped { clone, rel },
49    }
50}
51
52/// The public path the repository is a copy of: the entry's `public` key, the only public path,
53/// or the one whose last component is the repository's directory name.
54fn public_path(cfg: &Config, clone: &Path, named: Option<&str>) -> Option<String> {
55    let clean = |p: &str| p.trim_start_matches("./").trim_end_matches('/').to_string();
56    if let Some(p) = named {
57        return Some(clean(p));
58    }
59    let public = &cfg.raw.public;
60    let mut all: Vec<String> = public
61        .paths
62        .iter()
63        .chain(public.companion.keys())
64        .map(|p| clean(p))
65        .filter(|p| !p.is_empty() && !p.contains(['*', '?', '[', '{']))
66        .collect();
67    all.sort();
68    all.dedup();
69    if let [only] = all.as_slice() {
70        return Some(only.clone());
71    }
72    let name = clone.file_name()?.to_str()?;
73    let same: Vec<&String> = all.iter().filter(|p| p.rsplit('/').next() == Some(name)).collect();
74    match same.as_slice() {
75        [one] => Some((*one).clone()),
76        _ => None,
77    }
78}
79
80fn existing_ancestor(abs: &Path) -> Option<PathBuf> {
81    abs.ancestors().find(|a| a.is_dir()).map(Path::to_path_buf)
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87    use crate::config::types::RawConfig;
88
89    fn cfg(paths: &[&str]) -> Config {
90        let mut raw = RawConfig::default();
91        raw.public.paths = paths.iter().map(|p| p.to_string()).collect();
92        Config::from_raw(PathBuf::from("/r"), raw, false)
93    }
94
95    #[test]
96    fn public_path_takes_the_only_one_or_the_one_named_like_the_clone() {
97        let clone = Path::new("/w/cli");
98        assert_eq!(public_path(&cfg(&["packages/tool"]), clone, None).as_deref(), Some("packages/tool"));
99        assert_eq!(public_path(&cfg(&["libs/auth", "packages/cli/"]), clone, None).as_deref(), Some("packages/cli"));
100        assert_eq!(public_path(&cfg(&["libs/auth", "libs/shop"]), clone, None), None);
101        assert_eq!(public_path(&cfg(&[]), clone, None), None);
102        assert_eq!(
103            public_path(&cfg(&["libs/auth", "libs/shop"]), clone, Some("libs/shop")).as_deref(),
104            Some("libs/shop")
105        );
106    }
107}