garbage-code-hunter 0.2.0

A humorous Rust code quality detector that roasts your garbage code
Documentation
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
use regex::Regex;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Instant;

// ============================================================
// Automated Bootstrap Integration Tests
// ============================================================

/// Find the garbage-code-hunter binary path (release or debug)
fn find_binary_path() -> Option<PathBuf> {
    let possible_paths = [
        PathBuf::from("./target/release/garbage-code-hunter"),
        PathBuf::from("./target/debug/garbage-code-hunter"),
    ];

    for path in &possible_paths {
        if path.exists() {
            return Some(path.clone());
        }
    }

    None
}

/// Helper function to run garbage-code-hunter CLI and return (stdout, stderr, exit_code)
/// Returns None if binary not found
fn run_garbage_hunter(args: &[&str]) -> Option<(String, String, i32)> {
    let binary_path = find_binary_path()?;

    let output = Command::new(&binary_path)
        .args(args)
        .output()
        .expect("Failed to execute garbage-code-hunter");

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    let exit_code = output.status.code().unwrap_or(-1);

    Some((stdout, stderr, exit_code))
}

/// Macro to simplify running tests with automatic skip if binary not found
macro_rules! run_test {
    ($args:expr) => {
        match run_garbage_hunter($args) {
            Some(result) => result,
            None => return,
        }
    };
}

/// Extract total issue count from output
fn extract_total_issues(output: &str) -> u32 {
    output
        .lines()
        .find(|line| line.contains("📝 Total") || line.contains("Total"))
        .and_then(|line| line.split_whitespace().next())
        .and_then(|num| num.parse().ok())
        .unwrap_or_else(|| {
            // Fallback: try to find any number followed by "Total" or "total"
            let re = Regex::new(r"(\d+)\s*(?:📝\s*)?Total").unwrap();
            re.captures(output)
                .and_then(|caps| caps.get(1).and_then(|m| m.as_str().parse().ok()))
                .unwrap_or(0)
        })
}

// ============================================================
// Test: Self-Bootstrap (garbage-code-hunter analyzes itself)
// ============================================================

#[test]
fn test_self_bootstrap_completes_successfully() {
    let (stdout, stderr, exit_code) = run_test!(&[".", "--lang", "en-US"]);

    assert_eq!(exit_code, 0, "Should exit with code 0\nstderr: {}", stderr);

    let total = extract_total_issues(&stdout);
    assert!(
        total > 0,
        "Self-bootstrap should detect some issues in itself, got {}",
        total
    );

    assert!(
        total < 300,
        "Self-bootstrap should have reasonable issue count (<300), got {}",
        total
    );
}

#[test]
fn test_self_bootstrap_performance() {
    let start = Instant::now();
    let (_stdout, _stderr, exit_code) = run_test!(&[".", "--lang", "en-US"]);
    let duration = start.elapsed();

    assert_eq!(exit_code, 0, "Should complete successfully");

    assert!(
        duration.as_secs() < 10,
        "Self-bootstrap should complete within 10 seconds, took {:?}",
        duration
    );
}

// ============================================================
// Test: Known Projects Validation
// ============================================================

#[test]
fn test_system_alert_detection_stable() {
    let project_path = "../system_alert";

    if !Path::new(project_path).exists() {
        eprintln!("Skipping: {} not found", project_path);
        return;
    }

    let (stdout, _stderr, exit_code) = run_test!(&[project_path, "--lang", "en-US"]);

    assert_eq!(exit_code, 0, "Should analyze system_alert successfully");

    let total = extract_total_issues(&stdout);

    // Based on Round 5 results: should be ~122 issues
    assert!(
        (100..=150).contains(&total),
        "system_alert should have ~122 issues (±25%), got {}",
        total
    );
}

#[test]
fn test_rechat_server_detection_stable() {
    let project_path = "../ReChat-server";

    if !Path::new(project_path).exists() {
        eprintln!("Skipping: {} not found", project_path);
        return;
    }

    let (stdout, _stderr, exit_code) = run_test!(&[project_path, "--lang", "en-US"]);

    assert_eq!(exit_code, 0, "Should analyze ReChat-server successfully");

    let total = extract_total_issues(&stdout);

    // Based on Round 5 results: should be ~52 issues
    assert!(
        (40..=70).contains(&total),
        "ReChat-server should have ~52 issues (±20%), got {}",
        total
    );
}

#[test]
fn test_finance_project_improved_accuracy() {
    let project_path = "../Finance";

    if !Path::new(project_path).exists() {
        eprintln!("Skipping: {} not found", project_path);
        return;
    }

    let (stdout, _stderr, exit_code) = run_test!(&[project_path, "--lang", "en-US"]);

    assert_eq!(exit_code, 0, "Should analyze Finance successfully");

    let total = extract_total_issues(&stdout);

    // After Cargo.toml smart detection: should be ~266 (was 772 before fix)
    assert!(
        (200..=350).contains(&total),
        "Finance should have ~266 issues after Web context detection (±30%), got {}",
        total
    );

    // Verify it's significantly better than old baseline of 772
    assert!(
        total < 500,
        "Finance should show improvement from 772 baseline, got {}",
        total
    );
}

#[test]
fn test_memscope_rs_best_in_class() {
    let project_path = "../memscope-rs";

    if !Path::new(project_path).exists() {
        eprintln!("Skipping: {} not found", project_path);
        return;
    }

    let (stdout, _stderr, exit_code) = run_test!(&[project_path, "--lang", "en-US"]);

    assert_eq!(exit_code, 0, "Should analyze memscope-rs successfully");

    let total = extract_total_issues(&stdout);

    // memscope-rs is our best-performing large project: ~72 issues for 208 files
    assert!(
        (50..=100).contains(&total),
        "memscope-rs should have ~72 issues (±30%), got {}",
        total
    );

    // Quality score should be excellent (<1.0 per file average)
    let files_count = 208; // Known from bootstrap tests
    let avg_issues_per_file = total as f64 / files_count as f64;

    assert!(
        avg_issues_per_file < 1.0,
        "memscope-rs should have <1.0 issues/file on average, got {:.2}",
        avg_issues_per_file
    );
}

// ============================================================
// Test: Zero Crash Guarantee
// ============================================================

#[test]
fn test_all_testable_projects_zero_crashes() {
    let projects: Vec<(&str, Option<std::ops::RangeInclusive<u32>>)> = vec![
        ("../algo", Some(0..=0)),       // Algorithm example: perfect code, 0 issues
        ("../gpu-code", Some(20..=50)), // GPU code: small number of issues
    ];

    for (path, expected_range) in projects {
        if !Path::new(path).exists() {
            eprintln!("Skipping: {} not found", path);
            continue;
        }

        let (stdout, stderr, exit_code) = run_test!(&[path, "--lang", "en-US"]);

        assert_eq!(
            exit_code, 0,
            "{} should complete without crash\nstderr: {}",
            path, stderr
        );

        if let Some(range) = expected_range {
            let total = extract_total_issues(&stdout);
            assert!(
                range.contains(&total),
                "{} should have issues in range {:?}, got {}",
                path,
                range,
                total
            );
        }
    }
}

// ============================================================
// Test: Performance Benchmarks
// ============================================================

#[test]
fn test_small_project_performance_under_1s() {
    let project_path = "../AlgoGpuRust";

    if !Path::new(project_path).exists() {
        eprintln!("Skipping: {} not found", project_path);
        return;
    }

    let start = Instant::now();
    let (_stdout, _stderr, exit_code) = run_test!(&[project_path, "--lang", "en-US"]);
    let duration = start.elapsed();

    assert_eq!(exit_code, 0, "Should complete successfully");

    assert!(
        duration.as_millis() < 1000,
        "Small-medium project (21 files) should complete under 1s, took {:?}",
        duration
    );
}

#[test]
fn test_medium_project_performance_under_5s() {
    let project_path = "../Finance";

    if !Path::new(project_path).exists() {
        eprintln!("Skipping: {} not found", project_path);
        return;
    }

    let start = Instant::now();
    let (_stdout, _stderr, exit_code) = run_test!(&[project_path, "--lang", "en-US"]);
    let duration = start.elapsed();

    assert_eq!(exit_code, 0, "Should complete successfully");

    assert!(
        duration.as_secs() < 5,
        "Medium-large project (66 files) should complete under 5s, took {:?}",
        duration
    );
}

// ============================================================
// Test: Output Format Validation
// ============================================================

#[test]
fn test_markdown_output_format_valid() {
    let (stdout, _stderr, exit_code) = run_test!(&[".", "--lang", "en-US", "--markdown"]);

    assert_eq!(exit_code, 0, "Should generate markdown output");

    // Markdown output should contain standard elements
    assert!(
        stdout.contains("# 🗑️") || stdout.contains("# Garbage"),
        "Markdown output should contain header"
    );

    assert!(
        stdout.contains("## 📈")
            || stdout.contains("Issue Statistics")
            || stdout.contains("Issues by File"),
        "Markdown output should contain issues section"
    );

    // Should have table or list format for issues
    assert!(
        stdout.contains("|") || stdout.contains("- **"),
        "Markdown output should contain formatted issues (table or list)"
    );
}

#[test]
fn test_verbose_output_contains_rule_weights() {
    let (stdout, _stderr, exit_code) =
        run_test!(&["../system_alert", "--lang", "en-US", "--verbose"]);

    assert_eq!(exit_code, 0, "Should generate verbose output");

    // Verbose output should show rule weight multipliers
    assert!(
        stdout.contains("") || stdout.contains("rule_weight"),
        "Verbose output should show performance metrics or rule weights"
    );
}

// ============================================================
// Test: Context Detection Accuracy
// ============================================================

#[test]
fn test_ui_context_reduces_false_positives() {
    let project_path = "../system_alert";

    if !Path::new(project_path).exists() {
        eprintln!("Skipping: {} not found", project_path);
        return;
    }

    let (stdout, _stderr, exit_code) = run_test!(&[project_path, "--lang", "en-US", "--verbose"]);

    assert_eq!(exit_code, 0, "Should complete successfully");

    // Count meaningless-naming issues (should be low due to UI whitelist)
    let naming_issues: Vec<&str> = stdout
        .lines()
        .filter(|line| line.contains("meaningless-naming"))
        .collect();

    // With UI context detection, meaningless-naming should be ≤10 (was 89 before fix)
    assert!(
        naming_issues.len() <= 15,
        "UI context should reduce meaningless-naming to ≤15, got {}",
        naming_issues.len()
    );

    println!(
        "✅ system_alert UI context test passed: {} naming issues",
        naming_issues.len()
    );
}

// ============================================================
// Test: Regression Prevention
// ============================================================

#[test]
fn test_no_regression_from_round4_to_round5() {
    let regression_data: Vec<(&str, std::ops::RangeInclusive<u32>)> = vec![
        ("../system_alert", 100..=150), // Round 5: 122
        ("../ReChat-server", 40..=70),  // Round 5: 52
        ("../AlgoGpuRust", 20..=40),    // Round 5: 29
        ("../memscope-rs", 60..=90),    // Round 5: 72
    ];

    for (project_path, expected_range) in regression_data {
        if !Path::new(project_path).exists() {
            continue;
        }

        let (stdout, _stderr, exit_code) = run_test!(&[project_path, "--lang", "en-US"]);

        assert_eq!(exit_code, 0, "{} should succeed", project_path);

        let total = extract_total_issues(&stdout);

        assert!(
            expected_range.contains(&total),
            "REGRESSION DETECTED!\n\
             Project: {}\n\
             Expected range: {:?}\n\
             Actual: {}\n\
             This suggests a regression from the validated Round 5 baseline.",
            project_path,
            expected_range,
            total
        );
    }
}