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 /// Pretty-print the JSON output (the default is compact, one line).
54 pub pretty: Option<bool>,
55 /// Cache results and reuse them for files unchanged since the last run.
56 pub cache: Option<bool>,
57 /// Where to keep the results cache (default: `.cccc.cache` next to this
58 /// config file). Does not enable caching by itself.
59 pub cache_file: Option<PathBuf>,
60 /// Directory containing the loaded config file. Not a config key — filled
61 /// in at load time so the default cache location can sit beside the file.
62 #[serde(skip)]
63 pub source_dir: Option<PathBuf>,
64}
65
66impl Config {
67 /// Resolve the config for this run, honoring `--config` / `--no-config`.
68 ///
69 /// - `--no-config` (`no_config = true`): always returns an empty config.
70 /// - `--config <path>` (`explicit = Some`): loads exactly that file; a
71 /// missing or malformed file is an error.
72 /// - neither: discovers a file by walking up from the current directory,
73 /// returning the empty config if none is found.
74 pub fn resolve(explicit: Option<&Path>, no_config: bool) -> Result<Config, String> {
75 if no_config {
76 return Ok(Config::default());
77 }
78 if let Some(path) = explicit {
79 if !path.exists() {
80 return Err(format!("config file not found: {}", path.display()));
81 }
82 return load(path);
83 }
84 match find_config() {
85 Some(path) => load(&path),
86 None => Ok(Config::default()),
87 }
88 }
89}
90
91/// Walk up from the current directory looking for a config file. Returns the
92/// path of the first match (checking [`CONFIG_NAMES`] in order within each
93/// directory), or `None` if none exists up to the filesystem root.
94fn find_config() -> Option<PathBuf> {
95 let cwd = std::env::current_dir().ok()?;
96 for dir in cwd.ancestors() {
97 for name in CONFIG_NAMES {
98 let candidate = dir.join(name);
99 if candidate.is_file() {
100 return Some(candidate);
101 }
102 }
103 }
104 None
105}
106
107/// Read and parse a config file, turning IO/parse failures into messages.
108fn load(path: &Path) -> Result<Config, String> {
109 let text = std::fs::read_to_string(path)
110 .map_err(|e| format!("cannot read config {}: {e}", path.display()))?;
111 let mut config: Config =
112 toml::from_str(&text).map_err(|e| format!("invalid config {}: {e}", path.display()))?;
113 config.source_dir = path.parent().map(Path::to_path_buf);
114 Ok(config)
115}
116
117#[cfg(test)]
118mod tests {
119 use super::*;
120
121 #[test]
122 fn parses_all_fields() {
123 let cfg: Config = toml::from_str(
124 r#"
125 table = true
126 exclude = ["dist/**"]
127 languages = ["es", "go"]
128 max-cognitive = 15
129 max-cyclomatic = 10
130 min = 1
131 no-ignore = true
132 jobs = 8
133
134 [ext]
135 es = ["ts", "tsx"]
136 go = ["go", "tmpl"]
137 "#,
138 )
139 .unwrap();
140 assert_eq!(cfg.table, Some(true));
141 let ext = cfg.ext.as_ref().unwrap();
142 assert_eq!(ext["es"], vec!["ts".to_string(), "tsx".to_string()]);
143 assert_eq!(ext["go"], vec!["go".to_string(), "tmpl".to_string()]);
144 assert_eq!(
145 cfg.languages.as_deref(),
146 Some(&["es".to_string(), "go".to_string()][..])
147 );
148 assert_eq!(cfg.max_cognitive, Some(15));
149 assert_eq!(cfg.jobs, Some(8));
150 }
151
152 #[test]
153 fn empty_config_is_all_none() {
154 let cfg: Config = toml::from_str("").unwrap();
155 assert!(cfg.table.is_none() && cfg.ext.is_none() && cfg.max_cognitive.is_none());
156 }
157
158 #[test]
159 fn unknown_key_is_rejected() {
160 assert!(toml::from_str::<Config>("nonsense = 1").is_err());
161 }
162
163 #[test]
164 fn no_config_yields_default() {
165 let cfg = Config::resolve(None, true).unwrap();
166 assert!(cfg.ext.is_none());
167 }
168
169 #[test]
170 fn explicit_missing_config_errors() {
171 let err = Config::resolve(Some(Path::new("/no/such/cccc.toml")), false).unwrap_err();
172 assert!(err.contains("not found"));
173 }
174}