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 exclude = match walk::build_exclude_set(&cli.exclude) {
81 Ok(set) => set,
82 Err(e) => {
83 eprintln!("cccc: invalid --exclude pattern: {e}");
84 return 2;
85 }
86 };
87
88 let files = walk::collect_files(&cli.paths, &exts, cli.no_ignore, exclude.as_ref());
89 if files.is_empty() {
90 eprintln!("cccc: no matching files found");
91 return 0;
92 }
93
94 let jobs = cli.jobs.map(|j| j as usize).unwrap_or_else(|| {
97 std::thread::available_parallelism()
98 .map(|n| n.get())
99 .unwrap_or(1)
100 });
101
102 let mut reports: Vec<FileReport> = if jobs <= 1 || files.len() <= PARALLEL_THRESHOLD {
105 files
106 .iter()
107 .filter_map(|p| read_and_analyze(analyze, p))
108 .collect()
109 } else {
110 let pool = match rayon::ThreadPoolBuilder::new().num_threads(jobs).build() {
111 Ok(pool) => pool,
112 Err(e) => {
113 eprintln!("cccc: failed to start thread pool: {e}");
114 return 2;
115 }
116 };
117 pool.install(|| {
118 files
119 .par_iter()
120 .filter_map(|p| read_and_analyze(analyze, p))
121 .collect()
122 })
123 };
124
125 reports.sort_by(|a, b| a.path.cmp(&b.path));
126
127 let fail = (cli.max_cognitive.is_some() || cli.max_cyclomatic.is_some())
130 && reports
131 .iter()
132 .any(|r| exceeds(&r.functions, cli.max_cognitive, cli.max_cyclomatic));
133
134 let summary = report::compute_summary(&reports);
137
138 let top_request = match (cli.top_cognitive, cli.top_cyclomatic) {
141 (Some(n), _) => Some((Metric::Cognitive, n)),
142 (_, Some(n)) => Some((Metric::Cyclomatic, n)),
143 (None, None) => None,
144 };
145 if let Some((metric, n)) = top_request {
146 let top = report::build_top_report(&reports, summary, metric, n);
147 if cli.table {
148 output::print_top_table(&top);
149 } else {
150 output::print_json(&top);
151 }
152 return i32::from(fail);
153 }
154
155 if let Some(min) = cli.min {
156 for r in &mut reports {
157 r.functions = filter_min(std::mem::take(&mut r.functions), min);
158 }
159 }
160
161 let report = Report {
162 files: reports,
163 summary,
164 };
165
166 if cli.table {
167 output::print_table(&report);
168 } else {
169 output::print_json(&report);
170 }
171
172 i32::from(fail)
173}
174
175fn read_and_analyze(analyze: AnalyzeFn, path: &Path) -> Option<FileReport> {
177 match std::fs::read_to_string(path) {
178 Ok(src) => Some(analyze(path, &src)),
179 Err(e) => {
180 eprintln!("cccc: cannot read {}: {e}", path.display());
181 None
182 }
183 }
184}
185
186fn exceeds(fns: &[FunctionReport], max_cog: Option<u32>, max_cyc: Option<u32>) -> bool {
188 fns.iter().any(|f| {
189 max_cog.is_some_and(|m| f.cognitive > m)
190 || max_cyc.is_some_and(|m| f.cyclomatic > m)
191 || exceeds(&f.children, max_cog, max_cyc)
192 })
193}
194
195fn filter_min(fns: Vec<FunctionReport>, min: u32) -> Vec<FunctionReport> {
198 fns.into_iter()
199 .filter_map(|mut f| {
200 f.children = filter_min(std::mem::take(&mut f.children), min);
201 let keep = f.cognitive >= min || f.cyclomatic >= min || !f.children.is_empty();
202 if keep { Some(f) } else { None }
203 })
204 .collect()
205}