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, the results cache (see [`cache`]), parallel
11//! analysis, the threshold/`--min`/`--top` logic, and output rendering. Each
12//! language supplies only how to analyze one file and its default extensions,
13//! via the [`lang::LANGUAGES`] registry.
14//!
15//! ## Exit codes
16//!
17//! [`run`] returns a process exit code with a consistent meaning:
18//! - `0` — success (including an existing input path that simply contains no
19//!   matching files: "nothing to analyze" is not an error).
20//! - `1` — a `--max-cognitive`/`--max-cyclomatic` threshold was exceeded
21//!   (the CI gate).
22//! - `2` — unable to proceed: a given path does not exist, a config/`--lang`
23//!   value was invalid, or the worker pool could not be created. (clap's own
24//!   usage errors also exit `2`.)
25
26mod cache;
27mod cli;
28pub mod config;
29pub mod lang;
30mod output;
31mod walk;
32
33use std::collections::{BTreeMap, HashMap};
34use std::path::Path;
35
36use clap::parser::ValueSource;
37use clap::{CommandFactory, FromArgMatches};
38use rayon::prelude::*;
39
40use cccc_core::report::{self, FileReport, FunctionReport, Metric, Report};
41use cli::Cli;
42use config::Config;
43
44/// Below this many files, sequential analysis beats paying for a rayon pool.
45const PARALLEL_THRESHOLD: usize = 16;
46
47/// Analyze one file's source into a [`FileReport`]. Implemented per language by
48/// the relevant adapter (e.g. `cccc_es::analyze_source`).
49pub type AnalyzeFn = fn(&Path, &str) -> FileReport;
50
51/// Run the CLI end to end and return a process exit code.
52pub fn run() -> i32 {
53    let command = Cli::command()
54        .name("cccc")
55        .bin_name("cccc")
56        .version(env!("CARGO_PKG_VERSION"));
57    let matches = command.get_matches();
58    let cli = match Cli::from_arg_matches(&matches) {
59        Ok(cli) => cli,
60        Err(e) => e.exit(),
61    };
62
63    // Load the config file (honoring --config/--no-config) before resolving any
64    // option, so CLI flags can be layered on top of it.
65    let config = match Config::resolve(cli.config.as_deref(), cli.no_config) {
66        Ok(config) => config,
67        Err(e) => {
68            eprintln!("cccc: {e}");
69            return 2;
70        }
71    };
72
73    // Resolve each option as: explicit CLI value > config file > built-in
74    // default. `was_set` distinguishes a flag the user actually passed from one
75    // sitting at its clap default (needed for the boolean flags).
76    let was_set = |id: &str| matches.value_source(id) == Some(ValueSource::CommandLine);
77    let table = if was_set("table") {
78        cli.table
79    } else {
80        config.table.unwrap_or(false)
81    };
82    let no_ignore = if was_set("no_ignore") {
83        cli.no_ignore
84    } else {
85        config.no_ignore.unwrap_or(false)
86    };
87    let exclude_patterns = if was_set("exclude") {
88        cli.exclude.clone()
89    } else {
90        config.exclude.clone().unwrap_or_default()
91    };
92    let pretty = if was_set("pretty") {
93        cli.pretty
94    } else {
95        config.pretty.unwrap_or(false)
96    };
97    // The cache is on when the user says so (`--cache`, an explicit
98    // `--cache-file`, or `cache = true` in the config) and `--no-cache` doesn't
99    // veto it. The file defaults to `.cccc.cache` beside the config file, so a
100    // project-enabled cache lands in the same place from any subdirectory.
101    let cache_enabled = if cli.no_cache {
102        false
103    } else {
104        cli.cache || cli.cache_file.is_some() || config.cache.unwrap_or(false)
105    };
106    let cache_path: Option<std::path::PathBuf> = cache_enabled.then(|| {
107        cli.cache_file
108            .clone()
109            .or_else(|| config.cache_file.clone())
110            .unwrap_or_else(|| {
111                config
112                    .source_dir
113                    .as_deref()
114                    .unwrap_or(Path::new(""))
115                    .join(".cccc.cache")
116            })
117    });
118    // Tooling introspection: report where the cache would live (nothing when
119    // disabled) so wrappers like CI actions can wire persistence around it
120    // without re-implementing config discovery.
121    if cli.print_cache_file {
122        if let Some(path) = &cache_path {
123            println!("{}", path.display());
124        }
125        return 0;
126    }
127
128    let max_cognitive = cli.max_cognitive.or(config.max_cognitive);
129    let max_cyclomatic = cli.max_cyclomatic.or(config.max_cyclomatic);
130    let min = cli.min.or(config.min);
131    let jobs_opt = cli.jobs.or(config.jobs);
132    let lang_filter = cli.lang.clone().or_else(|| config.languages.clone());
133    let exclude_lang_filter = cli
134        .exclude_lang
135        .clone()
136        .or_else(|| config.exclude_languages.clone());
137    // Resolve extensions from both the config `[ext]` table and the `--ext`
138    // flag. `per_lang_ext` (keyed by canonical language name) replaces a
139    // language's default extensions and routes them to it; `global_ext` is a
140    // cross-language scan filter. CLI per-language entries override the config's.
141    let (per_lang_ext, global_ext) = match resolve_ext(config.ext.clone(), cli.ext.as_deref()) {
142        Ok(pair) => pair,
143        Err(e) => {
144            eprintln!("cccc: {e}");
145            return 2;
146        }
147    };
148
149    // A path that doesn't exist is almost always a typo, so fail loudly rather
150    // than silently reporting "no files". (A path that exists but contains no
151    // matching files is still treated as an empty, successful run below.)
152    let mut any_missing = false;
153    for path in cli.paths.iter().filter(|p| !p.exists()) {
154        eprintln!("cccc: path does not exist: {}", path.display());
155        any_missing = true;
156    }
157    if any_missing {
158        return 2;
159    }
160
161    // Determine which languages are in play and build the extension→analyzer
162    // dispatch used to route each file.
163    let languages =
164        match lang::resolve_languages(lang_filter.as_deref(), exclude_lang_filter.as_deref()) {
165            Ok(langs) => langs,
166            Err(e) => {
167                eprintln!("cccc: {e}");
168                return 2;
169            }
170        };
171    let dispatch = lang::build_dispatch(&languages, &per_lang_ext);
172
173    // Which extensions to collect: a global `--ext` filter if one was given,
174    // otherwise the union of the active languages' (possibly overridden)
175    // extensions. Either way each file is dispatched by its own extension.
176    let exts: Vec<String> = if global_ext.is_empty() {
177        dispatch.keys().cloned().collect()
178    } else {
179        for ext in &global_ext {
180            if !dispatch.contains_key(ext) {
181                output::warn(&format!(
182                    "cccc: warning: no active language analyzes .{ext} files; they will be skipped"
183                ));
184            }
185        }
186        global_ext
187    };
188
189    // Compile the exclude globs up front so a bad pattern fails loudly (exit 2)
190    // rather than silently skipping nothing.
191    let exclude = match walk::build_exclude_set(&exclude_patterns) {
192        Ok(set) => set,
193        Err(e) => {
194            eprintln!("cccc: invalid --exclude pattern: {e}");
195            return 2;
196        }
197    };
198
199    // `--jobs` caps the worker count; without it we fall back to the number of
200    // logical CPUs (1 if that can't be determined). Resolved before discovery
201    // because the directory walk fans out across the same worker count.
202    let jobs = jobs_opt.map(|j| j as usize).unwrap_or_else(|| {
203        std::thread::available_parallelism()
204            .map(|n| n.get())
205            .unwrap_or(1)
206    });
207
208    // Let cache validation ask git which files are clean and what their blob
209    // SHAs are, so it can skip reading files whose mtime moved but whose
210    // content didn't — the CI fast path: a fresh checkout resets every mtime
211    // but writes a stat-clean index. Consulted (and under CI, started) only
212    // when needed — see [`cache::LazyGitIndex`] — and only prepared at all
213    // when there is an existing cache to validate against.
214    let git_index = cache_path.as_ref().filter(|p| p.exists()).map(|_| {
215        let root = match cli.paths.first() {
216            Some(p) if p.is_dir() => p.clone(),
217            Some(p) => p
218                .parent()
219                .filter(|d| !d.as_os_str().is_empty())
220                .unwrap_or(Path::new("."))
221                .to_path_buf(),
222            None => std::path::PathBuf::from("."),
223        };
224        cache::LazyGitIndex::new(root)
225    });
226
227    let files = walk::collect_files(&cli.paths, &exts, no_ignore, exclude.as_ref(), jobs);
228    if files.is_empty() {
229        eprintln!("cccc: no matching files found");
230        return 0;
231    }
232
233    // For a handful of files, spinning up a rayon pool costs more than it
234    // saves, so run sequentially. Above the threshold one pool drives every
235    // parallel phase (cache validation, analysis, cache write-back), keeping
236    // `--jobs` an honest bound on worker count.
237    let pool = if jobs <= 1 || files.len() <= PARALLEL_THRESHOLD {
238        None
239    } else {
240        match rayon::ThreadPoolBuilder::new().num_threads(jobs).build() {
241            Ok(pool) => Some(pool),
242            Err(e) => {
243                eprintln!("cccc: failed to start thread pool: {e}");
244                return 2;
245            }
246        }
247    };
248
249    // Split the files into cache hits (report ready) and misses (to analyze).
250    // Without a usable cache everything is a miss.
251    let cache = cache_path.as_deref().and_then(cache::load);
252    let mut sig_refreshed = false;
253    let (cached_entries, to_analyze): (
254        Vec<(FileReport, Option<cache::Sig>)>,
255        Vec<&std::path::PathBuf>,
256    ) = match &cache {
257        Some(c) => {
258            let git = git_index.as_ref();
259            let checked: Vec<Result<cache::Hit, &std::path::PathBuf>> = match &pool {
260                Some(pool) => pool.install(|| {
261                    files
262                        .par_iter()
263                        .map(|p| check_cached(c, &dispatch, p, git))
264                        .collect()
265                }),
266                None => files
267                    .iter()
268                    .map(|p| check_cached(c, &dispatch, p, git))
269                    .collect(),
270            };
271            let mut hits = Vec::new();
272            let mut misses = Vec::new();
273            for entry in checked {
274                match entry {
275                    Ok(hit) => {
276                        sig_refreshed |= hit.refreshed;
277                        hits.push((hit.report, Some(hit.sig)));
278                    }
279                    Err(p) => misses.push(p),
280                }
281            }
282            (hits, misses)
283        }
284        None => (Vec::new(), files.iter().collect()),
285    };
286
287    // Analyze the misses, signing each off the bytes just read when a cache is
288    // in play (no cache, no hashing cost).
289    let want_sig = cache_path.is_some();
290    let mut entries: Vec<(FileReport, Option<cache::Sig>)> = match &pool {
291        Some(pool) => pool.install(|| {
292            to_analyze
293                .par_iter()
294                .filter_map(|p| read_and_analyze(&dispatch, p, want_sig))
295                .collect()
296        }),
297        None => to_analyze
298            .iter()
299            .filter_map(|p| read_and_analyze(&dispatch, p, want_sig))
300            .collect(),
301    };
302    entries.extend(cached_entries);
303
304    // Refresh the cache — unless it is already exactly what we would write:
305    // every file was a stat hit AND the cache holds nothing else. The second
306    // check matters when files were deleted (or newly excluded) since the last
307    // run — all-hits alone would skip the write and leave their stale entries
308    // behind. A hit that passed by content hash also forces the write: its
309    // stored mtime is stale, and persisting the refreshed one is what lets the
310    // next run stat-hit instead of hashing again.
311    let cache_is_current = cache.as_ref().is_some_and(|c| {
312        to_analyze.is_empty() && !sig_refreshed && c.entry_count() == entries.len()
313    });
314    if let Some(cache_file) = cache_path.as_deref()
315        && !cache_is_current
316    {
317        let store = || {
318            cache::store(cache_file, &entries, &|p| {
319                lang_for(&dispatch, p).map(|l| l.name)
320            })
321        };
322        match &pool {
323            Some(pool) => pool.install(store),
324            None => store(),
325        }
326    }
327
328    let mut reports: Vec<FileReport> = entries.into_iter().map(|(r, _)| r).collect();
329    reports.sort_by(|a, b| a.path.cmp(&b.path));
330
331    // Determine exit status before any `--min` filtering, so display options do
332    // not change pass/fail behaviour.
333    let fail = (max_cognitive.is_some() || max_cyclomatic.is_some())
334        && reports
335            .iter()
336            .any(|r| exceeds(&r.functions, max_cognitive, max_cyclomatic));
337
338    // Compute the summary over the full population, before `--min`/`--top` change
339    // what is displayed, so the distribution always reflects all code.
340    let summary = report::compute_summary(&reports);
341
342    // Parse errors mean the scores may be computed from a partial parse. JSON
343    // consumers see this in `summary`; for the human-readable views, warn on
344    // stderr — with the affected paths — so it isn't lost in a long table.
345    if table && summary.parse_error_count > 0 {
346        output::warn(&format!(
347            "cccc: warning: {} parse error(s) in {} file(s); results for those files may be incomplete:",
348            summary.parse_error_count, summary.parse_error_file_count
349        ));
350        for r in reports.iter().filter(|r| !r.parse_errors.is_empty()) {
351            output::warn(&format!("cccc:   {} ({})", r.path, r.parse_errors.len()));
352        }
353    }
354
355    // `--top-*` is a distinct, flat ranking view that replaces the per-file
356    // output. The two top flags are mutually exclusive (enforced by clap).
357    let top_request = match (cli.top_cognitive, cli.top_cyclomatic) {
358        (Some(n), _) => Some((Metric::Cognitive, n)),
359        (_, Some(n)) => Some((Metric::Cyclomatic, n)),
360        (None, None) => None,
361    };
362    if let Some((metric, n)) = top_request {
363        let top = report::build_top_report(&reports, summary, metric, n);
364        if table {
365            output::print_top_table(&top);
366        } else {
367            output::print_json(&top, pretty);
368        }
369        return i32::from(fail);
370    }
371
372    if let Some(min) = min {
373        for r in &mut reports {
374            r.functions = filter_min(std::mem::take(&mut r.functions), min);
375        }
376    }
377
378    let report = Report {
379        files: reports,
380        summary,
381    };
382
383    if table {
384        output::print_table(&report);
385    } else {
386        output::print_json(&report, pretty);
387    }
388
389    i32::from(fail)
390}
391
392/// Resolved extension settings: per-language overrides keyed by canonical
393/// language name, plus the global cross-language scan filter.
394type ExtSettings = (BTreeMap<String, Vec<String>>, Vec<String>);
395
396/// Merge the config `[ext]` table and the `--ext` flag into [`ExtSettings`].
397///
398/// Config entries are applied first, then CLI entries, so a `--ext lang=…`
399/// overrides the config's entry for the same language. Each `--ext` value is
400/// either `LANG=ext,ext` (a per-language override) or `ext,ext` (added to the
401/// global filter). An unknown language name (in either source) is an error.
402fn resolve_ext(
403    config_ext: Option<BTreeMap<String, Vec<String>>>,
404    cli_ext: Option<&[String]>,
405) -> Result<ExtSettings, String> {
406    let mut per_lang: BTreeMap<String, Vec<String>> = BTreeMap::new();
407    if let Some(cfg) = config_ext {
408        for (key, list) in cfg {
409            let canon = lang::require_canonical(key.trim(), "[ext] config")?;
410            per_lang.insert(canon.to_string(), list);
411        }
412    }
413    let mut global: Vec<String> = Vec::new();
414    for raw in cli_ext.unwrap_or(&[]) {
415        match raw.split_once('=') {
416            Some((name, exts)) => {
417                let canon = lang::require_canonical(name.trim(), "--ext")?;
418                per_lang.insert(canon.to_string(), split_exts(exts));
419            }
420            None => global.extend(split_exts(raw).into_iter().map(|e| e.to_ascii_lowercase())),
421        }
422    }
423    Ok((per_lang, global))
424}
425
426/// Split a comma-separated extension list, trimming blanks and empties.
427fn split_exts(s: &str) -> Vec<String> {
428    s.split(',')
429        .map(|e| e.trim().to_string())
430        .filter(|e| !e.is_empty())
431        .collect()
432}
433
434/// Read a file and analyze it with the language matching its extension,
435/// reporting (but not failing on) read errors. A file whose extension no active
436/// language claims is skipped silently (it was only collected via `--ext`).
437///
438/// With `want_sig`, also produce the file's cache signature, hashed from the
439/// bytes already in memory. The mtime is stat'ed *before* the read: if the
440/// file changes in between, the stored mtime undershoots the analyzed content,
441/// and the next run's hash check catches it — the unsafe direction (a fresher
442/// mtime masking older content) can't happen.
443fn read_and_analyze(
444    dispatch: &HashMap<String, &'static lang::Language>,
445    path: &Path,
446    want_sig: bool,
447) -> Option<(FileReport, Option<cache::Sig>)> {
448    let language = lang_for(dispatch, path)?;
449    let mtime = if want_sig {
450        cache::mtime_ns(path)
451    } else {
452        None
453    };
454    match std::fs::read_to_string(path) {
455        Ok(src) => {
456            let sig = mtime.map(|m| cache::sig_for(src.as_bytes(), m));
457            Some(((language.analyze)(path, &src), sig))
458        }
459        Err(e) => {
460            eprintln!("cccc: cannot read {}: {e}", path.display());
461            None
462        }
463    }
464}
465
466/// The active language claiming `path`'s extension, if any does.
467fn lang_for(
468    dispatch: &HashMap<String, &'static lang::Language>,
469    path: &Path,
470) -> Option<&'static lang::Language> {
471    path.extension()
472        .and_then(|e| e.to_str())
473        .and_then(|e| dispatch.get(&e.to_ascii_lowercase()))
474        .copied()
475}
476
477/// The cache hit for `path` — or `path` itself, as a miss to analyze.
478fn check_cached<'a>(
479    cache: &cache::Cache,
480    dispatch: &HashMap<String, &'static lang::Language>,
481    path: &'a std::path::PathBuf,
482    git: Option<&cache::LazyGitIndex>,
483) -> Result<cache::Hit, &'a std::path::PathBuf> {
484    match lang_for(dispatch, path).and_then(|l| cache.lookup(path, l.name, git)) {
485        Some(hit) => Ok(hit),
486        None => Err(path),
487    }
488}
489
490/// True if any function (at any depth) exceeds either threshold.
491fn exceeds(fns: &[FunctionReport], max_cog: Option<u32>, max_cyc: Option<u32>) -> bool {
492    fns.iter().any(|f| {
493        max_cog.is_some_and(|m| f.cognitive > m)
494            || max_cyc.is_some_and(|m| f.cyclomatic > m)
495            || exceeds(&f.children, max_cog, max_cyc)
496    })
497}
498
499/// Keep functions whose own complexity meets `min`, or that have a kept
500/// descendant.
501fn filter_min(fns: Vec<FunctionReport>, min: u32) -> Vec<FunctionReport> {
502    fns.into_iter()
503        .filter_map(|mut f| {
504            f.children = filter_min(std::mem::take(&mut f.children), min);
505            let keep = f.cognitive >= min || f.cyclomatic >= min || !f.children.is_empty();
506            if keep { Some(f) } else { None }
507        })
508        .collect()
509}