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