specfold_core/config/
reader.rs1use 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 pub repo_root: PathBuf,
16 pub spec_home: PathBuf,
19 pub raw: RawConfig,
20 pub registry: Registry,
21 pub implicit: bool,
23 pub tracked: Option<std::sync::Arc<vcs::TrackedSet>>,
26}
27
28impl Config {
29 pub fn discover(start: &Path) -> Result<Self> {
32 let start = start.canonicalize().with_context(|| format!("cannot open {}", start.display()))?;
33 let mut dir = Some(start.as_path());
34 while let Some(d) = dir {
35 let candidate = d.join(CONFIG_FILE);
36 if candidate.is_file() {
37 return Self::load(&candidate);
38 }
39 dir = d.parent();
40 }
41 let root = vcs::git_root(&start).unwrap_or(start);
42 if let Some(private) = super::private_root::mapped(&root) {
44 let toml = private.join(CONFIG_FILE);
45 if toml.is_file() {
46 let repo_root = root.canonicalize().unwrap_or(root);
47 return Self::load(&toml).map(|c| Config { repo_root, ..c });
48 }
49 bail!(
50 "{} is mapped to {} in {}, which has no {CONFIG_FILE}; next: spec -C {} init --write",
51 root.display(),
52 private.display(),
53 super::private_root::file().unwrap_or_default().display(),
54 private.display()
55 );
56 }
57 Ok(Self::from_raw(root, RawConfig::default(), true))
58 }
59
60 pub fn load(path: &Path) -> Result<Self> {
61 let text = std::fs::read_to_string(path).with_context(|| format!("cannot read {}", path.display()))?;
62 let raw: RawConfig = match toml::from_str(&text) {
63 Ok(r) => r,
64 Err(e) => {
65 let (_, changes) = super::upgrade::plan(&text, super::upgrade::RENAMED);
66 let hint =
67 if changes.is_empty() { String::new() } else { "; renamed keys: spec init --upgrade".into() };
68 return Err(anyhow::Error::new(e).context(format!("invalid {}{hint}", path.display())));
69 }
70 };
71 super::validate::loaded(path, &text, &raw)?;
72 let root = path.parent().unwrap_or(Path::new(".")).to_path_buf();
73 Ok(Self::from_raw(root, raw, false))
74 }
75
76 pub fn from_raw(root: PathBuf, mut raw: RawConfig, implicit: bool) -> Self {
77 if raw.spec.submodule_remotes {
78 for (name, path) in crate::workspace::projects::submodule_remotes(&root) {
79 raw.remotes.entry(name).or_insert(crate::config::types::RemoteRoot { path, paths: vec![], auto: true });
80 }
81 }
82 for (name, path) in crate::workspace::projects::nested_remotes(&root, &raw.owners) {
84 raw.remotes.entry(name).or_insert(crate::config::types::RemoteRoot { path, paths: vec![], auto: true });
85 }
86 for (name, dir) in super::private_root::prefixes() {
87 let path = dir.to_string_lossy().into_owned();
88 raw.remotes.entry(name).or_insert(crate::config::types::RemoteRoot { path, paths: vec![], auto: false });
89 }
90 let registry = Registry::new(&raw.types);
91 Config { repo_root: root.clone(), spec_home: root, raw, registry, implicit, tracked: None }
92 }
93
94 pub fn tracked_only(mut self) -> Self {
96 self.tracked = vcs::TrackedSet::load(&self.spec_home).map(std::sync::Arc::new);
97 self
98 }
99
100 pub fn reads(&self, rel: &str, dir: bool) -> bool {
103 let Some(t) = &self.tracked else { return true };
104 let local = self.local_dir();
105 if rel.is_empty() || crate::paths::is_under(rel, local) {
106 return true;
107 }
108 if dir { t.has_dir(rel) || t.has_file(rel) } else { t.has_file(rel) }
109 }
110
111 pub fn spec_dir(&self) -> &str {
112 &self.raw.spec.dir
113 }
114
115 pub fn type_dirs(&self) -> Vec<(String, String)> {
118 let own =
119 |t: &crate::model::TypeDef| Some((super::type_dirs::normalize(t.dir.as_deref()?).ok()?, t.name.clone()));
120 self.registry.types.iter().filter_map(own).collect()
121 }
122
123 pub fn path_cite_re(&self) -> regex::Regex {
126 crate::model::markdown::body::path_cite_re_with(self.spec_dir(), &self.type_dirs())
127 }
128
129 pub fn cite_key(&self) -> String {
131 let mut key = self.spec_dir().to_string();
132 for (dir, ty) in self.type_dirs() {
133 key.push_str(&format!("\n{dir}={ty}"));
134 }
135 key
136 }
137
138 pub fn manifests(&self) -> Vec<String> {
139 match &self.raw.owners.manifests {
140 Some(m) => m.clone(),
141 None => defaults::MANIFESTS.iter().map(|s| s.to_string()).collect(),
142 }
143 }
144
145 pub fn root_owner(&self) -> &str {
146 &self.raw.owners.root
147 }
148
149 pub fn local_dir(&self) -> &str {
150 &self.raw.local.path
151 }
152
153 pub fn expand_path(&self, p: &str) -> PathBuf {
154 paths::expand(&self.spec_home, p)
155 }
156}
157
158#[cfg(test)]
159mod tests {
160 use super::*;
161
162 #[test]
163 fn parses_full_config() {
164 let raw: RawConfig = toml::from_str(
165 r#"
166[spec]
167schema = 1
168[owners]
169root = "ws"
170retired = ["services/old"]
171[[owners.kinds]]
172pattern = "services/*"
173id = "{1}"
174[public]
175paths = ["libs/open"]
176[public.companion]
177"libs/open" = "services/open"
178[external.notes]
179path = "~/notes"
180[files.store]
181kind = "dir"
182path = "/tmp/store"
183[types.adr]
184statuses = ["draft", "active"]
185[types.memo]
186key = "slug"
187[[guards]]
188name = "public"
189paths = ["libs/open/**"]
190deny_terms = ["internal-name"]
191"#,
192 )
193 .unwrap();
194 let cfg = Config::from_raw(PathBuf::from("/r"), raw, false);
195 assert_eq!(cfg.root_owner(), "ws");
196 assert!(cfg.registry.get("memo").is_some());
197 assert_eq!(cfg.registry.get("adr").unwrap().statuses.len(), 2);
198 assert_eq!(cfg.raw.guards[0].range, "staged");
199 }
200
201 #[test]
202 fn unknown_keys_are_refused() {
203 assert!(toml::from_str::<RawConfig>("[spec]\nschema = 1\ntypo = 2\n").is_err());
204 }
205}