1mod cache;
28mod cli;
29pub mod config;
30pub mod lang;
31mod output;
32mod walk;
33
34use std::collections::{BTreeMap, HashMap};
35use std::path::Path;
36
37use clap::parser::ValueSource;
38use clap::{CommandFactory, FromArgMatches};
39use rayon::prelude::*;
40
41use cccc_core::report::{self, FileReport, FunctionReport, Metric, Report};
42use cli::Cli;
43use config::{Config, Format};
44
45const PARALLEL_THRESHOLD: usize = 16;
47
48pub type AnalyzeFn = fn(&Path, &str) -> FileReport;
51
52const STACK_SIZE: usize = cccc_core::guard::STACK_SIZE + (64 << 20);
61
62pub fn run() -> i32 {
64 std::thread::Builder::new()
65 .name("cccc".into())
66 .stack_size(STACK_SIZE)
67 .spawn(run_on_current_thread)
68 .expect("failed to spawn the main cccc thread")
69 .join()
70 .unwrap_or_else(|panic| std::panic::resume_unwind(panic))
71}
72
73fn run_on_current_thread() -> i32 {
74 let command = Cli::command()
75 .name("cccc")
76 .bin_name("cccc")
77 .version(env!("CARGO_PKG_VERSION"));
78 let matches = command.get_matches();
79 let cli = match Cli::from_arg_matches(&matches) {
80 Ok(cli) => cli,
81 Err(e) => e.exit(),
82 };
83
84 let config = match Config::resolve(cli.config.as_deref(), cli.no_config) {
87 Ok(config) => config,
88 Err(e) => {
89 eprintln!("cccc: {e}");
90 return 2;
91 }
92 };
93
94 let was_set = |id: &str| matches.value_source(id) == Some(ValueSource::CommandLine);
98 if cli.table {
101 output::warn("cccc: warning: --table is deprecated; use --format table");
102 }
103 if config.table.is_some() {
104 output::warn(
105 "cccc: warning: `table` in the config file is deprecated; use `format = \"table\"`",
106 );
107 }
108 let format = if let Some(format) = cli.format {
112 format
113 } else if cli.table {
114 Format::Table
115 } else if let Some(format) = config.format {
116 format
117 } else if config.table.unwrap_or(false) {
118 Format::Table
119 } else {
120 Format::Json
121 };
122 let table = format == Format::Table;
123 let no_ignore = if was_set("no_ignore") {
124 cli.no_ignore
125 } else {
126 config.no_ignore.unwrap_or(false)
127 };
128 let exclude_patterns = if was_set("exclude") {
129 cli.exclude.clone()
130 } else {
131 config.exclude.clone().unwrap_or_default()
132 };
133 let pretty = if was_set("pretty") {
134 cli.pretty
135 } else {
136 config.pretty.unwrap_or(false)
137 };
138 let cache_enabled = if cli.no_cache {
143 false
144 } else {
145 cli.cache || cli.cache_file.is_some() || config.cache.unwrap_or(false)
146 };
147 let cache_path: Option<std::path::PathBuf> = cache_enabled.then(|| {
148 cli.cache_file
149 .clone()
150 .or_else(|| config.cache_file.clone())
151 .unwrap_or_else(|| {
152 config
153 .source_dir
154 .as_deref()
155 .unwrap_or(Path::new(""))
156 .join(".cccc.cache")
157 })
158 });
159 if cli.print_cache_file {
163 if let Some(path) = &cache_path {
164 println!("{}", path.display());
165 }
166 return 0;
167 }
168
169 let max_cognitive = cli.max_cognitive.or(config.max_cognitive);
170 let max_cyclomatic = cli.max_cyclomatic.or(config.max_cyclomatic);
171 let min = cli.min.or(config.min);
172 let violations = if was_set("violations") {
173 cli.violations
174 } else {
175 config.violations.unwrap_or(false)
176 };
177 if violations {
182 if max_cognitive.is_none() && max_cyclomatic.is_none() {
183 eprintln!(
184 "cccc: --violations needs --max-cognitive and/or --max-cyclomatic (or `max-cognitive` / `max-cyclomatic` in cccc.toml)"
185 );
186 return 2;
187 }
188 for flag in ["min", "top_cognitive", "top_cyclomatic"] {
189 if was_set(flag) {
190 eprintln!(
191 "cccc: --{} cannot be used with --violations",
192 flag.replace('_', "-")
193 );
194 return 2;
195 }
196 }
197 }
198 let min = if violations { None } else { min };
199 let jobs_opt = cli.jobs.or(config.jobs);
200 let lang_filter = cli.lang.clone().or_else(|| config.languages.clone());
201 let exclude_lang_filter = cli
202 .exclude_lang
203 .clone()
204 .or_else(|| config.exclude_languages.clone());
205 let (per_lang_ext, global_ext) = match resolve_ext(config.ext.clone(), cli.ext.as_deref()) {
210 Ok(pair) => pair,
211 Err(e) => {
212 eprintln!("cccc: {e}");
213 return 2;
214 }
215 };
216
217 let mut any_missing = false;
221 for path in cli.paths.iter().filter(|p| !p.exists()) {
222 eprintln!("cccc: path does not exist: {}", path.display());
223 any_missing = true;
224 }
225 if any_missing {
226 return 2;
227 }
228
229 let languages =
232 match lang::resolve_languages(lang_filter.as_deref(), exclude_lang_filter.as_deref()) {
233 Ok(langs) => langs,
234 Err(e) => {
235 eprintln!("cccc: {e}");
236 return 2;
237 }
238 };
239 let dispatch = lang::build_dispatch(&languages, &per_lang_ext);
240
241 let exts: Vec<String> = if global_ext.is_empty() {
245 dispatch.keys().cloned().collect()
246 } else {
247 for ext in &global_ext {
248 if !dispatch.contains_key(ext) {
249 output::warn(&format!(
250 "cccc: warning: no active language analyzes .{ext} files; they will be skipped"
251 ));
252 }
253 }
254 global_ext
255 };
256
257 let exclude = match walk::build_exclude_set(&exclude_patterns) {
260 Ok(set) => set,
261 Err(e) => {
262 eprintln!("cccc: invalid --exclude pattern: {e}");
263 return 2;
264 }
265 };
266
267 let jobs = jobs_opt.map(|j| j as usize).unwrap_or_else(|| {
271 std::thread::available_parallelism()
272 .map(|n| n.get())
273 .unwrap_or(1)
274 });
275
276 let git_index = cache_path.as_ref().filter(|p| p.exists()).map(|_| {
283 let root = match cli.paths.first() {
284 Some(p) if p.is_dir() => p.clone(),
285 Some(p) => p
286 .parent()
287 .filter(|d| !d.as_os_str().is_empty())
288 .unwrap_or(Path::new("."))
289 .to_path_buf(),
290 None => std::path::PathBuf::from("."),
291 };
292 cache::LazyGitIndex::new(root)
293 });
294
295 let files = walk::collect_files(&cli.paths, &exts, no_ignore, exclude.as_ref(), jobs);
296 if files.is_empty() {
297 eprintln!("cccc: no matching files found");
298 return 0;
299 }
300
301 let pool = if jobs <= 1 || files.len() <= PARALLEL_THRESHOLD {
306 None
307 } else {
308 match rayon::ThreadPoolBuilder::new()
309 .num_threads(jobs)
310 .stack_size(STACK_SIZE)
311 .build()
312 {
313 Ok(pool) => Some(pool),
314 Err(e) => {
315 eprintln!("cccc: failed to start thread pool: {e}");
316 return 2;
317 }
318 }
319 };
320
321 let cache = cache_path.as_deref().and_then(cache::load);
324 let mut sig_refreshed = false;
325 let (cached_entries, to_analyze): (
326 Vec<(FileReport, Option<cache::Sig>)>,
327 Vec<&std::path::PathBuf>,
328 ) = match &cache {
329 Some(c) => {
330 let git = git_index.as_ref();
331 let checked: Vec<Result<cache::Hit, &std::path::PathBuf>> = match &pool {
332 Some(pool) => pool.install(|| {
333 files
334 .par_iter()
335 .map(|p| check_cached(c, &dispatch, p, git))
336 .collect()
337 }),
338 None => files
339 .iter()
340 .map(|p| check_cached(c, &dispatch, p, git))
341 .collect(),
342 };
343 let mut hits = Vec::new();
344 let mut misses = Vec::new();
345 for entry in checked {
346 match entry {
347 Ok(hit) => {
348 sig_refreshed |= hit.refreshed;
349 hits.push((hit.report, Some(hit.sig)));
350 }
351 Err(p) => misses.push(p),
352 }
353 }
354 (hits, misses)
355 }
356 None => (Vec::new(), files.iter().collect()),
357 };
358
359 let want_sig = cache_path.is_some();
362 let mut entries: Vec<(FileReport, Option<cache::Sig>)> = match &pool {
363 Some(pool) => pool.install(|| {
364 to_analyze
365 .par_iter()
366 .filter_map(|p| read_and_analyze(&dispatch, p, want_sig))
367 .collect()
368 }),
369 None => to_analyze
370 .iter()
371 .filter_map(|p| read_and_analyze(&dispatch, p, want_sig))
372 .collect(),
373 };
374 entries.extend(cached_entries);
375
376 let cache_is_current = cache.as_ref().is_some_and(|c| {
384 to_analyze.is_empty() && !sig_refreshed && c.entry_count() == entries.len()
385 });
386 if let Some(cache_file) = cache_path.as_deref()
387 && !cache_is_current
388 {
389 let store = |parallel| {
390 cache::store(cache_file, &entries, parallel, &|p| {
391 lang_for(&dispatch, p).map(|l| l.name)
392 })
393 };
394 match &pool {
395 Some(pool) => pool.install(|| store(true)),
396 None => store(false),
397 }
398 }
399
400 let mut reports: Vec<FileReport> = entries.into_iter().map(|(r, _)| r).collect();
401 reports.sort_by(|a, b| a.path.cmp(&b.path));
402
403 let fail = (max_cognitive.is_some() || max_cyclomatic.is_some())
406 && reports
407 .iter()
408 .any(|r| exceeds(&r.functions, max_cognitive, max_cyclomatic));
409
410 let summary = report::compute_summary(&reports);
413
414 if format != Format::Json && summary.parse_error_count > 0 {
418 output::warn(&format!(
419 "cccc: warning: {} parse error(s) in {} file(s); results for those files may be incomplete:",
420 summary.parse_error_count, summary.parse_error_file_count
421 ));
422 for r in reports.iter().filter(|r| !r.parse_errors.is_empty()) {
423 output::warn(&format!("cccc: {} ({})", r.path, r.parse_errors.len()));
424 }
425 }
426
427 let top_request = match (cli.top_cognitive, cli.top_cyclomatic) {
430 (Some(n), _) => Some((Metric::Cognitive, n)),
431 (_, Some(n)) => Some((Metric::Cyclomatic, n)),
432 (None, None) => None,
433 };
434 if let Some((metric, n)) = top_request {
435 let top = report::build_top_report(&reports, summary, metric, n);
436 match format {
437 Format::Json => output::print_json(&top, pretty),
438 Format::Table => output::print_top_table(&top),
439 Format::Simple => output::print_top_simple(&top),
440 }
441 return i32::from(fail);
442 }
443
444 let selected = |f: &FunctionReport| {
447 if violations {
448 over_limit(f, max_cognitive, max_cyclomatic)
449 } else {
450 min.is_none_or(|m| f.cognitive >= m || f.cyclomatic >= m)
451 }
452 };
453 if violations || min.is_some() {
454 for r in &mut reports {
455 r.functions = filter_tree(std::mem::take(&mut r.functions), &selected);
456 }
457 }
458 if violations || (table && min.is_some()) {
465 reports.retain(|r| !r.functions.is_empty());
466 }
467
468 if format == Format::Simple {
469 let limits = violations.then_some((max_cognitive, max_cyclomatic));
472 let (fns, files) = output::print_simple(&reports, &selected, limits);
473 if violations && fns > 0 {
474 eprintln!(
475 "cccc: {fns} function{} over the limits in {files} file{}",
476 if fns == 1 { "" } else { "s" },
477 if files == 1 { "" } else { "s" }
478 );
479 }
480 return i32::from(fail);
481 }
482
483 let report = Report {
484 files: reports,
485 summary,
486 };
487
488 if table {
489 output::print_table(&report);
490 } else {
491 output::print_json(&report, pretty);
492 }
493
494 i32::from(fail)
495}
496
497type ExtSettings = (BTreeMap<String, Vec<String>>, Vec<String>);
500
501fn resolve_ext(
508 config_ext: Option<BTreeMap<String, Vec<String>>>,
509 cli_ext: Option<&[String]>,
510) -> Result<ExtSettings, String> {
511 let mut per_lang: BTreeMap<String, Vec<String>> = BTreeMap::new();
512 if let Some(cfg) = config_ext {
513 for (key, list) in cfg {
514 let canon = lang::require_canonical(key.trim(), "[ext] config")?;
515 per_lang.insert(canon.to_string(), list);
516 }
517 }
518 let mut global: Vec<String> = Vec::new();
519 for raw in cli_ext.unwrap_or(&[]) {
520 match raw.split_once('=') {
521 Some((name, exts)) => {
522 let canon = lang::require_canonical(name.trim(), "--ext")?;
523 per_lang.insert(canon.to_string(), split_exts(exts));
524 }
525 None => global.extend(split_exts(raw).into_iter().map(|e| e.to_ascii_lowercase())),
526 }
527 }
528 Ok((per_lang, global))
529}
530
531fn split_exts(s: &str) -> Vec<String> {
533 s.split(',')
534 .map(|e| e.trim().to_string())
535 .filter(|e| !e.is_empty())
536 .collect()
537}
538
539fn read_and_analyze(
549 dispatch: &HashMap<String, &'static lang::Language>,
550 path: &Path,
551 want_sig: bool,
552) -> Option<(FileReport, Option<cache::Sig>)> {
553 let language = lang_for(dispatch, path)?;
554 let mtime = if want_sig {
555 cache::mtime_ns(path)
556 } else {
557 None
558 };
559 match std::fs::read_to_string(path) {
560 Ok(src) => {
561 let sig = mtime.map(|m| cache::sig_for(src.as_bytes(), m));
562 Some(((language.analyze)(path, &src), sig))
563 }
564 Err(e) => {
565 eprintln!("cccc: cannot read {}: {e}", path.display());
566 None
567 }
568 }
569}
570
571fn lang_for(
573 dispatch: &HashMap<String, &'static lang::Language>,
574 path: &Path,
575) -> Option<&'static lang::Language> {
576 path.extension()
577 .and_then(|e| e.to_str())
578 .and_then(|e| dispatch.get(&e.to_ascii_lowercase()))
579 .copied()
580}
581
582fn check_cached<'a>(
584 cache: &cache::Cache,
585 dispatch: &HashMap<String, &'static lang::Language>,
586 path: &'a std::path::PathBuf,
587 git: Option<&cache::LazyGitIndex>,
588) -> Result<cache::Hit, &'a std::path::PathBuf> {
589 match lang_for(dispatch, path).and_then(|l| cache.lookup(path, l.name, git)) {
590 Some(hit) => Ok(hit),
591 None => Err(path),
592 }
593}
594
595fn exceeds(fns: &[FunctionReport], max_cog: Option<u32>, max_cyc: Option<u32>) -> bool {
597 fns.iter()
598 .any(|f| over_limit(f, max_cog, max_cyc) || exceeds(&f.children, max_cog, max_cyc))
599}
600
601fn over_limit(f: &FunctionReport, max_cog: Option<u32>, max_cyc: Option<u32>) -> bool {
603 max_cog.is_some_and(|m| f.cognitive > m) || max_cyc.is_some_and(|m| f.cyclomatic > m)
604}
605
606fn filter_tree(
609 fns: Vec<FunctionReport>,
610 keep: &impl Fn(&FunctionReport) -> bool,
611) -> Vec<FunctionReport> {
612 fns.into_iter()
613 .filter_map(|mut f| {
614 f.children = filter_tree(std::mem::take(&mut f.children), keep);
615 (keep(&f) || !f.children.is_empty()).then_some(f)
616 })
617 .collect()
618}