mod cli;
mod output;
mod walk;
use std::path::Path;
use clap::{CommandFactory, FromArgMatches};
use rayon::prelude::*;
use cccc_core::report::{self, FileReport, FunctionReport, Metric, Report};
use cli::Cli;
const PARALLEL_THRESHOLD: usize = 16;
pub type AnalyzeFn = fn(&Path, &str) -> FileReport;
pub fn run(
bin_name: &'static str,
version: &'static str,
analyze: AnalyzeFn,
default_exts: &[&str],
) -> i32 {
let command = Cli::command()
.name(bin_name)
.bin_name(bin_name)
.version(version);
let cli = match Cli::from_arg_matches(&command.get_matches()) {
Ok(cli) => cli,
Err(e) => e.exit(),
};
let mut any_missing = false;
for path in cli.paths.iter().filter(|p| !p.exists()) {
eprintln!("cccc: path does not exist: {}", path.display());
any_missing = true;
}
if any_missing {
return 2;
}
let exts: Vec<String> = match &cli.ext {
Some(e) => e.iter().map(|s| s.trim().to_string()).collect(),
None => default_exts.iter().map(|s| s.to_string()).collect(),
};
let exclude = match walk::build_exclude_set(&cli.exclude) {
Ok(set) => set,
Err(e) => {
eprintln!("cccc: invalid --exclude pattern: {e}");
return 2;
}
};
let files = walk::collect_files(&cli.paths, &exts, cli.no_ignore, exclude.as_ref());
if files.is_empty() {
eprintln!("cccc: no matching files found");
return 0;
}
let jobs = cli.jobs.map(|j| j as usize).unwrap_or_else(|| {
std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1)
});
let mut reports: Vec<FileReport> = if jobs <= 1 || files.len() <= PARALLEL_THRESHOLD {
files
.iter()
.filter_map(|p| read_and_analyze(analyze, p))
.collect()
} else {
let pool = match rayon::ThreadPoolBuilder::new().num_threads(jobs).build() {
Ok(pool) => pool,
Err(e) => {
eprintln!("cccc: failed to start thread pool: {e}");
return 2;
}
};
pool.install(|| {
files
.par_iter()
.filter_map(|p| read_and_analyze(analyze, p))
.collect()
})
};
reports.sort_by(|a, b| a.path.cmp(&b.path));
let fail = (cli.max_cognitive.is_some() || cli.max_cyclomatic.is_some())
&& reports
.iter()
.any(|r| exceeds(&r.functions, cli.max_cognitive, cli.max_cyclomatic));
let summary = report::compute_summary(&reports);
let top_request = match (cli.top_cognitive, cli.top_cyclomatic) {
(Some(n), _) => Some((Metric::Cognitive, n)),
(_, Some(n)) => Some((Metric::Cyclomatic, n)),
(None, None) => None,
};
if let Some((metric, n)) = top_request {
let top = report::build_top_report(&reports, summary, metric, n);
if cli.table {
output::print_top_table(&top);
} else {
output::print_json(&top);
}
return i32::from(fail);
}
if let Some(min) = cli.min {
for r in &mut reports {
r.functions = filter_min(std::mem::take(&mut r.functions), min);
}
}
let report = Report {
files: reports,
summary,
};
if cli.table {
output::print_table(&report);
} else {
output::print_json(&report);
}
i32::from(fail)
}
fn read_and_analyze(analyze: AnalyzeFn, path: &Path) -> Option<FileReport> {
match std::fs::read_to_string(path) {
Ok(src) => Some(analyze(path, &src)),
Err(e) => {
eprintln!("cccc: cannot read {}: {e}", path.display());
None
}
}
}
fn exceeds(fns: &[FunctionReport], max_cog: Option<u32>, max_cyc: Option<u32>) -> bool {
fns.iter().any(|f| {
max_cog.is_some_and(|m| f.cognitive > m)
|| max_cyc.is_some_and(|m| f.cyclomatic > m)
|| exceeds(&f.children, max_cog, max_cyc)
})
}
fn filter_min(fns: Vec<FunctionReport>, min: u32) -> Vec<FunctionReport> {
fns.into_iter()
.filter_map(|mut f| {
f.children = filter_min(std::mem::take(&mut f.children), min);
let keep = f.cognitive >= min || f.cyclomatic >= min || !f.children.is_empty();
if keep { Some(f) } else { None }
})
.collect()
}