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/// How the report is rendered on stdout.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, clap::ValueEnum)]
23#[serde(rename_all = "kebab-case")]
24pub enum Format {
25    /// The full report as JSON (the default).
26    Json,
27    /// A human-readable per-file table.
28    Table,
29    /// One `path:line:` line per function, for grepping, editors and CI logs.
30    Simple,
31}
32
33/// File names searched for during upward discovery, in priority order.
34const CONFIG_NAMES: &[&str] = &["cccc.toml", ".cccc.toml"];
35
36/// The deserialized `cccc.toml`. Every field is optional; an absent field means
37/// "defer to the CLI flag or the built-in default". Unknown keys are rejected so
38/// typos surface as errors instead of being silently ignored.
39#[derive(Debug, Default, Deserialize)]
40#[serde(rename_all = "kebab-case", deny_unknown_fields)]
41pub struct Config {
42    /// Output format (`json`, `table` or `simple`). Takes precedence over
43    /// `table` when both are set.
44    pub format: Option<Format>,
45    /// Deprecated: use `format = "table"`. Print a human-readable table
46    /// instead of JSON.
47    pub table: Option<bool>,
48    /// Per-language file-extension overrides, e.g. `[ext]` with `es = ["ts"]`.
49    /// Each entry replaces that language's default extensions (and so also
50    /// routes those extensions to it). Keyed by a language's canonical name or
51    /// an alias. Languages without an entry keep their defaults.
52    pub ext: Option<BTreeMap<String, Vec<String>>>,
53    /// Glob patterns of files to exclude.
54    pub exclude: Option<Vec<String>>,
55    /// Languages to analyze (canonical names or aliases).
56    pub languages: Option<Vec<String>>,
57    /// Languages to exclude from analysis (the inverse of `languages`).
58    pub exclude_languages: Option<Vec<String>>,
59    /// Fail if any function's cognitive complexity exceeds this.
60    pub max_cognitive: Option<u32>,
61    /// Fail if any function's cyclomatic complexity exceeds this.
62    pub max_cyclomatic: Option<u32>,
63    /// Only report functions whose complexity is >= this.
64    pub min: Option<u32>,
65    /// Only report functions over `max-cognitive` / `max-cyclomatic`.
66    pub violations: Option<bool>,
67    /// Do not respect .gitignore / ignore files.
68    pub no_ignore: Option<bool>,
69    /// Number of files to analyze in parallel.
70    pub jobs: Option<u32>,
71    /// Pretty-print the JSON output (the default is compact, one line).
72    pub pretty: Option<bool>,
73    /// Cache results and reuse them for files unchanged since the last run.
74    pub cache: Option<bool>,
75    /// Where to keep the results cache (default: `.cccc.cache` next to this
76    /// config file). Does not enable caching by itself.
77    pub cache_file: Option<PathBuf>,
78    /// Directory containing the loaded config file. Not a config key — filled
79    /// in at load time so the default cache location can sit beside the file.
80    #[serde(skip)]
81    pub source_dir: Option<PathBuf>,
82}
83
84impl Config {
85    /// Resolve the config for this run, honoring `--config` / `--no-config`.
86    ///
87    /// - `--no-config` (`no_config = true`): always returns an empty config.
88    /// - `--config <path>` (`explicit = Some`): loads exactly that file; a
89    ///   missing or malformed file is an error.
90    /// - neither: discovers a file by walking up from the current directory,
91    ///   returning the empty config if none is found.
92    pub fn resolve(explicit: Option<&Path>, no_config: bool) -> Result<Config, String> {
93        if no_config {
94            return Ok(Config::default());
95        }
96        if let Some(path) = explicit {
97            if !path.exists() {
98                return Err(format!("config file not found: {}", path.display()));
99            }
100            return load(path);
101        }
102        match find_config() {
103            Some(path) => load(&path),
104            None => Ok(Config::default()),
105        }
106    }
107}
108
109/// Walk up from the current directory looking for a config file. Returns the
110/// path of the first match (checking [`CONFIG_NAMES`] in order within each
111/// directory), or `None` if none exists up to the filesystem root.
112fn find_config() -> Option<PathBuf> {
113    let cwd = std::env::current_dir().ok()?;
114    for dir in cwd.ancestors() {
115        for name in CONFIG_NAMES {
116            let candidate = dir.join(name);
117            if candidate.is_file() {
118                return Some(candidate);
119            }
120        }
121    }
122    None
123}
124
125/// Read and parse a config file, turning IO/parse failures into messages.
126fn load(path: &Path) -> Result<Config, String> {
127    let text = std::fs::read_to_string(path)
128        .map_err(|e| format!("cannot read config {}: {e}", path.display()))?;
129    let mut config: Config =
130        toml::from_str(&text).map_err(|e| format!("invalid config {}: {e}", path.display()))?;
131    config.source_dir = path.parent().map(Path::to_path_buf);
132    Ok(config)
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138
139    #[test]
140    fn parses_all_fields() {
141        let cfg: Config = toml::from_str(
142            r#"
143            table = true
144            exclude = ["dist/**"]
145            languages = ["es", "go"]
146            max-cognitive = 15
147            max-cyclomatic = 10
148            min = 1
149            no-ignore = true
150            jobs = 8
151
152            [ext]
153            es = ["ts", "tsx"]
154            go = ["go", "tmpl"]
155        "#,
156        )
157        .unwrap();
158        assert_eq!(cfg.table, Some(true));
159        let ext = cfg.ext.as_ref().unwrap();
160        assert_eq!(ext["es"], vec!["ts".to_string(), "tsx".to_string()]);
161        assert_eq!(ext["go"], vec!["go".to_string(), "tmpl".to_string()]);
162        assert_eq!(
163            cfg.languages.as_deref(),
164            Some(&["es".to_string(), "go".to_string()][..])
165        );
166        assert_eq!(cfg.max_cognitive, Some(15));
167        assert_eq!(cfg.jobs, Some(8));
168    }
169
170    #[test]
171    fn parses_format() {
172        let cfg: Config = toml::from_str("format = \"simple\"\nviolations = true").unwrap();
173        assert_eq!(cfg.format, Some(Format::Simple));
174        assert_eq!(cfg.violations, Some(true));
175        assert!(toml::from_str::<Config>(r#"format = "xml""#).is_err());
176    }
177
178    #[test]
179    fn empty_config_is_all_none() {
180        let cfg: Config = toml::from_str("").unwrap();
181        assert!(cfg.table.is_none() && cfg.ext.is_none() && cfg.max_cognitive.is_none());
182    }
183
184    #[test]
185    fn unknown_key_is_rejected() {
186        assert!(toml::from_str::<Config>("nonsense = 1").is_err());
187    }
188
189    #[test]
190    fn no_config_yields_default() {
191        let cfg = Config::resolve(None, true).unwrap();
192        assert!(cfg.ext.is_none());
193    }
194
195    #[test]
196    fn explicit_missing_config_errors() {
197        let err = Config::resolve(Some(Path::new("/no/such/cccc.toml")), false).unwrap_err();
198        assert!(err.contains("not found"));
199    }
200}