1mod cli;
21mod output;
22mod walk;
23
24use std::path::Path;
25
26use clap::{CommandFactory, FromArgMatches};
27use rayon::prelude::*;
28
29use cccc_core::report::{self, FileReport, FunctionReport, Metric, Report};
30use cli::Cli;
31
32const PARALLEL_THRESHOLD: usize = 16;
34
35pub type AnalyzeFn = fn(&Path, &str) -> FileReport;
38
39pub fn run(
47 bin_name: &'static str,
48 version: &'static str,
49 analyze: AnalyzeFn,
50 default_exts: &[&str],
51) -> i32 {
52 let command = Cli::command()
53 .name(bin_name)
54 .bin_name(bin_name)
55 .version(version);
56 let cli = match Cli::from_arg_matches(&command.get_matches()) {
57 Ok(cli) => cli,
58 Err(e) => e.exit(),
59 };
60
61 let mut any_missing = false;
65 for path in cli.paths.iter().filter(|p| !p.exists()) {
66 eprintln!("cccc: path does not exist: {}", path.display());
67 any_missing = true;
68 }
69 if any_missing {
70 return 2;
71 }
72
73 let exts: Vec<String> = match &cli.ext {
74 Some(e) => e.iter().map(|s| s.trim().to_string()).collect(),
75 None => default_exts.iter().map(|s| s.to_string()).collect(),
76 };
77
78 let files = walk::collect_files(&cli.paths, &exts, cli.no_ignore);
79 if files.is_empty() {
80 eprintln!("cccc: no matching files found");
81 return 0;
82 }
83
84 let jobs = cli.jobs.map(|j| j as usize).unwrap_or_else(|| {
87 std::thread::available_parallelism()
88 .map(|n| n.get())
89 .unwrap_or(1)
90 });
91
92 let mut reports: Vec<FileReport> = if jobs <= 1 || files.len() <= PARALLEL_THRESHOLD {
95 files
96 .iter()
97 .filter_map(|p| read_and_analyze(analyze, p))
98 .collect()
99 } else {
100 let pool = match rayon::ThreadPoolBuilder::new().num_threads(jobs).build() {
101 Ok(pool) => pool,
102 Err(e) => {
103 eprintln!("cccc: failed to start thread pool: {e}");
104 return 2;
105 }
106 };
107 pool.install(|| {
108 files
109 .par_iter()
110 .filter_map(|p| read_and_analyze(analyze, p))
111 .collect()
112 })
113 };
114
115 reports.sort_by(|a, b| a.path.cmp(&b.path));
116
117 let fail = (cli.max_cognitive.is_some() || cli.max_cyclomatic.is_some())
120 && reports
121 .iter()
122 .any(|r| exceeds(&r.functions, cli.max_cognitive, cli.max_cyclomatic));
123
124 let summary = report::compute_summary(&reports);
127
128 let top_request = match (cli.top_cognitive, cli.top_cyclomatic) {
131 (Some(n), _) => Some((Metric::Cognitive, n)),
132 (_, Some(n)) => Some((Metric::Cyclomatic, n)),
133 (None, None) => None,
134 };
135 if let Some((metric, n)) = top_request {
136 let top = report::build_top_report(&reports, summary, metric, n);
137 if cli.table {
138 output::print_top_table(&top);
139 } else {
140 output::print_json(&top);
141 }
142 return i32::from(fail);
143 }
144
145 if let Some(min) = cli.min {
146 for r in &mut reports {
147 r.functions = filter_min(std::mem::take(&mut r.functions), min);
148 }
149 }
150
151 let report = Report {
152 files: reports,
153 summary,
154 };
155
156 if cli.table {
157 output::print_table(&report);
158 } else {
159 output::print_json(&report);
160 }
161
162 i32::from(fail)
163}
164
165fn read_and_analyze(analyze: AnalyzeFn, path: &Path) -> Option<FileReport> {
167 match std::fs::read_to_string(path) {
168 Ok(src) => Some(analyze(path, &src)),
169 Err(e) => {
170 eprintln!("cccc: cannot read {}: {e}", path.display());
171 None
172 }
173 }
174}
175
176fn exceeds(fns: &[FunctionReport], max_cog: Option<u32>, max_cyc: Option<u32>) -> bool {
178 fns.iter().any(|f| {
179 max_cog.is_some_and(|m| f.cognitive > m)
180 || max_cyc.is_some_and(|m| f.cyclomatic > m)
181 || exceeds(&f.children, max_cog, max_cyc)
182 })
183}
184
185fn filter_min(fns: Vec<FunctionReport>, min: u32) -> Vec<FunctionReport> {
188 fns.into_iter()
189 .filter_map(|mut f| {
190 f.children = filter_min(std::mem::take(&mut f.children), min);
191 let keep = f.cognitive >= min || f.cyclomatic >= min || !f.children.is_empty();
192 if keep { Some(f) } else { None }
193 })
194 .collect()
195}