mod cache;
mod cli;
pub mod config;
pub mod lang;
mod output;
mod walk;
use std::collections::{BTreeMap, HashMap};
use std::path::Path;
use clap::parser::ValueSource;
use clap::{CommandFactory, FromArgMatches};
use rayon::prelude::*;
use cccc_core::report::{self, FileReport, FunctionReport, Metric, Report};
use cli::Cli;
use config::Config;
const PARALLEL_THRESHOLD: usize = 16;
pub type AnalyzeFn = fn(&Path, &str) -> FileReport;
pub fn run() -> i32 {
let command = Cli::command()
.name("cccc")
.bin_name("cccc")
.version(env!("CARGO_PKG_VERSION"));
let matches = command.get_matches();
let cli = match Cli::from_arg_matches(&matches) {
Ok(cli) => cli,
Err(e) => e.exit(),
};
let config = match Config::resolve(cli.config.as_deref(), cli.no_config) {
Ok(config) => config,
Err(e) => {
eprintln!("cccc: {e}");
return 2;
}
};
let was_set = |id: &str| matches.value_source(id) == Some(ValueSource::CommandLine);
let table = if was_set("table") {
cli.table
} else {
config.table.unwrap_or(false)
};
let no_ignore = if was_set("no_ignore") {
cli.no_ignore
} else {
config.no_ignore.unwrap_or(false)
};
let exclude_patterns = if was_set("exclude") {
cli.exclude.clone()
} else {
config.exclude.clone().unwrap_or_default()
};
let pretty = if was_set("pretty") {
cli.pretty
} else {
config.pretty.unwrap_or(false)
};
let cache_enabled = if cli.no_cache {
false
} else {
cli.cache || cli.cache_file.is_some() || config.cache.unwrap_or(false)
};
let cache_path: Option<std::path::PathBuf> = cache_enabled.then(|| {
cli.cache_file
.clone()
.or_else(|| config.cache_file.clone())
.unwrap_or_else(|| {
config
.source_dir
.as_deref()
.unwrap_or(Path::new(""))
.join(".cccc.cache")
})
});
if cli.print_cache_file {
if let Some(path) = &cache_path {
println!("{}", path.display());
}
return 0;
}
let max_cognitive = cli.max_cognitive.or(config.max_cognitive);
let max_cyclomatic = cli.max_cyclomatic.or(config.max_cyclomatic);
let min = cli.min.or(config.min);
let jobs_opt = cli.jobs.or(config.jobs);
let lang_filter = cli.lang.clone().or_else(|| config.languages.clone());
let exclude_lang_filter = cli
.exclude_lang
.clone()
.or_else(|| config.exclude_languages.clone());
let (per_lang_ext, global_ext) = match resolve_ext(config.ext.clone(), cli.ext.as_deref()) {
Ok(pair) => pair,
Err(e) => {
eprintln!("cccc: {e}");
return 2;
}
};
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 languages =
match lang::resolve_languages(lang_filter.as_deref(), exclude_lang_filter.as_deref()) {
Ok(langs) => langs,
Err(e) => {
eprintln!("cccc: {e}");
return 2;
}
};
let dispatch = lang::build_dispatch(&languages, &per_lang_ext);
let exts: Vec<String> = if global_ext.is_empty() {
dispatch.keys().cloned().collect()
} else {
for ext in &global_ext {
if !dispatch.contains_key(ext) {
output::warn(&format!(
"cccc: warning: no active language analyzes .{ext} files; they will be skipped"
));
}
}
global_ext
};
let exclude = match walk::build_exclude_set(&exclude_patterns) {
Ok(set) => set,
Err(e) => {
eprintln!("cccc: invalid --exclude pattern: {e}");
return 2;
}
};
let jobs = jobs_opt.map(|j| j as usize).unwrap_or_else(|| {
std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1)
});
let git_index = cache_path.as_ref().filter(|p| p.exists()).map(|_| {
let root = match cli.paths.first() {
Some(p) if p.is_dir() => p.clone(),
Some(p) => p
.parent()
.filter(|d| !d.as_os_str().is_empty())
.unwrap_or(Path::new("."))
.to_path_buf(),
None => std::path::PathBuf::from("."),
};
cache::LazyGitIndex::new(root)
});
let files = walk::collect_files(&cli.paths, &exts, no_ignore, exclude.as_ref(), jobs);
if files.is_empty() {
eprintln!("cccc: no matching files found");
return 0;
}
let pool = if jobs <= 1 || files.len() <= PARALLEL_THRESHOLD {
None
} else {
match rayon::ThreadPoolBuilder::new().num_threads(jobs).build() {
Ok(pool) => Some(pool),
Err(e) => {
eprintln!("cccc: failed to start thread pool: {e}");
return 2;
}
}
};
let cache = cache_path.as_deref().and_then(cache::load);
let mut sig_refreshed = false;
let (cached_entries, to_analyze): (
Vec<(FileReport, Option<cache::Sig>)>,
Vec<&std::path::PathBuf>,
) = match &cache {
Some(c) => {
let git = git_index.as_ref();
let checked: Vec<Result<cache::Hit, &std::path::PathBuf>> = match &pool {
Some(pool) => pool.install(|| {
files
.par_iter()
.map(|p| check_cached(c, &dispatch, p, git))
.collect()
}),
None => files
.iter()
.map(|p| check_cached(c, &dispatch, p, git))
.collect(),
};
let mut hits = Vec::new();
let mut misses = Vec::new();
for entry in checked {
match entry {
Ok(hit) => {
sig_refreshed |= hit.refreshed;
hits.push((hit.report, Some(hit.sig)));
}
Err(p) => misses.push(p),
}
}
(hits, misses)
}
None => (Vec::new(), files.iter().collect()),
};
let want_sig = cache_path.is_some();
let mut entries: Vec<(FileReport, Option<cache::Sig>)> = match &pool {
Some(pool) => pool.install(|| {
to_analyze
.par_iter()
.filter_map(|p| read_and_analyze(&dispatch, p, want_sig))
.collect()
}),
None => to_analyze
.iter()
.filter_map(|p| read_and_analyze(&dispatch, p, want_sig))
.collect(),
};
entries.extend(cached_entries);
let cache_is_current = cache.as_ref().is_some_and(|c| {
to_analyze.is_empty() && !sig_refreshed && c.entry_count() == entries.len()
});
if let Some(cache_file) = cache_path.as_deref()
&& !cache_is_current
{
let store = || {
cache::store(cache_file, &entries, &|p| {
lang_for(&dispatch, p).map(|l| l.name)
})
};
match &pool {
Some(pool) => pool.install(store),
None => store(),
}
}
let mut reports: Vec<FileReport> = entries.into_iter().map(|(r, _)| r).collect();
reports.sort_by(|a, b| a.path.cmp(&b.path));
let fail = (max_cognitive.is_some() || max_cyclomatic.is_some())
&& reports
.iter()
.any(|r| exceeds(&r.functions, max_cognitive, max_cyclomatic));
let summary = report::compute_summary(&reports);
if table && summary.parse_error_count > 0 {
output::warn(&format!(
"cccc: warning: {} parse error(s) in {} file(s); results for those files may be incomplete:",
summary.parse_error_count, summary.parse_error_file_count
));
for r in reports.iter().filter(|r| !r.parse_errors.is_empty()) {
output::warn(&format!("cccc: {} ({})", r.path, r.parse_errors.len()));
}
}
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 table {
output::print_top_table(&top);
} else {
output::print_json(&top, pretty);
}
return i32::from(fail);
}
if let Some(min) = min {
for r in &mut reports {
r.functions = filter_min(std::mem::take(&mut r.functions), min);
}
}
let report = Report {
files: reports,
summary,
};
if table {
output::print_table(&report);
} else {
output::print_json(&report, pretty);
}
i32::from(fail)
}
type ExtSettings = (BTreeMap<String, Vec<String>>, Vec<String>);
fn resolve_ext(
config_ext: Option<BTreeMap<String, Vec<String>>>,
cli_ext: Option<&[String]>,
) -> Result<ExtSettings, String> {
let mut per_lang: BTreeMap<String, Vec<String>> = BTreeMap::new();
if let Some(cfg) = config_ext {
for (key, list) in cfg {
let canon = lang::require_canonical(key.trim(), "[ext] config")?;
per_lang.insert(canon.to_string(), list);
}
}
let mut global: Vec<String> = Vec::new();
for raw in cli_ext.unwrap_or(&[]) {
match raw.split_once('=') {
Some((name, exts)) => {
let canon = lang::require_canonical(name.trim(), "--ext")?;
per_lang.insert(canon.to_string(), split_exts(exts));
}
None => global.extend(split_exts(raw).into_iter().map(|e| e.to_ascii_lowercase())),
}
}
Ok((per_lang, global))
}
fn split_exts(s: &str) -> Vec<String> {
s.split(',')
.map(|e| e.trim().to_string())
.filter(|e| !e.is_empty())
.collect()
}
fn read_and_analyze(
dispatch: &HashMap<String, &'static lang::Language>,
path: &Path,
want_sig: bool,
) -> Option<(FileReport, Option<cache::Sig>)> {
let language = lang_for(dispatch, path)?;
let mtime = if want_sig {
cache::mtime_ns(path)
} else {
None
};
match std::fs::read_to_string(path) {
Ok(src) => {
let sig = mtime.map(|m| cache::sig_for(src.as_bytes(), m));
Some(((language.analyze)(path, &src), sig))
}
Err(e) => {
eprintln!("cccc: cannot read {}: {e}", path.display());
None
}
}
}
fn lang_for(
dispatch: &HashMap<String, &'static lang::Language>,
path: &Path,
) -> Option<&'static lang::Language> {
path.extension()
.and_then(|e| e.to_str())
.and_then(|e| dispatch.get(&e.to_ascii_lowercase()))
.copied()
}
fn check_cached<'a>(
cache: &cache::Cache,
dispatch: &HashMap<String, &'static lang::Language>,
path: &'a std::path::PathBuf,
git: Option<&cache::LazyGitIndex>,
) -> Result<cache::Hit, &'a std::path::PathBuf> {
match lang_for(dispatch, path).and_then(|l| cache.lookup(path, l.name, git)) {
Some(hit) => Ok(hit),
None => Err(path),
}
}
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()
}