Skip to main content

cccc_cli/
lib.rs

1//! The unified `cccc` CLI.
2//!
3//! One binary measures Cognitive Complexity and Cyclomatic Complexity across
4//! every bundled language. A file is routed to the right front-end by its
5//! extension (see [`lang`]), so a single run can analyze a mixed-language tree.
6//! Recurring options can be baked into a `cccc.toml` config file (see
7//! [`config`]); CLI flags always take precedence over it.
8//!
9//! Everything common to the languages lives here: argument parsing, config
10//! resolution, file discovery, parallel analysis, the threshold/`--min`/`--top`
11//! logic, and output rendering. Each language supplies only how to analyze one
12//! file and its default extensions, via the [`lang::LANGUAGES`] registry.
13//!
14//! ## Exit codes
15//!
16//! [`run`] returns a process exit code with a consistent meaning:
17//! - `0` — success (including an existing input path that simply contains no
18//!   matching files: "nothing to analyze" is not an error).
19//! - `1` — a `--max-cognitive`/`--max-cyclomatic` threshold was exceeded
20//!   (the CI gate).
21//! - `2` — unable to proceed: a given path does not exist, a config/`--lang`
22//!   value was invalid, or the worker pool could not be created. (clap's own
23//!   usage errors also exit `2`.)
24
25mod cli;
26pub mod config;
27pub mod lang;
28mod output;
29mod walk;
30
31use std::collections::{BTreeMap, HashMap};
32use std::path::Path;
33
34use clap::parser::ValueSource;
35use clap::{CommandFactory, FromArgMatches};
36use rayon::prelude::*;
37
38use cccc_core::report::{self, FileReport, FunctionReport, Metric, Report};
39use cli::Cli;
40use config::Config;
41
42/// Below this many files, sequential analysis beats paying for a rayon pool.
43const PARALLEL_THRESHOLD: usize = 16;
44
45/// Analyze one file's source into a [`FileReport`]. Implemented per language by
46/// the relevant adapter (e.g. `cccc_es::analyze_source`).
47pub type AnalyzeFn = fn(&Path, &str) -> FileReport;
48
49/// Run the CLI end to end and return a process exit code.
50pub fn run() -> i32 {
51    let command = Cli::command()
52        .name("cccc")
53        .bin_name("cccc")
54        .version(env!("CARGO_PKG_VERSION"));
55    let matches = command.get_matches();
56    let cli = match Cli::from_arg_matches(&matches) {
57        Ok(cli) => cli,
58        Err(e) => e.exit(),
59    };
60
61    // Load the config file (honoring --config/--no-config) before resolving any
62    // option, so CLI flags can be layered on top of it.
63    let config = match Config::resolve(cli.config.as_deref(), cli.no_config) {
64        Ok(config) => config,
65        Err(e) => {
66            eprintln!("cccc: {e}");
67            return 2;
68        }
69    };
70
71    // Resolve each option as: explicit CLI value > config file > built-in
72    // default. `was_set` distinguishes a flag the user actually passed from one
73    // sitting at its clap default (needed for the boolean flags).
74    let was_set = |id: &str| matches.value_source(id) == Some(ValueSource::CommandLine);
75    let table = if was_set("table") {
76        cli.table
77    } else {
78        config.table.unwrap_or(false)
79    };
80    let no_ignore = if was_set("no_ignore") {
81        cli.no_ignore
82    } else {
83        config.no_ignore.unwrap_or(false)
84    };
85    let exclude_patterns = if was_set("exclude") {
86        cli.exclude.clone()
87    } else {
88        config.exclude.clone().unwrap_or_default()
89    };
90    let max_cognitive = cli.max_cognitive.or(config.max_cognitive);
91    let max_cyclomatic = cli.max_cyclomatic.or(config.max_cyclomatic);
92    let min = cli.min.or(config.min);
93    let jobs_opt = cli.jobs.or(config.jobs);
94    let lang_filter = cli.lang.clone().or_else(|| config.languages.clone());
95    let exclude_lang_filter = cli
96        .exclude_lang
97        .clone()
98        .or_else(|| config.exclude_languages.clone());
99    // Resolve extensions from both the config `[ext]` table and the `--ext`
100    // flag. `per_lang_ext` (keyed by canonical language name) replaces a
101    // language's default extensions and routes them to it; `global_ext` is a
102    // cross-language scan filter. CLI per-language entries override the config's.
103    let (per_lang_ext, global_ext) = match resolve_ext(config.ext.clone(), cli.ext.as_deref()) {
104        Ok(pair) => pair,
105        Err(e) => {
106            eprintln!("cccc: {e}");
107            return 2;
108        }
109    };
110
111    // A path that doesn't exist is almost always a typo, so fail loudly rather
112    // than silently reporting "no files". (A path that exists but contains no
113    // matching files is still treated as an empty, successful run below.)
114    let mut any_missing = false;
115    for path in cli.paths.iter().filter(|p| !p.exists()) {
116        eprintln!("cccc: path does not exist: {}", path.display());
117        any_missing = true;
118    }
119    if any_missing {
120        return 2;
121    }
122
123    // Determine which languages are in play and build the extension→analyzer
124    // dispatch used to route each file.
125    let languages =
126        match lang::resolve_languages(lang_filter.as_deref(), exclude_lang_filter.as_deref()) {
127            Ok(langs) => langs,
128            Err(e) => {
129                eprintln!("cccc: {e}");
130                return 2;
131            }
132        };
133    let dispatch = lang::build_dispatch(&languages, &per_lang_ext);
134
135    // Which extensions to collect: a global `--ext` filter if one was given,
136    // otherwise the union of the active languages' (possibly overridden)
137    // extensions. Either way each file is dispatched by its own extension.
138    let exts: Vec<String> = if global_ext.is_empty() {
139        dispatch.keys().cloned().collect()
140    } else {
141        for ext in &global_ext {
142            if !dispatch.contains_key(ext) {
143                eprintln!(
144                    "cccc: warning: no active language analyzes .{ext} files; they will be skipped"
145                );
146            }
147        }
148        global_ext
149    };
150
151    // Compile the exclude globs up front so a bad pattern fails loudly (exit 2)
152    // rather than silently skipping nothing.
153    let exclude = match walk::build_exclude_set(&exclude_patterns) {
154        Ok(set) => set,
155        Err(e) => {
156            eprintln!("cccc: invalid --exclude pattern: {e}");
157            return 2;
158        }
159    };
160
161    let files = walk::collect_files(&cli.paths, &exts, no_ignore, exclude.as_ref());
162    if files.is_empty() {
163        eprintln!("cccc: no matching files found");
164        return 0;
165    }
166
167    // `--jobs` caps the worker count; without it we fall back to the number of
168    // logical CPUs (1 if that can't be determined).
169    let jobs = jobs_opt.map(|j| j as usize).unwrap_or_else(|| {
170        std::thread::available_parallelism()
171            .map(|n| n.get())
172            .unwrap_or(1)
173    });
174
175    // For a handful of files, spinning up a rayon pool costs more than it saves,
176    // so analyze sequentially. Above the threshold, fan out across `jobs` workers.
177    let mut reports: Vec<FileReport> = if jobs <= 1 || files.len() <= PARALLEL_THRESHOLD {
178        files
179            .iter()
180            .filter_map(|p| read_and_analyze(&dispatch, p))
181            .collect()
182    } else {
183        let pool = match rayon::ThreadPoolBuilder::new().num_threads(jobs).build() {
184            Ok(pool) => pool,
185            Err(e) => {
186                eprintln!("cccc: failed to start thread pool: {e}");
187                return 2;
188            }
189        };
190        pool.install(|| {
191            files
192                .par_iter()
193                .filter_map(|p| read_and_analyze(&dispatch, p))
194                .collect()
195        })
196    };
197
198    reports.sort_by(|a, b| a.path.cmp(&b.path));
199
200    // Determine exit status before any `--min` filtering, so display options do
201    // not change pass/fail behaviour.
202    let fail = (max_cognitive.is_some() || max_cyclomatic.is_some())
203        && reports
204            .iter()
205            .any(|r| exceeds(&r.functions, max_cognitive, max_cyclomatic));
206
207    // Compute the summary over the full population, before `--min`/`--top` change
208    // what is displayed, so the distribution always reflects all code.
209    let summary = report::compute_summary(&reports);
210
211    // `--top-*` is a distinct, flat ranking view that replaces the per-file
212    // output. The two top flags are mutually exclusive (enforced by clap).
213    let top_request = match (cli.top_cognitive, cli.top_cyclomatic) {
214        (Some(n), _) => Some((Metric::Cognitive, n)),
215        (_, Some(n)) => Some((Metric::Cyclomatic, n)),
216        (None, None) => None,
217    };
218    if let Some((metric, n)) = top_request {
219        let top = report::build_top_report(&reports, summary, metric, n);
220        if table {
221            output::print_top_table(&top);
222        } else {
223            output::print_json(&top);
224        }
225        return i32::from(fail);
226    }
227
228    if let Some(min) = min {
229        for r in &mut reports {
230            r.functions = filter_min(std::mem::take(&mut r.functions), min);
231        }
232    }
233
234    let report = Report {
235        files: reports,
236        summary,
237    };
238
239    if table {
240        output::print_table(&report);
241    } else {
242        output::print_json(&report);
243    }
244
245    i32::from(fail)
246}
247
248/// Resolved extension settings: per-language overrides keyed by canonical
249/// language name, plus the global cross-language scan filter.
250type ExtSettings = (BTreeMap<String, Vec<String>>, Vec<String>);
251
252/// Merge the config `[ext]` table and the `--ext` flag into [`ExtSettings`].
253///
254/// Config entries are applied first, then CLI entries, so a `--ext lang=…`
255/// overrides the config's entry for the same language. Each `--ext` value is
256/// either `LANG=ext,ext` (a per-language override) or `ext,ext` (added to the
257/// global filter). An unknown language name (in either source) is an error.
258fn resolve_ext(
259    config_ext: Option<BTreeMap<String, Vec<String>>>,
260    cli_ext: Option<&[String]>,
261) -> Result<ExtSettings, String> {
262    let mut per_lang: BTreeMap<String, Vec<String>> = BTreeMap::new();
263    if let Some(cfg) = config_ext {
264        for (key, list) in cfg {
265            let canon = lang::require_canonical(key.trim(), "[ext] config")?;
266            per_lang.insert(canon.to_string(), list);
267        }
268    }
269    let mut global: Vec<String> = Vec::new();
270    for raw in cli_ext.unwrap_or(&[]) {
271        match raw.split_once('=') {
272            Some((name, exts)) => {
273                let canon = lang::require_canonical(name.trim(), "--ext")?;
274                per_lang.insert(canon.to_string(), split_exts(exts));
275            }
276            None => global.extend(split_exts(raw).into_iter().map(|e| e.to_ascii_lowercase())),
277        }
278    }
279    Ok((per_lang, global))
280}
281
282/// Split a comma-separated extension list, trimming blanks and empties.
283fn split_exts(s: &str) -> Vec<String> {
284    s.split(',')
285        .map(|e| e.trim().to_string())
286        .filter(|e| !e.is_empty())
287        .collect()
288}
289
290/// Read a file and analyze it with the language matching its extension,
291/// reporting (but not failing on) read errors. A file whose extension no active
292/// language claims is skipped silently (it was only collected via `--ext`).
293fn read_and_analyze(dispatch: &HashMap<String, AnalyzeFn>, path: &Path) -> Option<FileReport> {
294    let analyze = path
295        .extension()
296        .and_then(|e| e.to_str())
297        .and_then(|e| dispatch.get(&e.to_ascii_lowercase()))?;
298    match std::fs::read_to_string(path) {
299        Ok(src) => Some(analyze(path, &src)),
300        Err(e) => {
301            eprintln!("cccc: cannot read {}: {e}", path.display());
302            None
303        }
304    }
305}
306
307/// True if any function (at any depth) exceeds either threshold.
308fn exceeds(fns: &[FunctionReport], max_cog: Option<u32>, max_cyc: Option<u32>) -> bool {
309    fns.iter().any(|f| {
310        max_cog.is_some_and(|m| f.cognitive > m)
311            || max_cyc.is_some_and(|m| f.cyclomatic > m)
312            || exceeds(&f.children, max_cog, max_cyc)
313    })
314}
315
316/// Keep functions whose own complexity meets `min`, or that have a kept
317/// descendant.
318fn filter_min(fns: Vec<FunctionReport>, min: u32) -> Vec<FunctionReport> {
319    fns.into_iter()
320        .filter_map(|mut f| {
321            f.children = filter_min(std::mem::take(&mut f.children), min);
322            let keep = f.cognitive >= min || f.cyclomatic >= min || !f.children.is_empty();
323            if keep { Some(f) } else { None }
324        })
325        .collect()
326}