Skip to main content

cccc_cli/
config.rs

1//! Optional `cccc.toml` configuration file.
2//!
3//! A config file lets a project bake in the options it normally runs with
4//! (extensions, excludes, thresholds, …) so they don't have to be repeated on
5//! every invocation. Resolution precedence is **CLI flag > config file >
6//! built-in default**: anything given explicitly on the command line always
7//! wins, the config file fills in the rest, and built-in defaults apply where
8//! neither speaks.
9//!
10//! By default the file is discovered by walking up from the current directory,
11//! looking for `cccc.toml` (then `.cccc.toml`) in each ancestor — so running
12//! `cccc` from anywhere inside a project picks up the project's config.
13//! `--config <path>` points at an explicit file (which must exist) and
14//! `--no-config` disables discovery entirely.
15
16use std::collections::BTreeMap;
17use std::path::{Path, PathBuf};
18
19use serde::Deserialize;
20
21/// File names searched for during upward discovery, in priority order.
22const CONFIG_NAMES: &[&str] = &["cccc.toml", ".cccc.toml"];
23
24/// The deserialized `cccc.toml`. Every field is optional; an absent field means
25/// "defer to the CLI flag or the built-in default". Unknown keys are rejected so
26/// typos surface as errors instead of being silently ignored.
27#[derive(Debug, Default, Deserialize)]
28#[serde(rename_all = "kebab-case", deny_unknown_fields)]
29pub struct Config {
30    /// Print a human-readable table instead of JSON.
31    pub table: Option<bool>,
32    /// Per-language file-extension overrides, e.g. `[ext]` with `es = ["ts"]`.
33    /// Each entry replaces that language's default extensions (and so also
34    /// routes those extensions to it). Keyed by a language's canonical name or
35    /// an alias. Languages without an entry keep their defaults.
36    pub ext: Option<BTreeMap<String, Vec<String>>>,
37    /// Glob patterns of files to exclude.
38    pub exclude: Option<Vec<String>>,
39    /// Languages to analyze (canonical names or aliases).
40    pub languages: Option<Vec<String>>,
41    /// Languages to exclude from analysis (the inverse of `languages`).
42    pub exclude_languages: Option<Vec<String>>,
43    /// Fail if any function's cognitive complexity exceeds this.
44    pub max_cognitive: Option<u32>,
45    /// Fail if any function's cyclomatic complexity exceeds this.
46    pub max_cyclomatic: Option<u32>,
47    /// Only report functions whose complexity is >= this.
48    pub min: Option<u32>,
49    /// Do not respect .gitignore / ignore files.
50    pub no_ignore: Option<bool>,
51    /// Number of files to analyze in parallel.
52    pub jobs: Option<u32>,
53}
54
55impl Config {
56    /// Resolve the config for this run, honoring `--config` / `--no-config`.
57    ///
58    /// - `--no-config` (`no_config = true`): always returns an empty config.
59    /// - `--config <path>` (`explicit = Some`): loads exactly that file; a
60    ///   missing or malformed file is an error.
61    /// - neither: discovers a file by walking up from the current directory,
62    ///   returning the empty config if none is found.
63    pub fn resolve(explicit: Option<&Path>, no_config: bool) -> Result<Config, String> {
64        if no_config {
65            return Ok(Config::default());
66        }
67        if let Some(path) = explicit {
68            if !path.exists() {
69                return Err(format!("config file not found: {}", path.display()));
70            }
71            return load(path);
72        }
73        match find_config() {
74            Some(path) => load(&path),
75            None => Ok(Config::default()),
76        }
77    }
78}
79
80/// Walk up from the current directory looking for a config file. Returns the
81/// path of the first match (checking [`CONFIG_NAMES`] in order within each
82/// directory), or `None` if none exists up to the filesystem root.
83fn find_config() -> Option<PathBuf> {
84    let cwd = std::env::current_dir().ok()?;
85    for dir in cwd.ancestors() {
86        for name in CONFIG_NAMES {
87            let candidate = dir.join(name);
88            if candidate.is_file() {
89                return Some(candidate);
90            }
91        }
92    }
93    None
94}
95
96/// Read and parse a config file, turning IO/parse failures into messages.
97fn load(path: &Path) -> Result<Config, String> {
98    let text = std::fs::read_to_string(path)
99        .map_err(|e| format!("cannot read config {}: {e}", path.display()))?;
100    toml::from_str(&text).map_err(|e| format!("invalid config {}: {e}", path.display()))
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106
107    #[test]
108    fn parses_all_fields() {
109        let cfg: Config = toml::from_str(
110            r#"
111            table = true
112            exclude = ["dist/**"]
113            languages = ["es", "go"]
114            max-cognitive = 15
115            max-cyclomatic = 10
116            min = 1
117            no-ignore = true
118            jobs = 8
119
120            [ext]
121            es = ["ts", "tsx"]
122            go = ["go", "tmpl"]
123        "#,
124        )
125        .unwrap();
126        assert_eq!(cfg.table, Some(true));
127        let ext = cfg.ext.as_ref().unwrap();
128        assert_eq!(ext["es"], vec!["ts".to_string(), "tsx".to_string()]);
129        assert_eq!(ext["go"], vec!["go".to_string(), "tmpl".to_string()]);
130        assert_eq!(
131            cfg.languages.as_deref(),
132            Some(&["es".to_string(), "go".to_string()][..])
133        );
134        assert_eq!(cfg.max_cognitive, Some(15));
135        assert_eq!(cfg.jobs, Some(8));
136    }
137
138    #[test]
139    fn empty_config_is_all_none() {
140        let cfg: Config = toml::from_str("").unwrap();
141        assert!(cfg.table.is_none() && cfg.ext.is_none() && cfg.max_cognitive.is_none());
142    }
143
144    #[test]
145    fn unknown_key_is_rejected() {
146        assert!(toml::from_str::<Config>("nonsense = 1").is_err());
147    }
148
149    #[test]
150    fn no_config_yields_default() {
151        let cfg = Config::resolve(None, true).unwrap();
152        assert!(cfg.ext.is_none());
153    }
154
155    #[test]
156    fn explicit_missing_config_errors() {
157        let err = Config::resolve(Some(Path::new("/no/such/cccc.toml")), false).unwrap_err();
158        assert!(err.contains("not found"));
159    }
160}