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
51pub fn run() -> i32 {
53 let command = Cli::command()
54 .name("cccc")
55 .bin_name("cccc")
56 .version(env!("CARGO_PKG_VERSION"));
57 let matches = command.get_matches();
58 let cli = match Cli::from_arg_matches(&matches) {
59 Ok(cli) => cli,
60 Err(e) => e.exit(),
61 };
62
63 let config = match Config::resolve(cli.config.as_deref(), cli.no_config) {
66 Ok(config) => config,
67 Err(e) => {
68 eprintln!("cccc: {e}");
69 return 2;
70 }
71 };
72
73 let was_set = |id: &str| matches.value_source(id) == Some(ValueSource::CommandLine);
77 let table = if was_set("table") {
78 cli.table
79 } else {
80 config.table.unwrap_or(false)
81 };
82 let no_ignore = if was_set("no_ignore") {
83 cli.no_ignore
84 } else {
85 config.no_ignore.unwrap_or(false)
86 };
87 let exclude_patterns = if was_set("exclude") {
88 cli.exclude.clone()
89 } else {
90 config.exclude.clone().unwrap_or_default()
91 };
92 let pretty = if was_set("pretty") {
93 cli.pretty
94 } else {
95 config.pretty.unwrap_or(false)
96 };
97 let cache_enabled = if cli.no_cache {
102 false
103 } else {
104 cli.cache || cli.cache_file.is_some() || config.cache.unwrap_or(false)
105 };
106 let cache_path: Option<std::path::PathBuf> = cache_enabled.then(|| {
107 cli.cache_file
108 .clone()
109 .or_else(|| config.cache_file.clone())
110 .unwrap_or_else(|| {
111 config
112 .source_dir
113 .as_deref()
114 .unwrap_or(Path::new(""))
115 .join(".cccc.cache")
116 })
117 });
118 if cli.print_cache_file {
122 if let Some(path) = &cache_path {
123 println!("{}", path.display());
124 }
125 return 0;
126 }
127
128 let max_cognitive = cli.max_cognitive.or(config.max_cognitive);
129 let max_cyclomatic = cli.max_cyclomatic.or(config.max_cyclomatic);
130 let min = cli.min.or(config.min);
131 let jobs_opt = cli.jobs.or(config.jobs);
132 let lang_filter = cli.lang.clone().or_else(|| config.languages.clone());
133 let exclude_lang_filter = cli
134 .exclude_lang
135 .clone()
136 .or_else(|| config.exclude_languages.clone());
137 let (per_lang_ext, global_ext) = match resolve_ext(config.ext.clone(), cli.ext.as_deref()) {
142 Ok(pair) => pair,
143 Err(e) => {
144 eprintln!("cccc: {e}");
145 return 2;
146 }
147 };
148
149 let mut any_missing = false;
153 for path in cli.paths.iter().filter(|p| !p.exists()) {
154 eprintln!("cccc: path does not exist: {}", path.display());
155 any_missing = true;
156 }
157 if any_missing {
158 return 2;
159 }
160
161 let languages =
164 match lang::resolve_languages(lang_filter.as_deref(), exclude_lang_filter.as_deref()) {
165 Ok(langs) => langs,
166 Err(e) => {
167 eprintln!("cccc: {e}");
168 return 2;
169 }
170 };
171 let dispatch = lang::build_dispatch(&languages, &per_lang_ext);
172
173 let exts: Vec<String> = if global_ext.is_empty() {
177 dispatch.keys().cloned().collect()
178 } else {
179 for ext in &global_ext {
180 if !dispatch.contains_key(ext) {
181 output::warn(&format!(
182 "cccc: warning: no active language analyzes .{ext} files; they will be skipped"
183 ));
184 }
185 }
186 global_ext
187 };
188
189 let exclude = match walk::build_exclude_set(&exclude_patterns) {
192 Ok(set) => set,
193 Err(e) => {
194 eprintln!("cccc: invalid --exclude pattern: {e}");
195 return 2;
196 }
197 };
198
199 let jobs = jobs_opt.map(|j| j as usize).unwrap_or_else(|| {
203 std::thread::available_parallelism()
204 .map(|n| n.get())
205 .unwrap_or(1)
206 });
207
208 let git_index = cache_path.as_ref().filter(|p| p.exists()).map(|_| {
215 let root = match cli.paths.first() {
216 Some(p) if p.is_dir() => p.clone(),
217 Some(p) => p
218 .parent()
219 .filter(|d| !d.as_os_str().is_empty())
220 .unwrap_or(Path::new("."))
221 .to_path_buf(),
222 None => std::path::PathBuf::from("."),
223 };
224 cache::LazyGitIndex::new(root)
225 });
226
227 let files = walk::collect_files(&cli.paths, &exts, no_ignore, exclude.as_ref(), jobs);
228 if files.is_empty() {
229 eprintln!("cccc: no matching files found");
230 return 0;
231 }
232
233 let pool = if jobs <= 1 || files.len() <= PARALLEL_THRESHOLD {
238 None
239 } else {
240 match rayon::ThreadPoolBuilder::new().num_threads(jobs).build() {
241 Ok(pool) => Some(pool),
242 Err(e) => {
243 eprintln!("cccc: failed to start thread pool: {e}");
244 return 2;
245 }
246 }
247 };
248
249 let cache = cache_path.as_deref().and_then(cache::load);
252 let mut sig_refreshed = false;
253 let (cached_entries, to_analyze): (
254 Vec<(FileReport, Option<cache::Sig>)>,
255 Vec<&std::path::PathBuf>,
256 ) = match &cache {
257 Some(c) => {
258 let git = git_index.as_ref();
259 let checked: Vec<Result<cache::Hit, &std::path::PathBuf>> = match &pool {
260 Some(pool) => pool.install(|| {
261 files
262 .par_iter()
263 .map(|p| check_cached(c, &dispatch, p, git))
264 .collect()
265 }),
266 None => files
267 .iter()
268 .map(|p| check_cached(c, &dispatch, p, git))
269 .collect(),
270 };
271 let mut hits = Vec::new();
272 let mut misses = Vec::new();
273 for entry in checked {
274 match entry {
275 Ok(hit) => {
276 sig_refreshed |= hit.refreshed;
277 hits.push((hit.report, Some(hit.sig)));
278 }
279 Err(p) => misses.push(p),
280 }
281 }
282 (hits, misses)
283 }
284 None => (Vec::new(), files.iter().collect()),
285 };
286
287 let want_sig = cache_path.is_some();
290 let mut entries: Vec<(FileReport, Option<cache::Sig>)> = match &pool {
291 Some(pool) => pool.install(|| {
292 to_analyze
293 .par_iter()
294 .filter_map(|p| read_and_analyze(&dispatch, p, want_sig))
295 .collect()
296 }),
297 None => to_analyze
298 .iter()
299 .filter_map(|p| read_and_analyze(&dispatch, p, want_sig))
300 .collect(),
301 };
302 entries.extend(cached_entries);
303
304 let cache_is_current = cache.as_ref().is_some_and(|c| {
312 to_analyze.is_empty() && !sig_refreshed && c.entry_count() == entries.len()
313 });
314 if let Some(cache_file) = cache_path.as_deref()
315 && !cache_is_current
316 {
317 let store = || {
318 cache::store(cache_file, &entries, &|p| {
319 lang_for(&dispatch, p).map(|l| l.name)
320 })
321 };
322 match &pool {
323 Some(pool) => pool.install(store),
324 None => store(),
325 }
326 }
327
328 let mut reports: Vec<FileReport> = entries.into_iter().map(|(r, _)| r).collect();
329 reports.sort_by(|a, b| a.path.cmp(&b.path));
330
331 let fail = (max_cognitive.is_some() || max_cyclomatic.is_some())
334 && reports
335 .iter()
336 .any(|r| exceeds(&r.functions, max_cognitive, max_cyclomatic));
337
338 let summary = report::compute_summary(&reports);
341
342 if table && summary.parse_error_count > 0 {
346 output::warn(&format!(
347 "cccc: warning: {} parse error(s) in {} file(s); results for those files may be incomplete:",
348 summary.parse_error_count, summary.parse_error_file_count
349 ));
350 for r in reports.iter().filter(|r| !r.parse_errors.is_empty()) {
351 output::warn(&format!("cccc: {} ({})", r.path, r.parse_errors.len()));
352 }
353 }
354
355 let top_request = match (cli.top_cognitive, cli.top_cyclomatic) {
358 (Some(n), _) => Some((Metric::Cognitive, n)),
359 (_, Some(n)) => Some((Metric::Cyclomatic, n)),
360 (None, None) => None,
361 };
362 if let Some((metric, n)) = top_request {
363 let top = report::build_top_report(&reports, summary, metric, n);
364 if table {
365 output::print_top_table(&top);
366 } else {
367 output::print_json(&top, pretty);
368 }
369 return i32::from(fail);
370 }
371
372 if let Some(min) = min {
373 for r in &mut reports {
374 r.functions = filter_min(std::mem::take(&mut r.functions), min);
375 }
376 }
377
378 let report = Report {
379 files: reports,
380 summary,
381 };
382
383 if table {
384 output::print_table(&report);
385 } else {
386 output::print_json(&report, pretty);
387 }
388
389 i32::from(fail)
390}
391
392type ExtSettings = (BTreeMap<String, Vec<String>>, Vec<String>);
395
396fn resolve_ext(
403 config_ext: Option<BTreeMap<String, Vec<String>>>,
404 cli_ext: Option<&[String]>,
405) -> Result<ExtSettings, String> {
406 let mut per_lang: BTreeMap<String, Vec<String>> = BTreeMap::new();
407 if let Some(cfg) = config_ext {
408 for (key, list) in cfg {
409 let canon = lang::require_canonical(key.trim(), "[ext] config")?;
410 per_lang.insert(canon.to_string(), list);
411 }
412 }
413 let mut global: Vec<String> = Vec::new();
414 for raw in cli_ext.unwrap_or(&[]) {
415 match raw.split_once('=') {
416 Some((name, exts)) => {
417 let canon = lang::require_canonical(name.trim(), "--ext")?;
418 per_lang.insert(canon.to_string(), split_exts(exts));
419 }
420 None => global.extend(split_exts(raw).into_iter().map(|e| e.to_ascii_lowercase())),
421 }
422 }
423 Ok((per_lang, global))
424}
425
426fn split_exts(s: &str) -> Vec<String> {
428 s.split(',')
429 .map(|e| e.trim().to_string())
430 .filter(|e| !e.is_empty())
431 .collect()
432}
433
434fn read_and_analyze(
444 dispatch: &HashMap<String, &'static lang::Language>,
445 path: &Path,
446 want_sig: bool,
447) -> Option<(FileReport, Option<cache::Sig>)> {
448 let language = lang_for(dispatch, path)?;
449 let mtime = if want_sig {
450 cache::mtime_ns(path)
451 } else {
452 None
453 };
454 match std::fs::read_to_string(path) {
455 Ok(src) => {
456 let sig = mtime.map(|m| cache::sig_for(src.as_bytes(), m));
457 Some(((language.analyze)(path, &src), sig))
458 }
459 Err(e) => {
460 eprintln!("cccc: cannot read {}: {e}", path.display());
461 None
462 }
463 }
464}
465
466fn lang_for(
468 dispatch: &HashMap<String, &'static lang::Language>,
469 path: &Path,
470) -> Option<&'static lang::Language> {
471 path.extension()
472 .and_then(|e| e.to_str())
473 .and_then(|e| dispatch.get(&e.to_ascii_lowercase()))
474 .copied()
475}
476
477fn check_cached<'a>(
479 cache: &cache::Cache,
480 dispatch: &HashMap<String, &'static lang::Language>,
481 path: &'a std::path::PathBuf,
482 git: Option<&cache::LazyGitIndex>,
483) -> Result<cache::Hit, &'a std::path::PathBuf> {
484 match lang_for(dispatch, path).and_then(|l| cache.lookup(path, l.name, git)) {
485 Some(hit) => Ok(hit),
486 None => Err(path),
487 }
488}
489
490fn exceeds(fns: &[FunctionReport], max_cog: Option<u32>, max_cyc: Option<u32>) -> bool {
492 fns.iter().any(|f| {
493 max_cog.is_some_and(|m| f.cognitive > m)
494 || max_cyc.is_some_and(|m| f.cyclomatic > m)
495 || exceeds(&f.children, max_cog, max_cyc)
496 })
497}
498
499fn filter_min(fns: Vec<FunctionReport>, min: u32) -> Vec<FunctionReport> {
502 fns.into_iter()
503 .filter_map(|mut f| {
504 f.children = filter_min(std::mem::take(&mut f.children), min);
505 let keep = f.cognitive >= min || f.cyclomatic >= min || !f.children.is_empty();
506 if keep { Some(f) } else { None }
507 })
508 .collect()
509}