Skip to main content

cccc_cli/
lib.rs

1//! Shared CLI machinery for `cccc` front-ends.
2//!
3//! Everything common to every language front-end lives here: argument parsing,
4//! file discovery, parallel analysis, the threshold/`--min`/`--top` logic, and
5//! output rendering. A language-specific binary (e.g. `cccc-es`) supplies only
6//! two things via [`run`]: how to analyze one file into a [`FileReport`], and the
7//! default set of file extensions. This keeps the per-language binaries tiny and
8//! the behaviour identical across languages.
9//!
10//! ## Exit codes
11//!
12//! [`run`] returns a process exit code with a consistent meaning:
13//! - `0` — success (including an existing input path that simply contains no
14//!   matching files: "nothing to analyze" is not an error).
15//! - `1` — a `--max-cognitive`/`--max-cyclomatic` threshold was exceeded
16//!   (the CI gate).
17//! - `2` — unable to proceed: a given path does not exist, or the worker pool
18//!   could not be created. (clap's own usage errors also exit `2`.)
19
20mod cli;
21mod output;
22mod walk;
23
24use std::path::Path;
25
26use clap::{CommandFactory, FromArgMatches};
27use rayon::prelude::*;
28
29use cccc_core::report::{self, FileReport, FunctionReport, Metric, Report};
30use cli::Cli;
31
32/// Below this many files, sequential analysis beats paying for a rayon pool.
33const PARALLEL_THRESHOLD: usize = 16;
34
35/// Analyze one file's source into a [`FileReport`]. Implemented per language by
36/// the relevant adapter (e.g. `cccc_typescript::analyze_source`).
37pub type AnalyzeFn = fn(&Path, &str) -> FileReport;
38
39/// Run the CLI end to end and return a process exit code.
40///
41/// `bin_name` is the front-end binary's name (e.g. `"cccc-es"`); it sets the
42/// program name shown in `--help`/`--version` and the version string, so the
43/// shared `Cli` definition doesn't bake in any one front-end's identity.
44/// `analyze` lowers+scores a single file; `default_exts` is the extension set
45/// used when `--ext` is not given (e.g. `&["ts", "tsx", "js", ...]`).
46pub fn run(
47    bin_name: &'static str,
48    version: &'static str,
49    analyze: AnalyzeFn,
50    default_exts: &[&str],
51) -> i32 {
52    let command = Cli::command()
53        .name(bin_name)
54        .bin_name(bin_name)
55        .version(version);
56    let cli = match Cli::from_arg_matches(&command.get_matches()) {
57        Ok(cli) => cli,
58        Err(e) => e.exit(),
59    };
60
61    // A path that doesn't exist is almost always a typo, so fail loudly rather
62    // than silently reporting "no files". (A path that exists but contains no
63    // matching files is still treated as an empty, successful run below.)
64    let mut any_missing = false;
65    for path in cli.paths.iter().filter(|p| !p.exists()) {
66        eprintln!("cccc: path does not exist: {}", path.display());
67        any_missing = true;
68    }
69    if any_missing {
70        return 2;
71    }
72
73    let exts: Vec<String> = match &cli.ext {
74        Some(e) => e.iter().map(|s| s.trim().to_string()).collect(),
75        None => default_exts.iter().map(|s| s.to_string()).collect(),
76    };
77
78    let files = walk::collect_files(&cli.paths, &exts, cli.no_ignore);
79    if files.is_empty() {
80        eprintln!("cccc: no matching files found");
81        return 0;
82    }
83
84    // `--jobs` caps the worker count; without it we fall back to the number of
85    // logical CPUs (1 if that can't be determined).
86    let jobs = cli.jobs.map(|j| j as usize).unwrap_or_else(|| {
87        std::thread::available_parallelism()
88            .map(|n| n.get())
89            .unwrap_or(1)
90    });
91
92    // For a handful of files, spinning up a rayon pool costs more than it saves,
93    // so analyze sequentially. Above the threshold, fan out across `jobs` workers.
94    let mut reports: Vec<FileReport> = if jobs <= 1 || files.len() <= PARALLEL_THRESHOLD {
95        files
96            .iter()
97            .filter_map(|p| read_and_analyze(analyze, p))
98            .collect()
99    } else {
100        let pool = match rayon::ThreadPoolBuilder::new().num_threads(jobs).build() {
101            Ok(pool) => pool,
102            Err(e) => {
103                eprintln!("cccc: failed to start thread pool: {e}");
104                return 2;
105            }
106        };
107        pool.install(|| {
108            files
109                .par_iter()
110                .filter_map(|p| read_and_analyze(analyze, p))
111                .collect()
112        })
113    };
114
115    reports.sort_by(|a, b| a.path.cmp(&b.path));
116
117    // Determine exit status before any `--min` filtering, so display options do
118    // not change pass/fail behaviour.
119    let fail = (cli.max_cognitive.is_some() || cli.max_cyclomatic.is_some())
120        && reports
121            .iter()
122            .any(|r| exceeds(&r.functions, cli.max_cognitive, cli.max_cyclomatic));
123
124    // Compute the summary over the full population, before `--min`/`--top` change
125    // what is displayed, so the distribution always reflects all code.
126    let summary = report::compute_summary(&reports);
127
128    // `--top-*` is a distinct, flat ranking view that replaces the per-file
129    // output. The two top flags are mutually exclusive (enforced by clap).
130    let top_request = match (cli.top_cognitive, cli.top_cyclomatic) {
131        (Some(n), _) => Some((Metric::Cognitive, n)),
132        (_, Some(n)) => Some((Metric::Cyclomatic, n)),
133        (None, None) => None,
134    };
135    if let Some((metric, n)) = top_request {
136        let top = report::build_top_report(&reports, summary, metric, n);
137        if cli.table {
138            output::print_top_table(&top);
139        } else {
140            output::print_json(&top);
141        }
142        return i32::from(fail);
143    }
144
145    if let Some(min) = cli.min {
146        for r in &mut reports {
147            r.functions = filter_min(std::mem::take(&mut r.functions), min);
148        }
149    }
150
151    let report = Report {
152        files: reports,
153        summary,
154    };
155
156    if cli.table {
157        output::print_table(&report);
158    } else {
159        output::print_json(&report);
160    }
161
162    i32::from(fail)
163}
164
165/// Read a file and analyze it, reporting (but not failing on) read errors.
166fn read_and_analyze(analyze: AnalyzeFn, path: &Path) -> Option<FileReport> {
167    match std::fs::read_to_string(path) {
168        Ok(src) => Some(analyze(path, &src)),
169        Err(e) => {
170            eprintln!("cccc: cannot read {}: {e}", path.display());
171            None
172        }
173    }
174}
175
176/// True if any function (at any depth) exceeds either threshold.
177fn exceeds(fns: &[FunctionReport], max_cog: Option<u32>, max_cyc: Option<u32>) -> bool {
178    fns.iter().any(|f| {
179        max_cog.is_some_and(|m| f.cognitive > m)
180            || max_cyc.is_some_and(|m| f.cyclomatic > m)
181            || exceeds(&f.children, max_cog, max_cyc)
182    })
183}
184
185/// Keep functions whose own complexity meets `min`, or that have a kept
186/// descendant.
187fn filter_min(fns: Vec<FunctionReport>, min: u32) -> Vec<FunctionReport> {
188    fns.into_iter()
189        .filter_map(|mut f| {
190            f.children = filter_min(std::mem::take(&mut f.children), min);
191            let keep = f.cognitive >= min || f.cyclomatic >= min || !f.children.is_empty();
192            if keep { Some(f) } else { None }
193        })
194        .collect()
195}