1mod 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
44const PARALLEL_THRESHOLD: usize = 16;
46
47pub type AnalyzeFn = fn(&Path, &str) -> FileReport;
50
51const STACK_SIZE: usize = cccc_core::guard::STACK_SIZE + (64 << 20);
60
61pub 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 let summary = report::compute_summary(&reports);
365
366 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 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
416type ExtSettings = (BTreeMap<String, Vec<String>>, Vec<String>);
419
420fn 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
450fn 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
458fn 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
490fn 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
501fn 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
514fn 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
523fn 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}