Skip to main content

specfold_core/config/
reader.rs

1//! Finds and loads spec.toml, and answers questions about the loaded configuration.
2
3use super::defaults::{self, CONFIG_FILE};
4use super::paths;
5use super::types::RawConfig;
6use crate::model::registry::Registry;
7use crate::workspace::vcs;
8use anyhow::{Context, Result, bail};
9use std::path::{Path, PathBuf};
10
11#[derive(Debug, Clone)]
12pub struct Config {
13    /// Repository root: the directory holding spec.toml.
14    pub root: PathBuf,
15    pub raw: RawConfig,
16    pub registry: Registry,
17    /// True when no spec.toml was found and defaults are in use.
18    pub implicit: bool,
19}
20
21impl Config {
22    /// Finds spec.toml in `start` or its ancestors. Without one, the nearest git root (or `start`)
23    /// is used with defaults, so the tool works in any directory.
24    pub fn discover(start: &Path) -> Result<Self> {
25        let start = start.canonicalize().with_context(|| format!("cannot open {}", start.display()))?;
26        let mut dir = Some(start.as_path());
27        while let Some(d) = dir {
28            let candidate = d.join(CONFIG_FILE);
29            if candidate.is_file() {
30                return Self::load(&candidate);
31            }
32            dir = d.parent();
33        }
34        let root = vcs::git_root(&start).unwrap_or(start);
35        // F1: a public repository whose documents live in a mapped private directory.
36        if let Some(private) = super::private_root::mapped(&root) {
37            let toml = private.join(CONFIG_FILE);
38            if toml.is_file() {
39                return Self::load(&toml);
40            }
41            bail!(
42                "{} is mapped to {} in {}, which has no {CONFIG_FILE}; next: spec -C {} init --write",
43                root.display(),
44                private.display(),
45                super::private_root::file().unwrap_or_default().display(),
46                private.display()
47            );
48        }
49        Ok(Self::from_raw(root, RawConfig::default(), true))
50    }
51
52    pub fn load(path: &Path) -> Result<Self> {
53        let text = std::fs::read_to_string(path).with_context(|| format!("cannot read {}", path.display()))?;
54        let raw: RawConfig = match toml::from_str(&text) {
55            Ok(r) => r,
56            Err(e) => {
57                let (_, changes) = super::upgrade::plan(&text, super::upgrade::RENAMED);
58                let hint =
59                    if changes.is_empty() { String::new() } else { "; renamed keys: spec init --upgrade".into() };
60                return Err(anyhow::Error::new(e).context(format!("invalid {}{hint}", path.display())));
61            }
62        };
63        if raw.spec.schema > defaults::schema() {
64            return Err(newer_schema(path, raw.spec.schema));
65        }
66        if raw.spec.schema != defaults::schema() {
67            bail!(
68                "{}: schema {} is older than this version reads ({}); preview the upgrade: spec init --upgrade",
69                path.display(),
70                raw.spec.schema,
71                defaults::schema()
72            );
73        }
74        // C141: one guard with a mistyped range would stop every `spec guard` run later.
75        for g in &raw.guards {
76            if !matches!(g.range.as_str(), "staged" | "push" | "all") && !g.range.contains("..") {
77                bail!(
78                    "{}: guard '{}' has range = \"{}\"; use \"staged\", \"push\", \"all\" or a git range such as \"origin/main..HEAD\" (spec explain config)",
79                    path.display(),
80                    g.name,
81                    g.range
82                );
83            }
84        }
85        for k in &raw.owners.kinds {
86            if let Some(why) = crate::workspace::owners::patterns::kind_pattern_problem(&k.pattern) {
87                bail!("{}: {why}; next: spec explain config", path.display());
88            }
89        }
90        if let Some(n) = raw.owners.nested.iter().find(|n| n.contains(['*', '?', '[', '{']) || n.starts_with("..")) {
91            bail!(
92                "{}: [owners] nested has \"{n}\"; name each nested project by its directory inside the repository, e.g. packages/cli; next: spec explain config",
93                path.display()
94            );
95        }
96        if let Some((why, value)) = super::validate::pattern_problem(&raw) {
97            let at = text.lines().position(|l| l.contains(&value)).map(|n| format!(" at line {}", n + 1));
98            bail!("{}{}: {why}; next: spec explain config", path.display(), at.unwrap_or_default());
99        }
100        // C184: guards sharing a baseline file overwrite each other's entries on --write-baseline.
101        let mut seen: Vec<(&str, String)> = Vec::new();
102        for g in &raw.guards {
103            let Some(b) = g.baseline.as_deref() else { continue };
104            let b = same_file_key(path.parent().unwrap_or(Path::new(".")), b);
105            if let Some((other, _)) = seen.iter().find(|(_, x)| *x == b) {
106                bail!(
107                    "{}: guards '{other}' and '{}' both write the baseline file \"{b}\"; give each guard its own baseline file; next: spec explain config",
108                    path.display(),
109                    g.name
110                );
111            }
112            seen.push((&g.name, b));
113        }
114        let root = path.parent().unwrap_or(Path::new(".")).to_path_buf();
115        Ok(Self::from_raw(root, raw, false))
116    }
117
118    pub fn from_raw(root: PathBuf, mut raw: RawConfig, implicit: bool) -> Self {
119        if raw.spec.submodule_remotes {
120            for (name, path) in submodule_specs(&root) {
121                raw.remotes.entry(name).or_insert(crate::config::types::RemoteRoot { path, paths: vec![], auto: true });
122            }
123        }
124        // C1: a nested project is a remote whether or not submodule_remotes is set.
125        for (name, path) in crate::workspace::nested::remotes(&root, &raw.owners) {
126            raw.remotes.entry(name).or_insert(crate::config::types::RemoteRoot { path, paths: vec![], auto: true });
127        }
128        for (name, dir) in super::private_root::prefixes() {
129            let path = dir.to_string_lossy().into_owned();
130            raw.remotes.entry(name).or_insert(crate::config::types::RemoteRoot { path, paths: vec![], auto: false });
131        }
132        let registry = Registry::new(&raw.types);
133        Config { root, raw, registry, implicit }
134    }
135
136    pub fn spec_dir(&self) -> &str {
137        &self.raw.spec.dir
138    }
139
140    pub fn manifests(&self) -> Vec<String> {
141        match &self.raw.owners.manifests {
142            Some(m) => m.clone(),
143            None => defaults::MANIFESTS.iter().map(|s| s.to_string()).collect(),
144        }
145    }
146
147    pub fn root_owner(&self) -> &str {
148        &self.raw.owners.root
149    }
150
151    pub fn local_dir(&self) -> &str {
152        &self.raw.local.path
153    }
154
155    pub fn expand_path(&self, p: &str) -> PathBuf {
156        paths::expand(&self.root, p)
157    }
158}
159
160/// Submodules listed in `.gitmodules` that carry their own spec.toml, as (remote name, path).
161fn submodule_specs(root: &Path) -> Vec<(String, String)> {
162    let Ok(text) = std::fs::read_to_string(root.join(".gitmodules")) else { return vec![] };
163    let mut out = vec![];
164    for line in text.lines() {
165        let Some((k, v)) = line.split_once('=') else { continue };
166        if k.trim() != "path" {
167            continue;
168        }
169        let path = v.trim().trim_matches('"').trim_end_matches('/').to_string();
170        let name = path.rsplit('/').next().unwrap_or(&path).to_string();
171        if !name.is_empty() && root.join(&path).join("spec.toml").is_file() {
172            out.push((name, path));
173        }
174    }
175    out
176}
177
178/// The refusal for a spec.toml whose schema is newer than this binary reads; `spec check` and
179/// `spec init --upgrade` (C170) both give it.
180pub fn newer_schema(path: &Path, schema: u32) -> anyhow::Error {
181    anyhow::anyhow!(
182        "{}: schema {schema} was written by a newer specfold (this version reads {}); install the latest spec",
183        path.display(),
184        defaults::schema()
185    )
186}
187
188/// C186: a baseline path as one string per file: relative to the repository root, with `.` and
189/// `..` resolved lexically, so `./b.json`, `x/../b.json` and `<root>/b.json` compare equal.
190fn same_file_key(root: &Path, p: &str) -> String {
191    // C194/C195: resolve the deepest part of the path that exists (symbolic links included)
192    // before any lexical clean-up, then apply the rest; `lnk/sub/..` is judged where the
193    // write would land. Kept root-relative so it compares with the lexical keys below.
194    if let Ok(croot) = root.canonicalize() {
195        let abs = root.join(p);
196        let comps: Vec<_> = abs.components().collect();
197        for k in (1..=comps.len()).rev() {
198            let Ok(mut out) = comps[..k].iter().collect::<std::path::PathBuf>().canonicalize() else {
199                continue;
200            };
201            for c in &comps[k..] {
202                match c {
203                    std::path::Component::ParentDir => {
204                        out.pop();
205                    }
206                    std::path::Component::Normal(n) => out.push(n),
207                    _ => {}
208                }
209            }
210            return match out.strip_prefix(&croot) {
211                Ok(r) => r.to_string_lossy().replace('\\', "/"),
212                Err(_) => out.to_string_lossy().into_owned(),
213            };
214        }
215    }
216    let p = Path::new(p);
217    let rel = p.strip_prefix(root).unwrap_or(p);
218    let mut parts: Vec<&str> = vec![];
219    for c in rel.to_str().unwrap_or_default().split(['/', '\\']) {
220        match c {
221            "" | "." => {}
222            ".." if parts.last().is_some_and(|l| *l != "..") => {
223                parts.pop();
224            }
225            other => parts.push(other),
226        }
227    }
228    parts.join("/")
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234
235    #[test]
236    fn parses_full_config() {
237        let raw: RawConfig = toml::from_str(
238            r#"
239[spec]
240schema = 1
241[owners]
242root = "ws"
243retired = ["services/old"]
244[[owners.kinds]]
245pattern = "services/*"
246id = "{1}"
247[public]
248paths = ["libs/open"]
249[public.companion]
250"libs/open" = "services/open"
251[external.notes]
252path = "~/notes"
253[files.store]
254kind = "dir"
255path = "/tmp/store"
256[types.adr]
257statuses = ["draft", "active"]
258[types.memo]
259key = "slug"
260[[guards]]
261name = "public"
262paths = ["libs/open/**"]
263deny_terms = ["internal-name"]
264"#,
265        )
266        .unwrap();
267        let cfg = Config::from_raw(PathBuf::from("/r"), raw, false);
268        assert_eq!(cfg.root_owner(), "ws");
269        assert!(cfg.registry.get("memo").is_some());
270        assert_eq!(cfg.registry.get("adr").unwrap().statuses.len(), 2);
271        assert_eq!(cfg.raw.guards[0].range, "staged");
272    }
273
274    #[test]
275    fn unknown_keys_are_refused() {
276        assert!(toml::from_str::<RawConfig>("[spec]\nschema = 1\ntypo = 2\n").is_err());
277    }
278}