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