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}
24
25impl Config {
26 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 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 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 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 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 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}