use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use serde::Deserialize;
const CONFIG_NAMES: &[&str] = &["cccc.toml", ".cccc.toml"];
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct Config {
pub table: Option<bool>,
pub ext: Option<BTreeMap<String, Vec<String>>>,
pub exclude: Option<Vec<String>>,
pub languages: Option<Vec<String>>,
pub exclude_languages: Option<Vec<String>>,
pub max_cognitive: Option<u32>,
pub max_cyclomatic: Option<u32>,
pub min: Option<u32>,
pub no_ignore: Option<bool>,
pub jobs: Option<u32>,
pub pretty: Option<bool>,
pub cache: Option<bool>,
pub cache_file: Option<PathBuf>,
#[serde(skip)]
pub source_dir: Option<PathBuf>,
}
impl Config {
pub fn resolve(explicit: Option<&Path>, no_config: bool) -> Result<Config, String> {
if no_config {
return Ok(Config::default());
}
if let Some(path) = explicit {
if !path.exists() {
return Err(format!("config file not found: {}", path.display()));
}
return load(path);
}
match find_config() {
Some(path) => load(&path),
None => Ok(Config::default()),
}
}
}
fn find_config() -> Option<PathBuf> {
let cwd = std::env::current_dir().ok()?;
for dir in cwd.ancestors() {
for name in CONFIG_NAMES {
let candidate = dir.join(name);
if candidate.is_file() {
return Some(candidate);
}
}
}
None
}
fn load(path: &Path) -> Result<Config, String> {
let text = std::fs::read_to_string(path)
.map_err(|e| format!("cannot read config {}: {e}", path.display()))?;
let mut config: Config =
toml::from_str(&text).map_err(|e| format!("invalid config {}: {e}", path.display()))?;
config.source_dir = path.parent().map(Path::to_path_buf);
Ok(config)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_all_fields() {
let cfg: Config = toml::from_str(
r#"
table = true
exclude = ["dist/**"]
languages = ["es", "go"]
max-cognitive = 15
max-cyclomatic = 10
min = 1
no-ignore = true
jobs = 8
[ext]
es = ["ts", "tsx"]
go = ["go", "tmpl"]
"#,
)
.unwrap();
assert_eq!(cfg.table, Some(true));
let ext = cfg.ext.as_ref().unwrap();
assert_eq!(ext["es"], vec!["ts".to_string(), "tsx".to_string()]);
assert_eq!(ext["go"], vec!["go".to_string(), "tmpl".to_string()]);
assert_eq!(
cfg.languages.as_deref(),
Some(&["es".to_string(), "go".to_string()][..])
);
assert_eq!(cfg.max_cognitive, Some(15));
assert_eq!(cfg.jobs, Some(8));
}
#[test]
fn empty_config_is_all_none() {
let cfg: Config = toml::from_str("").unwrap();
assert!(cfg.table.is_none() && cfg.ext.is_none() && cfg.max_cognitive.is_none());
}
#[test]
fn unknown_key_is_rejected() {
assert!(toml::from_str::<Config>("nonsense = 1").is_err());
}
#[test]
fn no_config_yields_default() {
let cfg = Config::resolve(None, true).unwrap();
assert!(cfg.ext.is_none());
}
#[test]
fn explicit_missing_config_errors() {
let err = Config::resolve(Some(Path::new("/no/such/cccc.toml")), false).unwrap_err();
assert!(err.contains("not found"));
}
}