use std::collections::BTreeMap;
use serde::Deserialize;
use super::excludes_d::AddedExclude;
use crate::{Error, RepoPath, RepoRoot, 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>,
format: FormatSection,
}
const PACKS_GONE: &str = "`[[pack]]` declares a pack, and packs are no longer part of sokf: \
remove each `[[pack]]` entry";
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields, default)]
struct FormatSection {
command: Option<Vec<String>>,
settings: Option<toml::Table>,
timeout: Option<i64>,
}
pub const FORMAT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FormatConfig {
pub command: Option<Vec<String>>,
pub settings: Option<String>,
pub timeout: std::time::Duration,
}
impl Default for FormatConfig {
fn default() -> FormatConfig {
FormatConfig {
command: None,
settings: None,
timeout: FORMAT_TIMEOUT,
}
}
}
impl FormatSection {
fn resolve(self) -> std::result::Result<FormatConfig, String> {
if let Some(command) = &self.command
&& (command.is_empty() || !command.iter().any(|a| a == "{files}"))
{
return Err("format.command must name a program and have an element `{files}`".into());
}
let settings = self
.settings
.map(|t| serde_json::to_string(&t).map_err(|e| format!("format.settings: {e}")))
.transpose()?;
let timeout = match self.timeout {
None => FORMAT_TIMEOUT,
Some(secs) => u64::try_from(secs)
.ok()
.filter(|s| *s > 0)
.map(std::time::Duration::from_secs)
.ok_or("format.timeout must be a whole number of seconds above 0")?,
};
Ok(FormatConfig {
command: self.command,
settings,
timeout,
})
}
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields, default)]
struct HarnessSection {
without: Vec<String>,
with: Vec<String>,
command: Option<String>,
}
fn parse(text: &str) -> std::result::Result<ConfigFile, String> {
let table: toml::Table = toml::from_str(text).map_err(|e| e.message().to_string())?;
if table.contains_key("pack") {
return Err(PACKS_GONE.to_string());
}
toml::from_str(text).map_err(|e| e.message().to_string())
}
impl ConfigFile {
fn declined(&self) -> BTreeMap<String, Vec<String>> {
self.harness
.iter()
.map(|(name, section)| (name.clone(), section.without.clone()))
.collect()
}
fn bad_with(&self) -> Option<String> {
self.harness
.iter()
.find_map(|(name, section)| crate::harness::bad_with(name, §ion.with))
}
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 registered_count: usize,
pub exclude: Vec<String>,
pub added_exclude: Vec<AddedExclude>,
pub declined: BTreeMap<String, Vec<String>>,
pub markers: MarkerCheck,
pub format: FormatConfig,
}
impl Default for Config {
fn default() -> Self {
Config {
roots: vec![RepoPath::parse("/knowledge").expect("literal")],
registered_count: 0,
exclude: Vec::new(),
added_exclude: Vec::new(),
declined: BTreeMap::new(),
markers: MarkerCheck::default(),
format: FormatConfig::default(),
}
}
}
impl Config {
pub fn excludes(&self) -> impl Iterator<Item = &str> {
self.exclude
.iter()
.map(String::as_str)
.chain(self.added_exclude.iter().map(|e| e.glob.as_str()))
}
}
pub(super) fn glob_fault(key: &str, g: &str) -> Option<String> {
if !g.starts_with('/') {
return Some(format!("{key} glob `{g}` is not /-rooted"));
}
crate::walk::repo_glob(g)
.err()
.map(|e| format!("{key} glob `{g}` does not parse: {e}"))
}
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 = parse(&text).map_err(|m| Error::config(path.clone(), m))?;
if let Some(m) = file.bad_with() {
return Err(Error::config(path, m));
}
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);
}
let registered = super::roots_d::read_registered(root, &|p, m| Error::config(p, m))?;
for r in ®istered {
if !r.root.to_fs(root).is_dir() {
return Err(Error::config(
r.file.clone(),
format!("knowledge root `{}` is not a directory", r.root),
));
}
}
super::roots_d::check_apart(&roots, ®istered)?;
let registered_count = registered.len();
roots.extend(registered.into_iter().map(|r| r.root));
for g in &file.repository.exclude {
if let Some(m) = glob_fault("repository.exclude", g) {
return Err(Error::config(path, m));
}
}
let added_exclude = super::excludes_d::read_added(root)?;
let declined = file.declined();
let format = file
.format
.resolve()
.map_err(|m| Error::config(path.clone(), m))?;
Ok(Config {
roots,
registered_count,
declined,
exclude: file.repository.exclude,
added_exclude,
markers: file.markers.check,
format,
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigText {
pub roots: Vec<RepoPath>,
pub registered: 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 registered = super::roots_d::registered_lenient(root);
let Some(text) = read_optional(&fs_path)? else {
return Ok(ConfigText {
roots: Config::default().roots,
registered,
declined: BTreeMap::new(),
hook_commands: BTreeMap::new(),
text: None,
});
};
let file = parse(&text).map_err(|m| Error::Init(format!("{path}: {m}")))?;
if let Some(m) = file.bad_with() {
return Err(Error::Init(format!("{path}: {m}")));
}
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,
registered,
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,
registered: vec![],
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()
],
registered: vec![],
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());
for text in [
"[harness.claude]\nwith = []\n",
"[harness.claude]\nwith = [\"hooks\"]\n",
] {
assert!(with(&dir, text).is_ok(), "{text:?}");
}
let e = with(&dir, "[harness.claude]\nwith = [\"skills\"]\n").unwrap_err();
assert!(matches!(e, Error::Config { .. }), "{e}");
assert!(e.to_string().contains("harness.claude.with"), "{e}");
let e = with(&dir, "[harness.claude]\nwithin = []\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();
}
#[test]
fn refuses_the_entries_of_the_packs() {
let dir = temp("packs");
let root = RepoRoot::new(dir.clone());
for text in [
"[[pack]]\nname = \"@acme/tool\"\nsource = \"./\"\n",
"[knowledge]\nroots = [\"/knowledge\"]\n\n[[pack]]\nname = \"rust\"\n",
"pack = []\n",
] {
let e = with(&dir, text).unwrap_err();
assert!(matches!(e, Error::Config { .. }), "{text:?} -> {e}");
assert!(
e.to_string().contains("packs are no longer part of sokf"),
"{e}"
);
let e = read_lenient(&root).unwrap_err();
assert!(matches!(e, Error::Init(_)), "{text:?} -> {e}");
assert!(
e.to_string().contains("packs are no longer part of sokf"),
"{e}"
);
}
let e = with(&dir, "foo = 1\n").unwrap_err().to_string();
assert!(e.contains("unknown field `foo`"), "{e}");
assert!(!e.contains("pack"), "{e}");
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn reads_the_format_table() {
let dir = temp("format");
for text in [
"[format]\ncommand = []\n",
"[format]\ncommand = [\"prettier\", \"--write\"]\n",
"[format]\ncommand = \"prettier {files}\"\n",
"[format]\nwidth = 3\n",
"[format]\ntimeout = 0\n",
"[format]\ntimeout = -1\n",
"[format]\ntimeout = 1.5\n",
] {
let e = with(&dir, text).unwrap_err();
assert!(matches!(e, Error::Config { .. }), "{text:?} -> {e}");
}
let config = with(
&dir,
"[format]\ncommand = [\"fmt\", \"{files}\"]\nsettings = { printWidth = 80, proseWrap = \"never\" }\n",
)
.unwrap();
assert_eq!(
config.format.command,
Some(vec!["fmt".into(), "{files}".into()])
);
assert_eq!(
config.format.settings.as_deref(),
Some(r#"{"printWidth":80,"proseWrap":"never"}"#)
);
assert_eq!(config.format.timeout, std::time::Duration::from_secs(10));
let config = with(&dir, "[format]\ntimeout = 3\n").unwrap();
assert_eq!(config.format.timeout, std::time::Duration::from_secs(3));
assert_eq!(with(&dir, "").unwrap().format, FormatConfig::default());
fs::remove_dir_all(&dir).unwrap();
}
}