1mod cli;
26pub mod config;
27pub mod lang;
28mod output;
29mod walk;
30
31use std::collections::{BTreeMap, HashMap};
32use std::path::Path;
33
34use clap::parser::ValueSource;
35use clap::{CommandFactory, FromArgMatches};
36use rayon::prelude::*;
37
38use cccc_core::report::{self, FileReport, FunctionReport, Metric, Report};
39use cli::Cli;
40use config::Config;
41
42const PARALLEL_THRESHOLD: usize = 16;
44
45pub type AnalyzeFn = fn(&Path, &str) -> FileReport;
48
49pub fn run() -> i32 {
51 let command = Cli::command()
52 .name("cccc")
53 .bin_name("cccc")
54 .version(env!("CARGO_PKG_VERSION"));
55 let matches = command.get_matches();
56 let cli = match Cli::from_arg_matches(&matches) {
57 Ok(cli) => cli,
58 Err(e) => e.exit(),
59 };
60
61 let config = match Config::resolve(cli.config.as_deref(), cli.no_config) {
64 Ok(config) => config,
65 Err(e) => {
66 eprintln!("cccc: {e}");
67 return 2;
68 }
69 };
70
71 let was_set = |id: &str| matches.value_source(id) == Some(ValueSource::CommandLine);
75 let table = if was_set("table") {
76 cli.table
77 } else {
78 config.table.unwrap_or(false)
79 };
80 let no_ignore = if was_set("no_ignore") {
81 cli.no_ignore
82 } else {
83 config.no_ignore.unwrap_or(false)
84 };
85 let exclude_patterns = if was_set("exclude") {
86 cli.exclude.clone()
87 } else {
88 config.exclude.clone().unwrap_or_default()
89 };
90 let max_cognitive = cli.max_cognitive.or(config.max_cognitive);
91 let max_cyclomatic = cli.max_cyclomatic.or(config.max_cyclomatic);
92 let min = cli.min.or(config.min);
93 let jobs_opt = cli.jobs.or(config.jobs);
94 let lang_filter = cli.lang.clone().or_else(|| config.languages.clone());
95 let exclude_lang_filter = cli
96 .exclude_lang
97 .clone()
98 .or_else(|| config.exclude_languages.clone());
99 let (per_lang_ext, global_ext) = match resolve_ext(config.ext.clone(), cli.ext.as_deref()) {
104 Ok(pair) => pair,
105 Err(e) => {
106 eprintln!("cccc: {e}");
107 return 2;
108 }
109 };
110
111 let mut any_missing = false;
115 for path in cli.paths.iter().filter(|p| !p.exists()) {
116 eprintln!("cccc: path does not exist: {}", path.display());
117 any_missing = true;
118 }
119 if any_missing {
120 return 2;
121 }
122
123 let languages =
126 match lang::resolve_languages(lang_filter.as_deref(), exclude_lang_filter.as_deref()) {
127 Ok(langs) => langs,
128 Err(e) => {
129 eprintln!("cccc: {e}");
130 return 2;
131 }
132 };
133 let dispatch = lang::build_dispatch(&languages, &per_lang_ext);
134
135 let exts: Vec<String> = if global_ext.is_empty() {
139 dispatch.keys().cloned().collect()
140 } else {
141 for ext in &global_ext {
142 if !dispatch.contains_key(ext) {
143 eprintln!(
144 "cccc: warning: no active language analyzes .{ext} files; they will be skipped"
145 );
146 }
147 }
148 global_ext
149 };
150
151 let exclude = match walk::build_exclude_set(&exclude_patterns) {
154 Ok(set) => set,
155 Err(e) => {
156 eprintln!("cccc: invalid --exclude pattern: {e}");
157 return 2;
158 }
159 };
160
161 let files = walk::collect_files(&cli.paths, &exts, no_ignore, exclude.as_ref());
162 if files.is_empty() {
163 eprintln!("cccc: no matching files found");
164 return 0;
165 }
166
167 let jobs = jobs_opt.map(|j| j as usize).unwrap_or_else(|| {
170 std::thread::available_parallelism()
171 .map(|n| n.get())
172 .unwrap_or(1)
173 });
174
175 let mut reports: Vec<FileReport> = if jobs <= 1 || files.len() <= PARALLEL_THRESHOLD {
178 files
179 .iter()
180 .filter_map(|p| read_and_analyze(&dispatch, p))
181 .collect()
182 } else {
183 let pool = match rayon::ThreadPoolBuilder::new().num_threads(jobs).build() {
184 Ok(pool) => pool,
185 Err(e) => {
186 eprintln!("cccc: failed to start thread pool: {e}");
187 return 2;
188 }
189 };
190 pool.install(|| {
191 files
192 .par_iter()
193 .filter_map(|p| read_and_analyze(&dispatch, p))
194 .collect()
195 })
196 };
197
198 reports.sort_by(|a, b| a.path.cmp(&b.path));
199
200 let fail = (max_cognitive.is_some() || max_cyclomatic.is_some())
203 && reports
204 .iter()
205 .any(|r| exceeds(&r.functions, max_cognitive, max_cyclomatic));
206
207 let summary = report::compute_summary(&reports);
210
211 let top_request = match (cli.top_cognitive, cli.top_cyclomatic) {
214 (Some(n), _) => Some((Metric::Cognitive, n)),
215 (_, Some(n)) => Some((Metric::Cyclomatic, n)),
216 (None, None) => None,
217 };
218 if let Some((metric, n)) = top_request {
219 let top = report::build_top_report(&reports, summary, metric, n);
220 if table {
221 output::print_top_table(&top);
222 } else {
223 output::print_json(&top);
224 }
225 return i32::from(fail);
226 }
227
228 if let Some(min) = min {
229 for r in &mut reports {
230 r.functions = filter_min(std::mem::take(&mut r.functions), min);
231 }
232 }
233
234 let report = Report {
235 files: reports,
236 summary,
237 };
238
239 if table {
240 output::print_table(&report);
241 } else {
242 output::print_json(&report);
243 }
244
245 i32::from(fail)
246}
247
248type ExtSettings = (BTreeMap<String, Vec<String>>, Vec<String>);
251
252fn resolve_ext(
259 config_ext: Option<BTreeMap<String, Vec<String>>>,
260 cli_ext: Option<&[String]>,
261) -> Result<ExtSettings, String> {
262 let mut per_lang: BTreeMap<String, Vec<String>> = BTreeMap::new();
263 if let Some(cfg) = config_ext {
264 for (key, list) in cfg {
265 let canon = lang::require_canonical(key.trim(), "[ext] config")?;
266 per_lang.insert(canon.to_string(), list);
267 }
268 }
269 let mut global: Vec<String> = Vec::new();
270 for raw in cli_ext.unwrap_or(&[]) {
271 match raw.split_once('=') {
272 Some((name, exts)) => {
273 let canon = lang::require_canonical(name.trim(), "--ext")?;
274 per_lang.insert(canon.to_string(), split_exts(exts));
275 }
276 None => global.extend(split_exts(raw).into_iter().map(|e| e.to_ascii_lowercase())),
277 }
278 }
279 Ok((per_lang, global))
280}
281
282fn split_exts(s: &str) -> Vec<String> {
284 s.split(',')
285 .map(|e| e.trim().to_string())
286 .filter(|e| !e.is_empty())
287 .collect()
288}
289
290fn read_and_analyze(dispatch: &HashMap<String, AnalyzeFn>, path: &Path) -> Option<FileReport> {
294 let analyze = path
295 .extension()
296 .and_then(|e| e.to_str())
297 .and_then(|e| dispatch.get(&e.to_ascii_lowercase()))?;
298 match std::fs::read_to_string(path) {
299 Ok(src) => Some(analyze(path, &src)),
300 Err(e) => {
301 eprintln!("cccc: cannot read {}: {e}", path.display());
302 None
303 }
304 }
305}
306
307fn exceeds(fns: &[FunctionReport], max_cog: Option<u32>, max_cyc: Option<u32>) -> bool {
309 fns.iter().any(|f| {
310 max_cog.is_some_and(|m| f.cognitive > m)
311 || max_cyc.is_some_and(|m| f.cyclomatic > m)
312 || exceeds(&f.children, max_cog, max_cyc)
313 })
314}
315
316fn filter_min(fns: Vec<FunctionReport>, min: u32) -> Vec<FunctionReport> {
319 fns.into_iter()
320 .filter_map(|mut f| {
321 f.children = filter_min(std::mem::take(&mut f.children), min);
322 let keep = f.cognitive >= min || f.cyclomatic >= min || !f.children.is_empty();
323 if keep { Some(f) } else { None }
324 })
325 .collect()
326}