Skip to main content

specfold_core/
remotes.rs

1//! Documents in other repositories. `[remotes.<name>] path = "../shared"` lets a reference or a
2//! relation name a document there as `<name>:<id>` (`shared:adr:org/20261030000000`). The other
3//! repository is read from a directory already on disk and never written. A remote whose
4//! directory is absent (a CI job without that checkout) is skipped, not reported; a remote that
5//! is present but lacks the id is an error like any missing document.
6
7use crate::config::Config;
8use crate::corpus::{Corpus, LoadOptions};
9use crate::graph::{Graph, Resolution};
10use crate::model::RefText;
11use std::collections::HashMap;
12use std::path::PathBuf;
13use std::sync::{Arc, Mutex, OnceLock};
14
15/// What `<name>:<id>` names.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum Remote {
18    /// Not a remote reference: no configured remote of that name.
19    Local,
20    /// The remote is configured but its directory is not on disk.
21    Absent {
22        name: String,
23        path: PathBuf,
24    },
25    /// One document: its id, type, title and absolute file path.
26    Found {
27        name: String,
28        id: String,
29        ty: String,
30        title: String,
31        file: PathBuf,
32    },
33    Missing {
34        name: String,
35        id: String,
36    },
37    MissingAnchor {
38        name: String,
39        id: String,
40        anchor: String,
41    },
42    Ambiguous {
43        name: String,
44        ids: Vec<String>,
45    },
46}
47
48pub struct Loaded {
49    pub corpus: Corpus,
50    pub graph: Graph,
51}
52
53type Cache = Mutex<HashMap<PathBuf, Option<Arc<Loaded>>>>;
54
55fn cache() -> &'static Cache {
56    static C: OnceLock<Cache> = OnceLock::new();
57    C.get_or_init(Default::default)
58}
59
60/// The remote a reference names, and the rest of the reference. A configured type name is never a
61/// remote, so `adr:x/y` stays a local id even with a remote called `adr`.
62pub fn split<'a>(cfg: &Config, text: &'a str) -> Option<(&'a str, &'a str)> {
63    let (name, rest) = text.trim().split_once(':')?;
64    (cfg.raw.remotes.contains_key(name) && cfg.registry.get(name).is_none()).then_some((name, rest))
65}
66
67/// The remote's directory: the first of `path` and `paths` on disk, else `path`.
68pub fn dir(cfg: &Config, name: &str) -> Option<PathBuf> {
69    let r = cfg.raw.remotes.get(name)?;
70    let first = cfg.expand_path(&r.path);
71    Some(r.paths.iter().map(|p| cfg.expand_path(p)).find(|p| p.is_dir()).filter(|_| !first.is_dir()).unwrap_or(first))
72}
73
74/// A governed path that belongs to another project: written `<remote>:<path>`, or inside a
75/// remote checked out within this repository, or inside a submodule no owner kind claims. P1 and
76/// L5 leave it out; D1 still matches it.
77pub fn is_external(cfg: &Config, governs: &str) -> bool {
78    if split(cfg, governs).is_some() {
79        return true;
80    }
81    let g = governs.trim_start_matches("./").trim_end_matches('/');
82    let under = |p: &str| {
83        let p = p.trim_start_matches("./").trim_end_matches('/');
84        !p.is_empty() && (g == p || g.starts_with(&format!("{p}/")))
85    };
86    inner_projects(cfg).iter().any(|p| under(p))
87}
88
89/// A1: the auto-registered submodule remote whose directory holds `rel`, and the path inside it.
90pub fn submodule_at(cfg: &Config, rel: &str) -> Option<(String, String)> {
91    cfg.raw.remotes.iter().filter(|(_, r)| r.auto).find_map(|(name, r)| {
92        let p = r.path.trim_end_matches('/');
93        let inner = if rel == p { "" } else { rel.strip_prefix(p)?.strip_prefix('/')? };
94        Some((name.clone(), inner.to_string()))
95    })
96}
97
98/// Whether the submodule at `path` is a project of its own rather than code of an owner here. A
99/// submodule an owner kind claims is that owner's code, with or without its own spec.toml (a
100/// product split into its own repository); any other submodule is vendored or another project.
101fn own_project(owners: &crate::workspace::Owners, path: &str) -> bool {
102    owners.by_path(path).is_none()
103}
104
105/// Projects inside this repository: submodules of their own and remotes checked out here, once
106/// per root.
107fn inner_projects(cfg: &Config) -> Vec<String> {
108    static C: OnceLock<Mutex<HashMap<PathBuf, Vec<String>>>> = OnceLock::new();
109    let mut c = C.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
110    c.entry(cfg.root.clone())
111        .or_insert_with(|| {
112            let owners = crate::workspace::Owners::discover(cfg);
113            let mut v: Vec<String> =
114                crate::workspace::vcs::gitlinks(&cfg.root).into_iter().filter(|p| own_project(&owners, p)).collect();
115            v.extend(cfg.raw.owners.nested_dirs().map(String::from));
116            // Submodules registered as remotes by `submodule_remotes` were judged above.
117            for r in cfg.raw.remotes.values().filter(|r| !r.auto) {
118                for p in std::iter::once(&r.path).chain(&r.paths) {
119                    if !p.starts_with("..") && !p.starts_with('/') && !p.starts_with('~') {
120                        v.push(p.clone());
121                    }
122                }
123            }
124            v
125        })
126        .clone()
127}
128
129/// Loads the remote corpus once per process; `None` when the directory is absent.
130pub fn load(cfg: &Config, name: &str) -> Option<Arc<Loaded>> {
131    let dir = dir(cfg, name)?;
132    let mut c = cache().lock().unwrap_or_else(|e| e.into_inner());
133    c.entry(dir.clone())
134        .or_insert_with(|| {
135            if !dir.is_dir() {
136                return None;
137            }
138            let start = std::time::Instant::now();
139            let rc = Config::discover(&dir).ok()?;
140            let corpus = Corpus::load(rc, &LoadOptions { include_local: false });
141            let graph = Graph::build(&corpus);
142            if crate::corpus::trace::enabled() {
143                let ms = start.elapsed().as_secs_f64() * 1000.0;
144                eprintln!("specfold:   remote {name:<12} {ms:>7.1} ms, {} documents", corpus.docs.len());
145            }
146            Some(Arc::new(Loaded { corpus, graph }))
147        })
148        .clone()
149}
150
151/// Resolves `<name>:<id>[#anchor]` against the remote repository.
152pub fn resolve(cfg: &Config, text: &str) -> Remote {
153    let Some((name, rest)) = split(cfg, text) else { return Remote::Local };
154    let name = name.to_string();
155    let Some(l) = load(cfg, &name) else {
156        return Remote::Absent { path: dir(cfg, &name).unwrap_or_default(), name };
157    };
158    let id = RefText::parse(rest).target;
159    match l.graph.resolve(rest) {
160        Resolution::Doc { idx, .. } => {
161            let d = &l.corpus.docs[idx];
162            Remote::Found {
163                name,
164                id: d.id.to_string(),
165                ty: d.id.ty.clone(),
166                title: d.title.clone().unwrap_or_default(),
167                file: l.corpus.cfg.root.join(&d.path),
168            }
169        }
170        Resolution::MissingAnchor { anchor, .. } => Remote::MissingAnchor { name, id, anchor },
171        Resolution::Ambiguous(list) => {
172            Remote::Ambiguous { name, ids: list.iter().map(|&i| l.corpus.docs[i].id.to_string()).collect() }
173        }
174        Resolution::Missing => Remote::Missing { name, id },
175    }
176}
177
178/// The id and source revision (see `translation::rev_of`) of the remote document `<name>:<id>`,
179/// or `None` when it is not a remote reference that resolves.
180pub fn rev(cfg: &Config, text: &str) -> Option<(String, String)> {
181    let (name, rest) = split(cfg, text)?;
182    let l = load(cfg, name)?;
183    match l.graph.resolve(rest) {
184        Resolution::Doc { idx, .. } => {
185            Some((format!("{name}:{}", l.corpus.docs[idx].id), crate::translation::rev_of(&l.corpus, idx)?))
186        }
187        _ => None,
188    }
189}
190/// F2: the status of the remote document `<name>:<id>` and, when another document there
191/// supersedes it, that document's id (`<name>:<id>`).
192pub fn status(cfg: &Config, text: &str) -> Option<(String, Option<String>)> {
193    let (name, rest) = split(cfg, text)?;
194    let l = load(cfg, name)?;
195    let Resolution::Doc { idx, .. } = l.graph.resolve(rest) else { return None };
196    let me = l.corpus.docs[idx].id.to_string();
197    let by = l.corpus.docs.iter().find(|d| d.rel().get("supersedes").is_some_and(|v| v.contains(&me)));
198    Some((l.corpus.docs[idx].status().unwrap_or_default(), by.map(|d| format!("{name}:{}", d.id))))
199}
200
201/// A document in this repository or a remote that names another repository's document.
202#[derive(Debug, Clone, PartialEq, Eq)]
203pub struct Consumer {
204    /// `.` for this repository, else the remote's name.
205    pub repo: String,
206    pub id: String,
207    pub path: String,
208    /// `rel.<kind>` or `pins`.
209    pub via: String,
210}
211
212/// The documents, here and in every remote on disk, whose relations or pins name the document at
213/// `target` (an absolute file path) through one of their own remotes. Only frontmatter is read;
214/// a remote's own remotes are resolved from directories already on disk, never fetched.
215pub fn consumers(cfg: &Config, here: &Corpus, target: &std::path::Path) -> Vec<Consumer> {
216    let canon = |p: &std::path::Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
217    let target = canon(target);
218    let mut repos: Vec<(String, Arc<Loaded>)> = vec![];
219    for name in cfg.raw.remotes.keys() {
220        if let Some(l) = load(cfg, name) {
221            repos.push((name.clone(), l));
222        }
223    }
224    let mut out = vec![];
225    let mut scan = |repo: &str, c: &Corpus| {
226        for d in &c.docs {
227            let mut refs: Vec<(String, String)> =
228                d.rel().into_iter().flat_map(|(k, vs)| vs.into_iter().map(move |v| (format!("rel.{k}"), v))).collect();
229            if let Some(serde_json::Value::Object(m)) = d.fm().and_then(|m| m.get("pins")) {
230                refs.extend(m.keys().map(|k| ("pins".to_string(), k.clone())));
231            }
232            for (via, v) in refs {
233                if let Remote::Found { file, .. } = resolve(&c.cfg, &v)
234                    && canon(&file) == target
235                {
236                    let u = Consumer { repo: repo.to_string(), id: d.id.to_string(), path: d.path.clone(), via };
237                    if !out.contains(&u) {
238                        out.push(u);
239                    }
240                }
241            }
242        }
243    };
244    scan(".", here);
245    for (name, l) in &repos {
246        scan(name, &l.corpus);
247    }
248    out
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254    use crate::config::types::RawConfig;
255
256    fn write(p: &std::path::Path, s: &str) {
257        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
258        std::fs::write(p, s).unwrap();
259    }
260
261    #[test]
262    fn resolves_ids_in_a_sibling_repository() {
263        let tmp = tempfile::tempdir().unwrap();
264        let shared = tmp.path().join("shared");
265        write(&shared.join("spec.toml"), "[spec]\nschema = 1\n");
266        write(
267            &shared.join(".spec/guide/setup.guide.md"),
268            "---\nid: guide:root/setup\ntitle: Setup\nstatus: active\n---\n\n# Setup\n\n## Install {#install}\n",
269        );
270        let mut raw = RawConfig::default();
271        raw.remotes.insert(
272            "org".into(),
273            crate::config::types::RemoteRoot { path: shared.to_string_lossy().into(), paths: vec![], auto: false },
274        );
275        raw.remotes.insert(
276            "gone".into(),
277            crate::config::types::RemoteRoot {
278                path: "/nonexistent/x".into(),
279                paths: vec![shared.to_string_lossy().into()],
280                auto: false,
281            },
282        );
283        let cfg = Config::from_raw(tmp.path().join("app"), raw, false);
284        assert_eq!(resolve(&cfg, "guide:x/y"), Remote::Local);
285        match resolve(&cfg, "org:guide:root/setup#install") {
286            Remote::Found { id, ty, .. } => assert_eq!((id.as_str(), ty.as_str()), ("guide:root/setup", "guide")),
287            other => panic!("{other:?}"),
288        }
289        assert!(matches!(resolve(&cfg, "org:guide:root/nope"), Remote::Missing { .. }));
290        assert!(matches!(resolve(&cfg, "org:guide:root/setup#zzz"), Remote::MissingAnchor { .. }));
291        assert!(matches!(resolve(&cfg, "gone:guide:root/setup"), Remote::Found { .. }), "a later candidate path");
292        assert!(is_external(&cfg, "org:src/lib.rs") && !is_external(&cfg, "src/lib.rs"));
293    }
294}