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.
68pub fn dir(cfg: &Config, name: &str) -> Option<PathBuf> {
69    cfg.raw.remotes.get(name).map(|r| cfg.expand_path(&r.path))
70}
71
72/// Loads the remote corpus once per process; `None` when the directory is absent.
73pub fn load(cfg: &Config, name: &str) -> Option<Arc<Loaded>> {
74    let dir = dir(cfg, name)?;
75    let mut c = cache().lock().unwrap_or_else(|e| e.into_inner());
76    c.entry(dir.clone())
77        .or_insert_with(|| {
78            if !dir.is_dir() {
79                return None;
80            }
81            let rc = Config::discover(&dir).ok()?;
82            let corpus = Corpus::load(rc, &LoadOptions { include_local: false });
83            let graph = Graph::build(&corpus);
84            Some(Arc::new(Loaded { corpus, graph }))
85        })
86        .clone()
87}
88
89/// Resolves `<name>:<id>[#anchor]` against the remote repository.
90pub fn resolve(cfg: &Config, text: &str) -> Remote {
91    let Some((name, rest)) = split(cfg, text) else { return Remote::Local };
92    let name = name.to_string();
93    let Some(l) = load(cfg, &name) else {
94        return Remote::Absent { path: dir(cfg, &name).unwrap_or_default(), name };
95    };
96    let id = RefText::parse(rest).target;
97    match l.graph.resolve(rest) {
98        Resolution::Doc { idx, .. } => {
99            let d = &l.corpus.docs[idx];
100            Remote::Found {
101                name,
102                id: d.id.to_string(),
103                ty: d.id.ty.clone(),
104                title: d.title.clone().unwrap_or_default(),
105                file: l.corpus.cfg.root.join(&d.path),
106            }
107        }
108        Resolution::MissingAnchor { anchor, .. } => Remote::MissingAnchor { name, id, anchor },
109        Resolution::Ambiguous(list) => {
110            Remote::Ambiguous { name, ids: list.iter().map(|&i| l.corpus.docs[i].id.to_string()).collect() }
111        }
112        Resolution::Missing => Remote::Missing { name, id },
113    }
114}
115
116/// The id and source revision (see `translation::rev_of`) of the remote document `<name>:<id>`,
117/// or `None` when it is not a remote reference that resolves.
118pub fn rev(cfg: &Config, text: &str) -> Option<(String, String)> {
119    let (name, rest) = split(cfg, text)?;
120    let l = load(cfg, name)?;
121    match l.graph.resolve(rest) {
122        Resolution::Doc { idx, .. } => {
123            Some((format!("{name}:{}", l.corpus.docs[idx].id), crate::translation::rev_of(&l.corpus, idx)?))
124        }
125        _ => None,
126    }
127}
128/// A document in this repository or a remote that names another repository's document.
129#[derive(Debug, Clone, PartialEq, Eq)]
130pub struct Consumer {
131    /// `.` for this repository, else the remote's name.
132    pub repo: String,
133    pub id: String,
134    pub path: String,
135    /// `rel.<kind>` or `pins`.
136    pub via: String,
137}
138
139/// The documents, here and in every remote on disk, whose relations or pins name the document at
140/// `target` (an absolute file path) through one of their own remotes. Only frontmatter is read;
141/// a remote's own remotes are resolved from directories already on disk, never fetched.
142pub fn consumers(cfg: &Config, here: &Corpus, target: &std::path::Path) -> Vec<Consumer> {
143    let canon = |p: &std::path::Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
144    let target = canon(target);
145    let mut repos: Vec<(String, Arc<Loaded>)> = vec![];
146    for name in cfg.raw.remotes.keys() {
147        if let Some(l) = load(cfg, name) {
148            repos.push((name.clone(), l));
149        }
150    }
151    let mut out = vec![];
152    let mut scan = |repo: &str, c: &Corpus| {
153        for d in &c.docs {
154            let mut refs: Vec<(String, String)> =
155                d.rel().into_iter().flat_map(|(k, vs)| vs.into_iter().map(move |v| (format!("rel.{k}"), v))).collect();
156            if let Some(serde_json::Value::Object(m)) = d.fm().and_then(|m| m.get("pins")) {
157                refs.extend(m.keys().map(|k| ("pins".to_string(), k.clone())));
158            }
159            for (via, v) in refs {
160                if let Remote::Found { file, .. } = resolve(&c.cfg, &v)
161                    && canon(&file) == target
162                {
163                    let u = Consumer { repo: repo.to_string(), id: d.id.to_string(), path: d.path.clone(), via };
164                    if !out.contains(&u) {
165                        out.push(u);
166                    }
167                }
168            }
169        }
170    };
171    scan(".", here);
172    for (name, l) in &repos {
173        scan(name, &l.corpus);
174    }
175    out
176}
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181    use crate::config::types::RawConfig;
182
183    fn write(p: &std::path::Path, s: &str) {
184        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
185        std::fs::write(p, s).unwrap();
186    }
187
188    #[test]
189    fn resolves_ids_in_a_sibling_repository() {
190        let tmp = tempfile::tempdir().unwrap();
191        let shared = tmp.path().join("shared");
192        write(&shared.join("spec.toml"), "[spec]\nschema = 1\n");
193        write(
194            &shared.join(".spec/guide/setup.guide.md"),
195            "---\nid: guide:root/setup\ntitle: Setup\nstatus: active\n---\n\n# Setup\n\n## Install {#install}\n",
196        );
197        let mut raw = RawConfig::default();
198        raw.remotes.insert("org".into(), crate::config::types::RemoteRoot { path: shared.to_string_lossy().into() });
199        raw.remotes.insert("gone".into(), crate::config::types::RemoteRoot { path: "/nonexistent/x".into() });
200        let cfg = Config::from_raw(tmp.path().join("app"), raw, false);
201        assert_eq!(resolve(&cfg, "guide:x/y"), Remote::Local);
202        match resolve(&cfg, "org:guide:root/setup#install") {
203            Remote::Found { id, ty, .. } => assert_eq!((id.as_str(), ty.as_str()), ("guide:root/setup", "guide")),
204            other => panic!("{other:?}"),
205        }
206        assert!(matches!(resolve(&cfg, "org:guide:root/nope"), Remote::Missing { .. }));
207        assert!(matches!(resolve(&cfg, "org:guide:root/setup#zzz"), Remote::MissingAnchor { .. }));
208        assert!(matches!(resolve(&cfg, "gone:guide:a/b"), Remote::Absent { .. }));
209    }
210}