use std::collections::BTreeMap;
use serde::Deserialize;
use crate::RepoRoot;
use crate::{Error, RepoPath, Result, Severity, source::read_optional};
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields, default)]
struct ConfigFile {
knowledge: KnowledgeSection,
repository: RepositorySection,
markers: MarkersSection,
harness: BTreeMap<String, HarnessSection>,
pack: Vec<super::packs::PackEntry>,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields, default)]
struct HarnessSection {
without: Vec<String>,
command: Option<String>,
}
impl ConfigFile {
fn declined(&self) -> BTreeMap<String, Vec<String>> {
self.harness
.iter()
.map(|(name, section)| (name.clone(), section.without.clone()))
.collect()
}
fn hook_commands(&self) -> BTreeMap<String, String> {
self.harness
.iter()
.filter_map(|(name, section)| section.command.clone().map(|c| (name.clone(), c)))
.collect()
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields, default)]
struct KnowledgeSection {
roots: Vec<String>,
}
impl Default for KnowledgeSection {
fn default() -> Self {
KnowledgeSection {
roots: vec!["/knowledge".into()],
}
}
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields, default)]
struct RepositorySection {
exclude: Vec<String>,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields, default)]
struct MarkersSection {
check: MarkerCheck,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MarkerCheck {
#[default]
Error,
Warn,
Off,
}
impl MarkerCheck {
pub fn severity(self) -> Severity {
match self {
MarkerCheck::Warn => Severity::Warning,
_ => Severity::Error,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Config {
pub roots: Vec<RepoPath>,
pub exclude: Vec<String>,
pub declined: BTreeMap<String, Vec<String>>,
pub markers: MarkerCheck,
}
impl Default for Config {
fn default() -> Self {
Config {
roots: vec![RepoPath::parse("/knowledge").expect("literal")],
exclude: Vec::new(),
declined: BTreeMap::new(),
markers: MarkerCheck::default(),
}
}
}
pub fn config_path() -> RepoPath {
RepoPath::parse("/.sokf/config.toml").expect("literal")
}
pub fn load_config(root: &RepoRoot) -> Result<Config> {
let path = config_path();
let fs_path = path.to_fs(root);
let text = read_optional(&fs_path)?.unwrap_or_default();
let file: ConfigFile =
toml::from_str(&text).map_err(|e| Error::config(path.clone(), e.message().to_string()))?;
let mut roots = Vec::new();
for r in &file.knowledge.roots {
let Some(rp) = RepoPath::parse(r) else {
return Err(Error::config(
path,
format!("knowledge.roots entry `{r}` is not a /-rooted path"),
));
};
if !rp.to_fs(root).is_dir() {
return Err(Error::config(
path,
format!("knowledge root `{r}` is not a directory"),
));
}
roots.push(rp);
}
for g in &file.repository.exclude {
if !g.starts_with('/') {
return Err(Error::config(
path,
format!("repository.exclude glob `{g}` is not /-rooted"),
));
}
if let Err(e) = globset::Glob::new(g) {
return Err(Error::config(
path,
format!("repository.exclude glob `{g}` does not parse: {e}"),
));
}
}
Ok(Config {
roots,
declined: file.declined(),
exclude: file.repository.exclude,
markers: file.markers.check,
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigText {
pub roots: Vec<RepoPath>,
pub declined: BTreeMap<String, Vec<String>>,
pub hook_commands: BTreeMap<String, String>,
pub text: Option<String>,
}
pub fn read_lenient(root: &RepoRoot) -> Result<ConfigText> {
let path = config_path();
let fs_path = path.to_fs(root);
let Some(text) = read_optional(&fs_path)? else {
return Ok(ConfigText {
roots: Config::default().roots,
declined: BTreeMap::new(),
hook_commands: BTreeMap::new(),
text: None,
});
};
let file: ConfigFile =
toml::from_str(&text).map_err(|e| Error::Init(format!("{path}: {}", e.message())))?;
let mut roots = Vec::new();
for r in &file.knowledge.roots {
let rp = RepoPath::parse(r).ok_or_else(|| {
Error::Init(format!(
"{path}: knowledge.roots entry `{r}` is not a /-rooted path"
))
})?;
roots.push(rp);
}
Ok(ConfigText {
roots,
declined: file.declined(),
hook_commands: file.hook_commands(),
text: Some(text),
})
}
#[cfg(test)]
mod tests {
use std::{
fs,
path::{Path, PathBuf},
};
use super::*;
#[test]
fn reads_leniently_for_init() {
let dir = temp("lenient");
let root = RepoRoot::new(dir.clone());
assert_eq!(
read_lenient(&root).unwrap(),
ConfigText {
roots: Config::default().roots,
declined: BTreeMap::new(),
hook_commands: BTreeMap::new(),
text: None
}
);
let text = "# c\n[knowledge]\nroots = [\"/missing\", \"/docs\"]\n[harness.claude]\nwithout = [\"hooks\"]\n";
fs::write(dir.join(".sokf/config.toml"), text).unwrap();
assert_eq!(
read_lenient(&root).unwrap(),
ConfigText {
roots: vec![
RepoPath::parse("/missing").unwrap(),
RepoPath::parse("/docs").unwrap()
],
declined: BTreeMap::from([("claude".to_string(), vec!["hooks".to_string()])]),
hook_commands: BTreeMap::new(),
text: Some(text.into())
}
);
for bad in [
"not toml [",
"[knowledge]\nroots = [\"docs\"]\n",
"[nope]\n",
] {
fs::write(dir.join(".sokf/config.toml"), bad).unwrap();
let e = read_lenient(&root).unwrap_err();
assert!(matches!(e, Error::Init(_)), "{bad:?} -> {e}");
assert!(
e.to_string().starts_with("init: /.sokf/config.toml: "),
"{e}"
);
}
fs::remove_dir_all(&dir).unwrap();
}
fn temp(name: &str) -> PathBuf {
let dir = crate::test_support::fresh_dir(&format!("config-{name}"));
fs::create_dir_all(dir.join(".sokf")).unwrap();
fs::create_dir_all(dir.join("knowledge")).unwrap();
fs::create_dir_all(dir.join("docs")).unwrap();
dir
}
fn with(dir: &Path, text: &str) -> Result<Config> {
fs::write(dir.join(".sokf/config.toml"), text).unwrap();
load_config(&RepoRoot::new(dir.to_path_buf()))
}
#[test]
fn absent_file_gives_defaults() {
let dir = temp("absent");
assert_eq!(
load_config(&RepoRoot::new(dir.clone())).unwrap(),
Config::default()
);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn an_absent_file_reads_as_a_file_with_no_tables() {
let dir = temp("no-tables");
fs::remove_file(dir.join(".sokf/config.toml")).ok();
let absent = load_config(&RepoRoot::new(dir.clone())).unwrap();
assert_eq!(absent.roots, vec![RepoPath::parse("/knowledge").unwrap()]);
for text in ["", "# A comment only.\n"] {
assert_eq!(with(&dir, text).unwrap(), absent, "{text:?}");
}
fs::remove_dir_all(dir.join("knowledge")).unwrap();
let empty = with(&dir, "").unwrap_err().to_string();
fs::remove_file(dir.join(".sokf/config.toml")).unwrap();
let absent = load_config(&RepoRoot::new(dir.clone()))
.unwrap_err()
.to_string();
assert_eq!(absent, empty);
assert!(absent.contains("is not a directory"), "{absent}");
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn reads_roots_and_excludes() {
let dir = temp("ok");
let c = with(
&dir,
"[knowledge]\nroots = [\"/knowledge\", \"/docs\"]\n[repository]\nexclude = [\"/vendor/**\"]\n",
)
.unwrap();
assert_eq!(c.roots.len(), 2);
assert_eq!(c.exclude, vec!["/vendor/**"]);
let c = with(&dir, "[repository]\nexclude = []\n").unwrap();
assert_eq!(c.roots, Config::default().roots);
let c = with(&dir, "[knowledge]\nroots = [\"\\x2Fdocs\"]\n").unwrap();
assert_eq!(c.roots, vec![RepoPath::parse("/docs").unwrap()]);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn reads_the_markers_table() {
let dir = temp("markers");
assert_eq!(with(&dir, "").unwrap().markers, MarkerCheck::Error);
for (text, check) in [
("[markers]\ncheck = \"error\"\n", MarkerCheck::Error),
("[markers]\ncheck = \"warn\"\n", MarkerCheck::Warn),
("[markers]\ncheck = \"off\"\n", MarkerCheck::Off),
("[markers]\n", MarkerCheck::Error),
] {
assert_eq!(with(&dir, text).unwrap().markers, check, "{text:?}");
}
for bad in [
"[markers]\ncheck = \"loud\"\n",
"[markers]\nchecks = \"off\"\n",
] {
let e = with(&dir, bad).unwrap_err();
assert!(matches!(e, Error::Config { .. }), "{bad:?} -> {e}");
}
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn reads_the_harness_table() {
let dir = temp("harness");
let c = with(
&dir,
"[harness.claude]\nwithout = [\"hooks\", \"skills\"]\n",
)
.unwrap();
assert_eq!(
c.declined,
BTreeMap::from([(
"claude".to_string(),
vec!["hooks".to_string(), "skills".to_string()]
)])
);
let c = with(&dir, "[harness.claude]\n[harness.other]\nwithout = []\n").unwrap();
assert_eq!(c.declined["claude"], Vec::<String>::new());
assert_eq!(c.declined["other"], Vec::<String>::new());
let e = with(&dir, "[harness.claude]\nwith = []\n").unwrap_err();
assert!(matches!(e, Error::Config { .. }), "{e}");
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn refuses_bad_files() {
let dir = temp("bad");
for text in [
"not toml [",
"[knowledge]\nrootz = []\n",
"[other]\nx = 1\n",
"[knowledge]\nroots = [\"knowledge\"]\n",
"[knowledge]\nroots = [\"/missing\"]\n",
"[repository]\nexclude = [\"vendor/**\"]\n",
"[repository]\nexclude = [\"/[\"]\n",
] {
let e = with(&dir, text).unwrap_err();
assert!(matches!(e, Error::Config { .. }), "{text:?} -> {e}");
assert!(e.to_string().starts_with("/.sokf/config.toml: "), "{e}");
}
fs::remove_dir_all(&dir).unwrap();
}
}