1use std::collections::BTreeMap;
5
6use serde::Deserialize;
7
8use super::{
9 excludes_d::AddedExclude,
10 format::{FormatConfig, FormatSection},
11};
12use crate::{Error, RepoPath, RepoRoot, Result, Severity, source::read_optional};
13
14#[derive(Debug, Clone, Default, Deserialize)]
21#[serde(deny_unknown_fields, default)]
22struct ConfigFile {
23 knowledge: KnowledgeSection,
24 repository: RepositorySection,
25 markers: MarkersSection,
26 harness: BTreeMap<String, HarnessSection>,
27 format: FormatSection,
28}
29const PACKS_GONE: &str = "`[[pack]]` declares a pack, and packs are no longer part of sokf: \
34 remove each `[[pack]]` entry";
35
36#[derive(Debug, Clone, Default, Deserialize)]
42#[serde(deny_unknown_fields, default)]
43struct HarnessSection {
44 without: Vec<String>,
45 with: Vec<String>,
46 command: Option<String>,
47}
48fn parse(text: &str) -> std::result::Result<ConfigFile, String> {
56 let table: toml::Table = toml::from_str(text).map_err(|e| e.message().to_string())?;
57 if table.contains_key("pack") {
58 return Err(PACKS_GONE.to_string());
59 }
60 toml::from_str(text).map_err(|e| e.message().to_string())
61}
62
63impl ConfigFile {
64 fn declined(&self) -> BTreeMap<String, Vec<String>> {
65 self.harness
66 .iter()
67 .map(|(name, section)| (name.clone(), section.without.clone()))
68 .collect()
69 }
70
71 fn bad_with(&self) -> Option<String> {
74 self.harness
75 .iter()
76 .find_map(|(name, section)| crate::harness::bad_with(name, §ion.with))
77 }
78
79 fn hook_commands(&self) -> BTreeMap<String, String> {
82 self.harness
83 .iter()
84 .filter_map(|(name, section)| section.command.clone().map(|c| (name.clone(), c)))
85 .collect()
86 }
87}
88
89#[derive(Debug, Clone, Deserialize)]
94#[serde(deny_unknown_fields, default)]
95struct KnowledgeSection {
96 roots: Vec<String>,
97}
98
99impl Default for KnowledgeSection {
100 fn default() -> Self {
101 KnowledgeSection {
102 roots: vec!["/knowledge".into()],
103 }
104 }
105}
106#[derive(Debug, Clone, Default, Deserialize)]
114#[serde(deny_unknown_fields, default)]
115struct RepositorySection {
116 exclude: Vec<String>,
117}
118#[derive(Debug, Clone, Default, Deserialize)]
124#[serde(deny_unknown_fields, default)]
125struct MarkersSection {
126 check: MarkerCheck,
127}
128
129#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
132#[serde(rename_all = "lowercase")]
133pub enum MarkerCheck {
134 #[default]
136 Error,
137 Warn,
139 Off,
141}
142impl MarkerCheck {
145 pub fn severity(self) -> Severity {
148 match self {
149 MarkerCheck::Warn => Severity::Warning,
150 _ => Severity::Error,
151 }
152 }
153}
154
155#[derive(Debug, Clone, PartialEq, Eq)]
157pub struct Config {
158 pub roots: Vec<RepoPath>,
161 pub registered_count: usize,
165 pub exclude: Vec<String>,
168 pub added_exclude: Vec<AddedExclude>,
171 pub declined: BTreeMap<String, Vec<String>>,
173 pub markers: MarkerCheck,
175 pub format: FormatConfig,
179}
180
181impl Default for Config {
182 fn default() -> Self {
183 Config {
184 roots: vec![RepoPath::parse("/knowledge").expect("literal")],
185 registered_count: 0,
186 exclude: Vec::new(),
187 added_exclude: Vec::new(),
188 declined: BTreeMap::new(),
189 markers: MarkerCheck::default(),
190 format: FormatConfig::default(),
191 }
192 }
193}
194
195impl Config {
196 pub fn excludes(&self) -> impl Iterator<Item = &str> {
199 self.exclude
200 .iter()
201 .map(String::as_str)
202 .chain(self.added_exclude.iter().map(|e| e.glob.as_str()))
203 }
204}
205
206pub(super) fn glob_fault(key: &str, g: &str) -> Option<String> {
212 if !g.starts_with('/') {
213 return Some(format!("{key} glob `{g}` is not /-rooted"));
214 }
215 crate::walk::repo_glob(g)
216 .err()
217 .map(|e| format!("{key} glob `{g}` does not parse: {e}"))
218}
219
220pub fn config_path() -> RepoPath {
222 RepoPath::parse("/.sokf/config.toml").expect("literal")
223}
224
225pub fn load_config(root: &RepoRoot) -> Result<Config> {
233 let path = config_path();
234 let fs_path = path.to_fs(root);
235 let text = read_optional(&fs_path)?.unwrap_or_default();
239 let file = parse(&text).map_err(|m| Error::config(path.clone(), m))?;
242 if let Some(m) = file.bad_with() {
243 return Err(Error::config(path, m));
244 }
245 let mut roots = Vec::new();
246 for r in &file.knowledge.roots {
247 let Some(rp) = RepoPath::parse(r) else {
249 return Err(Error::config(
250 path,
251 format!("knowledge.roots entry `{r}` is not a /-rooted path"),
252 ));
253 };
254 if !rp.to_fs(root).is_dir() {
256 return Err(Error::config(
257 path,
258 format!("knowledge root `{r}` is not a directory"),
259 ));
260 }
261 roots.push(rp);
262 }
263 let registered = super::roots_d::read_registered(root, &|p, m| Error::config(p, m))?;
265 for r in ®istered {
266 if !r.root.to_fs(root).is_dir() {
268 return Err(Error::config(
269 r.file.clone(),
270 format!("knowledge root `{}` is not a directory", r.root),
271 ));
272 }
273 }
274 super::roots_d::check_apart(&roots, ®istered)?;
275 let registered_count = registered.len();
276 roots.extend(registered.into_iter().map(|r| r.root));
277 for g in &file.repository.exclude {
278 if let Some(m) = glob_fault("repository.exclude", g) {
279 return Err(Error::config(path, m));
280 }
281 }
282 let added_exclude = super::excludes_d::read_added(root)?;
283 let declined = file.declined();
284 let format = file
285 .format
286 .resolve()
287 .and_then(|format| format.check_files(root))
288 .map_err(|m| Error::config(path.clone(), m))?;
289 Ok(Config {
290 roots,
291 registered_count,
292 declined,
293 exclude: file.repository.exclude,
294 added_exclude,
295 markers: file.markers.check,
296 format,
297 })
298}
299
300#[derive(Debug, Clone, PartialEq, Eq)]
304pub struct ConfigText {
305 pub roots: Vec<RepoPath>,
307 pub registered: Vec<RepoPath>,
310 pub declined: BTreeMap<String, Vec<String>>,
312 pub hook_commands: BTreeMap<String, String>,
314 pub text: Option<String>,
316}
317
318pub fn read_lenient(root: &RepoRoot) -> Result<ConfigText> {
330 let path = config_path();
331 let fs_path = path.to_fs(root);
332 let registered = super::roots_d::registered_lenient(root);
335 let Some(text) = read_optional(&fs_path)? else {
336 return Ok(ConfigText {
337 roots: Config::default().roots,
338 registered,
339 declined: BTreeMap::new(),
340 hook_commands: BTreeMap::new(),
341 text: None,
342 });
343 };
344 let file = parse(&text).map_err(|m| Error::Init(format!("{path}: {m}")))?;
345 if let Some(m) = file.bad_with() {
346 return Err(Error::Init(format!("{path}: {m}")));
347 }
348 let mut roots = Vec::new();
349 for r in &file.knowledge.roots {
350 let rp = RepoPath::parse(r).ok_or_else(|| {
351 Error::Init(format!(
352 "{path}: knowledge.roots entry `{r}` is not a /-rooted path"
353 ))
354 })?;
355 roots.push(rp);
356 }
357 Ok(ConfigText {
358 roots,
359 registered,
360 declined: file.declined(),
361 hook_commands: file.hook_commands(),
362 text: Some(text),
363 })
364}
365
366#[cfg(test)]
367mod tests {
368 use std::{
369 fs,
370 path::{Path, PathBuf},
371 };
372
373 use super::*;
374
375 #[test]
381 fn reads_leniently_for_init() {
382 let dir = temp("lenient");
383 let root = RepoRoot::new(dir.clone());
384 assert_eq!(
385 read_lenient(&root).unwrap(),
386 ConfigText {
387 roots: Config::default().roots,
388 registered: vec![],
389 declined: BTreeMap::new(),
390 hook_commands: BTreeMap::new(),
391 text: None
392 }
393 );
394 let text = "# c\n[knowledge]\nroots = [\"/missing\", \"/docs\"]\n[harness.claude]\nwithout = [\"hooks\"]\n";
397 fs::write(dir.join(".sokf/config.toml"), text).unwrap();
398 assert_eq!(
399 read_lenient(&root).unwrap(),
400 ConfigText {
401 roots: vec![
402 RepoPath::parse("/missing").unwrap(),
403 RepoPath::parse("/docs").unwrap()
404 ],
405 registered: vec![],
406 declined: BTreeMap::from([("claude".to_string(), vec!["hooks".to_string()])]),
407 hook_commands: BTreeMap::new(),
408 text: Some(text.into())
409 }
410 );
411 for bad in [
412 "not toml [",
413 "[knowledge]\nroots = [\"docs\"]\n",
414 "[nope]\n",
415 ] {
416 fs::write(dir.join(".sokf/config.toml"), bad).unwrap();
417 let e = read_lenient(&root).unwrap_err();
418 assert!(matches!(e, Error::Init(_)), "{bad:?} -> {e}");
419 assert!(
420 e.to_string().starts_with("init: /.sokf/config.toml: "),
421 "{e}"
422 );
423 }
424 fs::remove_dir_all(&dir).unwrap();
425 }
426
427 fn temp(name: &str) -> PathBuf {
428 let dir = crate::test_support::fresh_dir(&format!("config-{name}"));
429 fs::create_dir_all(dir.join(".sokf")).unwrap();
430 fs::create_dir_all(dir.join("knowledge")).unwrap();
431 fs::create_dir_all(dir.join("docs")).unwrap();
432 dir
433 }
434
435 fn with(dir: &Path, text: &str) -> Result<Config> {
436 fs::write(dir.join(".sokf/config.toml"), text).unwrap();
437 load_config(&RepoRoot::new(dir.to_path_buf()))
438 }
439
440 #[test]
441 fn absent_file_gives_defaults() {
442 let dir = temp("absent");
443 assert_eq!(
444 load_config(&RepoRoot::new(dir.clone())).unwrap(),
445 Config::default()
446 );
447 fs::remove_dir_all(&dir).unwrap();
448 }
449
450 #[test]
453 fn an_absent_file_reads_as_a_file_with_no_tables() {
454 let dir = temp("no-tables");
455 fs::remove_file(dir.join(".sokf/config.toml")).ok();
456 let absent = load_config(&RepoRoot::new(dir.clone())).unwrap();
457 assert_eq!(absent.roots, vec![RepoPath::parse("/knowledge").unwrap()]);
458 for text in ["", "# A comment only.\n"] {
459 assert_eq!(with(&dir, text).unwrap(), absent, "{text:?}");
460 }
461 fs::remove_dir_all(dir.join("knowledge")).unwrap();
464 let empty = with(&dir, "").unwrap_err().to_string();
465 fs::remove_file(dir.join(".sokf/config.toml")).unwrap();
466 let absent = load_config(&RepoRoot::new(dir.clone()))
467 .unwrap_err()
468 .to_string();
469 assert_eq!(absent, empty);
470 assert!(absent.contains("is not a directory"), "{absent}");
471 fs::remove_dir_all(&dir).unwrap();
472 }
473
474 #[test]
477 fn reads_roots_and_excludes() {
478 let dir = temp("ok");
479 let c = with(
480 &dir,
481 "[knowledge]\nroots = [\"/knowledge\", \"/docs\"]\n[repository]\nexclude = [\"/vendor/**\"]\n",
482 )
483 .unwrap();
484 assert_eq!(c.roots.len(), 2);
485 assert_eq!(c.exclude, vec!["/vendor/**"]);
486 let c = with(&dir, "[repository]\nexclude = []\n").unwrap();
487 assert_eq!(c.roots, Config::default().roots);
488 let c = with(&dir, "[knowledge]\nroots = [\"\\x2Fdocs\"]\n").unwrap();
490 assert_eq!(c.roots, vec![RepoPath::parse("/docs").unwrap()]);
491 fs::remove_dir_all(&dir).unwrap();
492 }
493
494 #[test]
497 fn reads_the_markers_table() {
498 let dir = temp("markers");
499 assert_eq!(with(&dir, "").unwrap().markers, MarkerCheck::Error);
500 for (text, check) in [
501 ("[markers]\ncheck = \"error\"\n", MarkerCheck::Error),
502 ("[markers]\ncheck = \"warn\"\n", MarkerCheck::Warn),
503 ("[markers]\ncheck = \"off\"\n", MarkerCheck::Off),
504 ("[markers]\n", MarkerCheck::Error),
505 ] {
506 assert_eq!(with(&dir, text).unwrap().markers, check, "{text:?}");
507 }
508 for bad in [
509 "[markers]\ncheck = \"loud\"\n",
510 "[markers]\nchecks = \"off\"\n",
511 ] {
512 let e = with(&dir, bad).unwrap_err();
513 assert!(matches!(e, Error::Config { .. }), "{bad:?} -> {e}");
514 }
515 fs::remove_dir_all(&dir).unwrap();
516 }
517
518 #[test]
520 fn reads_the_harness_table() {
521 let dir = temp("harness");
522 let c = with(
523 &dir,
524 "[harness.claude]\nwithout = [\"hooks\", \"skills\"]\n",
525 )
526 .unwrap();
527 assert_eq!(
528 c.declined,
529 BTreeMap::from([(
530 "claude".to_string(),
531 vec!["hooks".to_string(), "skills".to_string()]
532 )])
533 );
534 let c = with(&dir, "[harness.claude]\n[harness.other]\nwithout = []\n").unwrap();
537 assert_eq!(c.declined["claude"], Vec::<String>::new());
538 assert_eq!(c.declined["other"], Vec::<String>::new());
539 for text in [
541 "[harness.claude]\nwith = []\n",
542 "[harness.claude]\nwith = [\"hooks\"]\n",
543 ] {
544 assert!(with(&dir, text).is_ok(), "{text:?}");
545 }
546 let e = with(&dir, "[harness.claude]\nwith = [\"skills\"]\n").unwrap_err();
549 assert!(matches!(e, Error::Config { .. }), "{e}");
550 assert!(e.to_string().contains("harness.claude.with"), "{e}");
551 let e = with(&dir, "[harness.claude]\nwithin = []\n").unwrap_err();
554 assert!(matches!(e, Error::Config { .. }), "{e}");
555 fs::remove_dir_all(&dir).unwrap();
556 }
557
558 #[test]
565 fn refuses_bad_files() {
566 let dir = temp("bad");
567 for text in [
568 "not toml [",
569 "[knowledge]\nrootz = []\n",
570 "[other]\nx = 1\n",
571 "[knowledge]\nroots = [\"knowledge\"]\n",
572 "[knowledge]\nroots = [\"/missing\"]\n",
573 "[repository]\nexclude = [\"vendor/**\"]\n",
574 "[repository]\nexclude = [\"/[\"]\n",
575 ] {
576 let e = with(&dir, text).unwrap_err();
577 assert!(matches!(e, Error::Config { .. }), "{text:?} -> {e}");
578 assert!(e.to_string().starts_with("/.sokf/config.toml: "), "{e}");
579 }
580 fs::remove_dir_all(&dir).unwrap();
581 }
582
583 #[test]
588 fn refuses_the_entries_of_the_packs() {
589 let dir = temp("packs");
590 let root = RepoRoot::new(dir.clone());
591 for text in [
592 "[[pack]]\nname = \"@acme/tool\"\nsource = \"./\"\n",
593 "[knowledge]\nroots = [\"/knowledge\"]\n\n[[pack]]\nname = \"rust\"\n",
594 "pack = []\n",
595 ] {
596 let e = with(&dir, text).unwrap_err();
597 assert!(matches!(e, Error::Config { .. }), "{text:?} -> {e}");
598 assert!(
599 e.to_string().contains("packs are no longer part of sokf"),
600 "{e}"
601 );
602 let e = read_lenient(&root).unwrap_err();
603 assert!(matches!(e, Error::Init(_)), "{text:?} -> {e}");
604 assert!(
605 e.to_string().contains("packs are no longer part of sokf"),
606 "{e}"
607 );
608 }
609 let e = with(&dir, "foo = 1\n").unwrap_err().to_string();
611 assert!(e.contains("unknown field `foo`"), "{e}");
612 assert!(!e.contains("pack"), "{e}");
613 fs::remove_dir_all(&dir).unwrap();
614 }
615}