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    /// F1: the repository the configuration was found from: the spec home, or under roots.toml
14    /// the public repository mapped to it. Code paths typed there are named from it.
15    pub repo_root: PathBuf,
16    /// The spec home: the directory holding spec.toml, its owners and documents. Every
17    /// repository-relative path in the configuration and the corpus is relative to it.
18    pub spec_home: PathBuf,
19    pub raw: RawConfig,
20    pub registry: Registry,
21    /// True when no spec.toml was found and defaults are in use.
22    pub implicit: bool,
23}
24
25impl Config {
26    /// Finds spec.toml in `start` or its ancestors. Without one, the nearest git root (or `start`)
27    /// is used with defaults, so the tool works in any directory.
28    pub fn discover(start: &Path) -> Result<Self> {
29        let start = start.canonicalize().with_context(|| format!("cannot open {}", start.display()))?;
30        let mut dir = Some(start.as_path());
31        while let Some(d) = dir {
32            let candidate = d.join(CONFIG_FILE);
33            if candidate.is_file() {
34                return Self::load(&candidate);
35            }
36            dir = d.parent();
37        }
38        let root = vcs::git_root(&start).unwrap_or(start);
39        // F1: a public repository whose documents live in a mapped private directory.
40        if let Some(private) = super::private_root::mapped(&root) {
41            let toml = private.join(CONFIG_FILE);
42            if toml.is_file() {
43                let repo_root = root.canonicalize().unwrap_or(root);
44                return Self::load(&toml).map(|c| Config { repo_root, ..c });
45            }
46            bail!(
47                "{} is mapped to {} in {}, which has no {CONFIG_FILE}; next: spec -C {} init --write",
48                root.display(),
49                private.display(),
50                super::private_root::file().unwrap_or_default().display(),
51                private.display()
52            );
53        }
54        Ok(Self::from_raw(root, RawConfig::default(), true))
55    }
56
57    pub fn load(path: &Path) -> Result<Self> {
58        let text = std::fs::read_to_string(path).with_context(|| format!("cannot read {}", path.display()))?;
59        let raw: RawConfig = match toml::from_str(&text) {
60            Ok(r) => r,
61            Err(e) => {
62                let (_, changes) = super::upgrade::plan(&text, super::upgrade::RENAMED);
63                let hint =
64                    if changes.is_empty() { String::new() } else { "; renamed keys: spec init --upgrade".into() };
65                return Err(anyhow::Error::new(e).context(format!("invalid {}{hint}", path.display())));
66            }
67        };
68        super::validate::loaded(path, &text, &raw)?;
69        let root = path.parent().unwrap_or(Path::new(".")).to_path_buf();
70        Ok(Self::from_raw(root, raw, false))
71    }
72
73    pub fn from_raw(root: PathBuf, mut raw: RawConfig, implicit: bool) -> Self {
74        if raw.spec.submodule_remotes {
75            for (name, path) in crate::workspace::projects::submodule_remotes(&root) {
76                raw.remotes.entry(name).or_insert(crate::config::types::RemoteRoot { path, paths: vec![], auto: true });
77            }
78        }
79        // C1: a nested project is a remote whether or not submodule_remotes is set.
80        for (name, path) in crate::workspace::projects::nested_remotes(&root, &raw.owners) {
81            raw.remotes.entry(name).or_insert(crate::config::types::RemoteRoot { path, paths: vec![], auto: true });
82        }
83        for (name, dir) in super::private_root::prefixes() {
84            let path = dir.to_string_lossy().into_owned();
85            raw.remotes.entry(name).or_insert(crate::config::types::RemoteRoot { path, paths: vec![], auto: false });
86        }
87        let registry = Registry::new(&raw.types);
88        Config { repo_root: root.clone(), spec_home: root, raw, registry, implicit }
89    }
90
91    pub fn spec_dir(&self) -> &str {
92        &self.raw.spec.dir
93    }
94
95    /// `(directory, type)` for each type kept in a directory of its own (`[types.<name>] dir`),
96    /// the directory relative to an owner's root.
97    pub fn type_dirs(&self) -> Vec<(String, String)> {
98        let own =
99            |t: &crate::model::TypeDef| Some((super::type_dirs::normalize(t.dir.as_deref()?).ok()?, t.name.clone()));
100        self.registry.types.iter().filter_map(own).collect()
101    }
102
103    /// The regex that finds plain-text paths to documents: into the spec directory, or to a
104    /// document file in a type's own directory.
105    pub fn path_cite_re(&self) -> regex::Regex {
106        crate::model::markdown::body::path_cite_re_with(self.spec_dir(), &self.type_dirs())
107    }
108
109    /// What a scan's path citations depend on, so a cache of scans is dropped when it changes.
110    pub fn cite_key(&self) -> String {
111        let mut key = self.spec_dir().to_string();
112        for (dir, ty) in self.type_dirs() {
113            key.push_str(&format!("\n{dir}={ty}"));
114        }
115        key
116    }
117
118    pub fn manifests(&self) -> Vec<String> {
119        match &self.raw.owners.manifests {
120            Some(m) => m.clone(),
121            None => defaults::MANIFESTS.iter().map(|s| s.to_string()).collect(),
122        }
123    }
124
125    pub fn root_owner(&self) -> &str {
126        &self.raw.owners.root
127    }
128
129    pub fn local_dir(&self) -> &str {
130        &self.raw.local.path
131    }
132
133    pub fn expand_path(&self, p: &str) -> PathBuf {
134        paths::expand(&self.spec_home, p)
135    }
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141
142    #[test]
143    fn parses_full_config() {
144        let raw: RawConfig = toml::from_str(
145            r#"
146[spec]
147schema = 1
148[owners]
149root = "ws"
150retired = ["services/old"]
151[[owners.kinds]]
152pattern = "services/*"
153id = "{1}"
154[public]
155paths = ["libs/open"]
156[public.companion]
157"libs/open" = "services/open"
158[external.notes]
159path = "~/notes"
160[files.store]
161kind = "dir"
162path = "/tmp/store"
163[types.adr]
164statuses = ["draft", "active"]
165[types.memo]
166key = "slug"
167[[guards]]
168name = "public"
169paths = ["libs/open/**"]
170deny_terms = ["internal-name"]
171"#,
172        )
173        .unwrap();
174        let cfg = Config::from_raw(PathBuf::from("/r"), raw, false);
175        assert_eq!(cfg.root_owner(), "ws");
176        assert!(cfg.registry.get("memo").is_some());
177        assert_eq!(cfg.registry.get("adr").unwrap().statuses.len(), 2);
178        assert_eq!(cfg.raw.guards[0].range, "staged");
179    }
180
181    #[test]
182    fn unknown_keys_are_refused() {
183        assert!(toml::from_str::<RawConfig>("[spec]\nschema = 1\ntypo = 2\n").is_err());
184    }
185}