cargo-crappy 0.1.0

CRAP metric analysis for Rust — clippy-style diagnostics for change-risk, complexity, coverage, and idiomatic code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
#[macro_use]
mod color;
mod complexity;
mod coverage;
mod dryness;
mod idiom;
mod report;
mod scoring;
mod visitor;

use std::fmt;
use std::path::PathBuf;
use std::time::Instant;

#[derive(Debug)]
pub enum Error {
    Command {
        tool: &'static str,
        status: std::process::ExitStatus,
    },
    ToolNotFound {
        tool: String,
    },
    Io(std::io::Error),
    Json(bourne::Error),
    Syn {
        file: PathBuf,
        error: syn::Error,
    },
    NoTestBinaries,
    NoProfrawFiles,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Command { tool, status } => write!(f, "{tool} exited with {status}"),
            Self::ToolNotFound { tool } => {
                write!(f, "{tool} not found (run: rustup component add llvm-tools)")
            }
            Self::Io(e) => write!(f, "{e}"),
            Self::Json(e) => write!(f, "JSON parse error: {e}"),
            Self::Syn { file, error } => write!(f, "parse error in {}: {error}", file.display()),
            Self::NoTestBinaries => write!(f, "no test binaries found"),
            Self::NoProfrawFiles => write!(f, "no .profraw files generated (did any tests run?)"),
        }
    }
}

impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Self {
        Self::Io(e)
    }
}

impl From<bourne::Error> for Error {
    fn from(e: bourne::Error) -> Self {
        Self::Json(e)
    }
}

#[derive(Default)]
pub(crate) struct Opts {
    pub threshold: Option<f64>,
    pub top: Option<usize>,
    pub exclude_paths: Vec<String>,
    pub exclude_fns: Vec<String>,
    pub features: Vec<String>,
    pub all_features: bool,
    pub no_default_features: bool,
}

enum Action {
    Run(Opts),
    Help,
    Version,
}

fn arg_error(msg: &str) -> Error {
    Error::Io(std::io::Error::new(std::io::ErrorKind::InvalidInput, msg))
}

fn parse_flag_value<'a>(args: &'a [String], i: &mut usize, name: &str) -> Result<&'a str, Error> {
    *i += 1;
    args.get(*i)
        .map(std::string::String::as_str)
        .ok_or_else(|| arg_error(&format!("{name} requires a value")))
}

fn parse_args_from(args: &[String]) -> Result<Action, Error> {
    let mut opts = Opts::default();

    let mut i = 0;
    while i < args.len() {
        match args[i].as_str() {
            "--threshold" => {
                let val = parse_flag_value(args, &mut i, "--threshold")?;
                opts.threshold = Some(
                    val.parse::<f64>()
                        .map_err(|_| arg_error("invalid threshold value"))?,
                );
            }
            "--top" => {
                let val = parse_flag_value(args, &mut i, "--top")?;
                opts.top = Some(
                    val.parse::<usize>()
                        .map_err(|_| arg_error("invalid top value"))?,
                );
            }
            "--exclude-path" => {
                let val = parse_flag_value(args, &mut i, "--exclude-path")?;
                opts.exclude_paths.push(val.to_string());
            }
            "--exclude-fn" => {
                let val = parse_flag_value(args, &mut i, "--exclude-fn")?;
                opts.exclude_fns.push(val.to_string());
            }
            "--features" => {
                let val = parse_flag_value(args, &mut i, "--features")?;
                opts.features.push(val.to_string());
            }
            "--all-features" => opts.all_features = true,
            "--no-default-features" => opts.no_default_features = true,
            "-h" | "--help" => return Ok(Action::Help),
            "-V" | "--version" => return Ok(Action::Version),
            other => {
                eprintln!("unknown option: {other}");
                return Ok(Action::Help);
            }
        }
        i += 1;
    }

    Ok(Action::Run(opts))
}

fn parse_args() -> Result<Action, Error> {
    let args: Vec<String> = std::env::args().collect();
    let args = if args.get(1).is_some_and(|s| s == "crappy") {
        &args[2..]
    } else {
        &args[1..]
    };
    parse_args_from(args)
}

fn print_help() {
    eprintln!(
        "\
cargo-crappy — CRAP metric analysis with idiomatic Rust scoring

USAGE:
    cargo crappy [OPTIONS]

OPTIONS:
    --threshold <N>        Exit with code 1 if any function exceeds this CRAPPY score
    --top <N>              Show only the top N worst functions
    --exclude-path <PAT>   Exclude functions whose file path contains PAT (repeatable)
    --exclude-fn <NAME>    Exclude a function by name (repeatable)
    --features <F>         Comma-separated features to activate (passed to cargo test)
    --all-features         Activate all available features
    --no-default-features  Do not activate the `default` feature
    -h, --help             Print help
    -V, --version          Print version

SCORING:
    CRAPPY = CRAP x idiom_penalty

    CRAP (Change Risk Anti-Patterns):
        CRAP = CC^2 x (1 - cov/100)^3 + CC
        CC   = cyclomatic complexity (branches, match arms, loops, &&/||, ?)
        cov  = line coverage percentage from instrumented tests
        A fully-covered function scores CRAPPY = CC (complexity alone).
        An uncovered function scores CRAPPY = CC^2 + CC (risk amplified).

    Idiom penalty (multiplier >= 1.0):
        penalty = 1.0 + demerits x 0.25
        Each violation adds demerits; the penalty multiplies the CRAP score.
        Clean code gets 1.0x (no change). A single high-weight violation
        adds 50%. Multiple violations stack.

    Idiom checks (high-weight, 2 demerits each):
        - Free function whose first param is &Struct (should be a method)
        - Match on integer/string/char literals (should be an enum)
        - Primitive `as` cast inside comparison/arithmetic (use Ord/Add traits)

    Idiom checks (low-weight, 1 demerit each):
        - .unwrap() calls (use ? or .expect())
        - Explicit drop() calls (use scoped blocks)
        - vec![] for empty vectors (use Vec::new())
        - FromIterator::from_iter() (use .collect())
        - Box<dyn Error> in return types (use concrete error types)

    DRY-ness checks (3 demerits each):
        - Signature duplicate: two functions with identical (param_types)->return_type
        - Body duplicate: two functions with identical normalized AST structure
        Both can stack (6 demerits) when a function matches on both signals.

SUPPRESSION:
    #[allow(crappy)]   Annotate a function to exclude it from analysis.
                       Use #[allow(unknown_lints, crappy)] to also silence the compiler warning.

OUTPUT:
    Each function gets a clippy-style diagnostic with its location
    and actionable suggestions based on what contributes to its score.
    Functions above the threshold (default 30) are shown as warnings."
    );
}

pub(crate) fn cargo_feature_args(opts: &Opts) -> Vec<String> {
    let mut args = Vec::new();
    for f in &opts.features {
        args.push("--features".to_string());
        args.push(f.clone());
    }
    if opts.all_features {
        args.push("--all-features".to_string());
    }
    if opts.no_default_features {
        args.push("--no-default-features".to_string());
    }
    args
}

fn format_duration(d: std::time::Duration) -> String {
    let total_secs = d.as_secs();
    let millis = d.subsec_millis();
    if total_secs < 60 {
        format!("{total_secs}.{millis:03}s")
    } else {
        let mins = total_secs / 60;
        let rem = total_secs % 60;
        format!("{mins}m {rem}.{millis:03}s")
    }
}

pub(crate) fn analyze(
    project_dir: &std::path::Path,
    opts: &Opts,
) -> Result<Vec<scoring::CrapRecord>, Error> {
    let start = Instant::now();
    let feature_args = cargo_feature_args(opts);

    eprintln!(
        "{} tests with coverage instrumentation...",
        color::bold_green("Instrumenting")
    );
    let cov = coverage::collect_coverage(project_dir, &feature_args)?;
    eprintln!(
        "    {} {} functions with coverage data",
        color::bold_green("Collected"),
        cov.len()
    );

    eprintln!(
        "    {} complexity and idioms...",
        color::bold_green("Analyzing")
    );
    let (comp, idioms) = complexity::analyze_all(project_dir, &feature_args)?;
    eprintln!(
        "    {} {} functions",
        color::bold_green("Analyzed"),
        comp.len()
    );

    let mut records = scoring::compute_crap_scores(cov, &comp, idioms, project_dir);

    records.retain(|r| {
        !opts
            .exclude_paths
            .iter()
            .any(|p| r.file.contains(p.as_str()))
            && !opts.exclude_fns.contains(&r.name)
    });

    eprintln!(
        "    {} {} functions in {}\n",
        color::bold_green("Finished"),
        records.len(),
        format_duration(start.elapsed()),
    );

    report::print_report(&records, opts);

    Ok(records)
}

#[allow(unknown_lints, crappy)]
fn run() -> Result<(), Error> {
    let opts = match parse_args()? {
        Action::Run(opts) => opts,
        Action::Help => {
            print_help();
            return Ok(());
        }
        Action::Version => {
            println!("cargo-crappy {}", env!("CARGO_PKG_VERSION"));
            return Ok(());
        }
    };

    let project_dir = std::env::current_dir()?;
    let records = analyze(&project_dir, &opts)?;

    if let Some(threshold) = opts.threshold
        && records.iter().any(|r| r.crappy_score > threshold)
    {
        std::process::exit(1);
    }

    Ok(())
}

fn main() {
    if let Err(e) = run() {
        eprintln!("error: {e}");
        std::process::exit(2);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn args(strs: &[&str]) -> Vec<String> {
        strs.iter().map(|s| (*s).to_string()).collect()
    }

    #[test]
    fn no_args() {
        let a = args(&[]);
        let Action::Run(opts) = parse_args_from(&a).unwrap() else {
            panic!("expected Run");
        };
        assert!(opts.threshold.is_none());
        assert!(opts.top.is_none());
    }

    #[test]
    fn threshold_flag() {
        let a = args(&["--threshold", "30"]);
        let Action::Run(opts) = parse_args_from(&a).unwrap() else {
            panic!("expected Run");
        };
        assert!((opts.threshold.unwrap() - 30.0).abs() < f64::EPSILON);
    }

    #[test]
    fn top_flag() {
        let a = args(&["--top", "5"]);
        let Action::Run(opts) = parse_args_from(&a).unwrap() else {
            panic!("expected Run");
        };
        assert_eq!(opts.top.unwrap(), 5);
    }

    #[test]
    fn both_flags() {
        let a = args(&["--threshold", "20", "--top", "10"]);
        let Action::Run(opts) = parse_args_from(&a).unwrap() else {
            panic!("expected Run");
        };
        assert!((opts.threshold.unwrap() - 20.0).abs() < f64::EPSILON);
        assert_eq!(opts.top.unwrap(), 10);
    }

    #[test]
    fn help_flag() {
        let a = args(&["--help"]);
        assert!(matches!(parse_args_from(&a).unwrap(), Action::Help));
    }

    #[test]
    fn version_flag() {
        let a = args(&["-V"]);
        assert!(matches!(parse_args_from(&a).unwrap(), Action::Version));
    }

    #[test]
    fn missing_threshold_value() {
        let a = args(&["--threshold"]);
        assert!(parse_args_from(&a).is_err());
    }

    #[test]
    fn invalid_threshold_value() {
        let a = args(&["--threshold", "abc"]);
        assert!(parse_args_from(&a).is_err());
    }

    #[test]
    fn exclude_path_flag() {
        let a = args(&["--exclude-path", "tests/", "--exclude-path", "benches/"]);
        let Action::Run(opts) = parse_args_from(&a).unwrap() else {
            panic!("expected Run");
        };
        assert_eq!(opts.exclude_paths, vec!["tests/", "benches/"]);
    }

    #[test]
    fn exclude_fn_flag() {
        let a = args(&["--exclude-fn", "main", "--exclude-fn", "run"]);
        let Action::Run(opts) = parse_args_from(&a).unwrap() else {
            panic!("expected Run");
        };
        assert_eq!(opts.exclude_fns, vec!["main", "run"]);
    }

    #[test]
    fn exclude_combined_with_threshold() {
        let a = args(&[
            "--threshold",
            "30",
            "--exclude-path",
            "tests/",
            "--exclude-fn",
            "run",
        ]);
        let Action::Run(opts) = parse_args_from(&a).unwrap() else {
            panic!("expected Run");
        };
        assert!((opts.threshold.unwrap() - 30.0).abs() < f64::EPSILON);
        assert_eq!(opts.exclude_paths, vec!["tests/"]);
        assert_eq!(opts.exclude_fns, vec!["run"]);
    }

    #[test]
    fn features_flag() {
        let a = args(&["--features", "foo,bar"]);
        let Action::Run(opts) = parse_args_from(&a).unwrap() else {
            panic!("expected Run");
        };
        assert_eq!(opts.features, vec!["foo,bar"]);
    }

    #[test]
    fn all_features_flag() {
        let a = args(&["--all-features"]);
        let Action::Run(opts) = parse_args_from(&a).unwrap() else {
            panic!("expected Run");
        };
        assert!(opts.all_features);
    }

    #[test]
    fn no_default_features_flag() {
        let a = args(&["--no-default-features"]);
        let Action::Run(opts) = parse_args_from(&a).unwrap() else {
            panic!("expected Run");
        };
        assert!(opts.no_default_features);
    }

    #[test]
    fn cargo_feature_args_empty() {
        let opts = Opts::default();
        assert!(cargo_feature_args(&opts).is_empty());
    }

    #[test]
    fn cargo_feature_args_all() {
        let opts = Opts {
            features: vec!["foo".into(), "bar".into()],
            all_features: true,
            no_default_features: true,
            ..Opts::default()
        };
        let a = cargo_feature_args(&opts);
        assert!(a.contains(&"--features".to_string()));
        assert!(a.contains(&"foo".to_string()));
        assert!(a.contains(&"bar".to_string()));
        assert!(a.contains(&"--all-features".to_string()));
        assert!(a.contains(&"--no-default-features".to_string()));
    }

    #[test]
    fn display_command_error() {
        use std::os::unix::process::ExitStatusExt;
        let e = Error::Command {
            tool: "cargo test",
            status: std::process::ExitStatus::from_raw(256), // exit code 1
        };
        let msg = format!("{e}");
        assert!(msg.contains("cargo test"));
    }

    #[test]
    fn display_tool_not_found() {
        let e = Error::ToolNotFound {
            tool: "llvm-cov".into(),
        };
        let msg = format!("{e}");
        assert!(msg.contains("llvm-cov"));
        assert!(msg.contains("rustup component add llvm-tools"));
    }

    #[test]
    fn display_io_error() {
        let e = Error::Io(std::io::Error::new(std::io::ErrorKind::NotFound, "gone"));
        assert!(format!("{e}").contains("gone"));
    }

    #[test]
    fn display_json_error() {
        let err = bourne::parse::<bool>(b"not json").unwrap_err();
        let e = Error::Json(err);
        assert!(!format!("{e}").is_empty());
    }

    #[test]
    fn display_syn_error() {
        let err = syn::parse_file("fn {")
            .map(|_| ())
            .expect_err("should fail");
        let e = Error::Syn {
            file: PathBuf::from("test.rs"),
            error: err,
        };
        let msg = format!("{e}");
        assert!(msg.contains("test.rs"));
    }

    #[test]
    fn display_no_test_binaries() {
        assert!(format!("{}", Error::NoTestBinaries).contains("no test binaries"));
    }

    #[test]
    fn display_no_profraw() {
        assert!(format!("{}", Error::NoProfrawFiles).contains("profraw"));
    }

    #[test]
    fn from_io_error() {
        let io_err = std::io::Error::other("x");
        let e: Error = io_err.into();
        assert!(matches!(e, Error::Io(_)));
    }

    #[test]
    fn from_bourne_error() {
        let b_err = bourne::parse::<bool>(b"bad").unwrap_err();
        let e: Error = b_err.into();
        assert!(matches!(e, Error::Json(_)));
    }

    fn create_temp_project(name: &str, lib_rs: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("crappy-inproc-{}-{name}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let src = dir.join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(
            dir.join("Cargo.toml"),
            "[package]\nname = \"test-crate\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
        )
        .unwrap();
        std::fs::write(src.join("lib.rs"), lib_rs).unwrap();
        dir
    }

    #[test]
    #[ignore = "spawns cargo test — conflicts with outer coverage instrumentation"]
    fn collect_coverage_on_temp_project() {
        let dir = create_temp_project(
            "cov",
            r"
pub fn add(a: i32, b: i32) -> i32 { a + b }
pub fn unused(x: i32) -> i32 { if x > 0 { x } else { -x } }
#[cfg(test)]
mod tests {
    #[test]
    fn test_add() { assert_eq!(super::add(1, 2), 3); }
}
",
        );

        let cov = coverage::collect_coverage(&dir, &[]).unwrap();
        assert!(!cov.is_empty(), "should find covered functions");

        let add_cov = cov
            .iter()
            .find(|f| f.file.to_str().unwrap_or("").contains("lib.rs") && f.start_line <= 2);
        assert!(add_cov.is_some(), "should find coverage for add");
        assert!(
            add_cov.unwrap().line_coverage_pct > 0.0,
            "add should have coverage"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    #[ignore = "spawns cargo test — conflicts with outer coverage instrumentation"]
    fn analyze_full_pipeline() {
        let dir = create_temp_project(
            "full",
            r"
pub fn covered() -> i32 { 42 }
pub fn branchy(x: bool) -> i32 { if x { 1 } else { 2 } }
#[cfg(test)]
mod tests {
    #[test]
    fn test_covered() { assert_eq!(super::covered(), 42); }
}
",
        );

        let records = analyze(&dir, &Opts::default()).unwrap();
        assert_eq!(records.len(), 2, "should score 2 functions");

        let covered = records.iter().find(|r| r.name == "covered").unwrap();
        assert_eq!(covered.complexity, 1);
        assert!(covered.coverage_pct > 0.0);
        assert!((covered.crap_score - 1.0).abs() < 0.1);

        let branchy = records.iter().find(|r| r.name == "branchy").unwrap();
        assert!(branchy.complexity >= 2);

        let _ = std::fs::remove_dir_all(&dir);
    }
}