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.root`.
26pub fn locate(cfg: &Config, abs: &Path) -> ClonePath {
27    let Some(clone) = existing_ancestor(abs).and_then(|d| vcs::git_root(&d)).and_then(|c| c.canonicalize().ok()) else {
28        return ClonePath::Outside;
29    };
30    let Some(m) = private_root::mapping(&clone) else { return ClonePath::Outside };
31    if m.spec.canonicalize().ok() != cfg.root.canonicalize().ok() {
32        return ClonePath::Outside;
33    }
34    let Ok(below) = abs.strip_prefix(&clone) else { return ClonePath::Outside };
35    let rel = below.to_string_lossy().replace('\\', "/");
36    match public_path(cfg, &clone, m.public.as_deref()) {
37        Some(p) if rel.is_empty() => ClonePath::Mapped(p),
38        Some(p) => ClonePath::Mapped(format!("{p}/{rel}")),
39        None => ClonePath::Unmapped { clone, rel },
40    }
41}
42
43/// The public path the repository is a copy of: the entry's `public` key, the only public path,
44/// or the one whose last component is the repository's directory name.
45fn public_path(cfg: &Config, clone: &Path, named: Option<&str>) -> Option<String> {
46    let clean = |p: &str| p.trim_start_matches("./").trim_end_matches('/').to_string();
47    if let Some(p) = named {
48        return Some(clean(p));
49    }
50    let public = &cfg.raw.public;
51    let mut all: Vec<String> = public
52        .paths
53        .iter()
54        .chain(public.companion.keys())
55        .map(|p| clean(p))
56        .filter(|p| !p.is_empty() && !p.contains(['*', '?', '[', '{']))
57        .collect();
58    all.sort();
59    all.dedup();
60    if let [only] = all.as_slice() {
61        return Some(only.clone());
62    }
63    let name = clone.file_name()?.to_str()?;
64    let same: Vec<&String> = all.iter().filter(|p| p.rsplit('/').next() == Some(name)).collect();
65    match same.as_slice() {
66        [one] => Some((*one).clone()),
67        _ => None,
68    }
69}
70
71fn existing_ancestor(abs: &Path) -> Option<PathBuf> {
72    abs.ancestors().find(|a| a.is_dir()).map(Path::to_path_buf)
73}
74
75#[cfg(test)]
76mod tests {
77    use super::*;
78    use crate::config::types::RawConfig;
79
80    fn cfg(paths: &[&str]) -> Config {
81        let mut raw = RawConfig::default();
82        raw.public.paths = paths.iter().map(|p| p.to_string()).collect();
83        Config::from_raw(PathBuf::from("/r"), raw, false)
84    }
85
86    #[test]
87    fn public_path_takes_the_only_one_or_the_one_named_like_the_clone() {
88        let clone = Path::new("/w/cli");
89        assert_eq!(public_path(&cfg(&["packages/tool"]), clone, None).as_deref(), Some("packages/tool"));
90        assert_eq!(public_path(&cfg(&["libs/auth", "packages/cli/"]), clone, None).as_deref(), Some("packages/cli"));
91        assert_eq!(public_path(&cfg(&["libs/auth", "libs/shop"]), clone, None), None);
92        assert_eq!(public_path(&cfg(&[]), clone, None), None);
93        assert_eq!(
94            public_path(&cfg(&["libs/auth", "libs/shop"]), clone, Some("libs/shop")).as_deref(),
95            Some("libs/shop")
96        );
97    }
98}