garbage-code-hunter 0.2.2

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
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
use regex::Regex;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Instant;

fn skip_unless_integration() -> bool {
    std::env::var("GCH_INTEGRATION").is_err()
}

// ============================================================
// 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 {
    // Current format: "Corruption Index: 1155 (💥76 🌶️87 😐992)"
    // Take the last occurrence (final verdict total)
    if let Some(caps) = Regex::new(r"Corruption Index:\s*(\d+)")
        .unwrap()
        .captures_iter(output)
        .last()
    {
        if let Some(m) = caps.get(1) {
            if let Ok(n) = m.as_str().parse() {
                return n;
            }
        }
    }
    // Legacy format: "Anomalies Detected: 1126 anomalies"
    if let Some(caps) = Regex::new(r"Anomalies Detected:\s*(\d+)")
        .unwrap()
        .captures(output)
    {
        if let Some(m) = caps.get(1) {
            if let Ok(n) = m.as_str().parse() {
                return n;
            }
        }
    }
    // Old format: "📝 Total" or "Total"
    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(|| {
            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!(&["analyze", ".", "--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 < 100000,
        "Self-bootstrap should have reasonable issue count (<100000), got {}",
        total
    );
}

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

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

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

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

#[test]
fn test_system_alert_detection_stable() {
    if skip_unless_integration() {
        return;
    }
    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!(&["analyze", project_path, "--lang", "en-US"]);

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

    let total = extract_total_issues(&stdout);

    assert!(
        (50..=200).contains(&total),
        "system_alert should have ~73 issues (near-dup removed), got {}",
        total
    );
}

#[test]
fn test_rechat_server_detection_stable() {
    if skip_unless_integration() {
        return;
    }
    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!(&["analyze", project_path, "--lang", "en-US"]);

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

    let total = extract_total_issues(&stdout);

    assert!(
        (50..=300).contains(&total),
        "ReChat-server should have ~160 issues (near-dup removed), got {}",
        total
    );
}

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

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

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

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

    let total = extract_total_issues(&stdout);

    assert!(
        (100..=60000).contains(&total),
        "Finance should have ~500-60000 issues (near-dup removed), got {}",
        total
    );
}

#[test]
fn test_memscope_rs_best_in_class() {
    if skip_unless_integration() {
        return;
    }
    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!(&["analyze", project_path, "--lang", "en-US"]);

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

    let total = extract_total_issues(&stdout);

    assert!(
        (1000..=1500000).contains(&total),
        "memscope-rs should have ~1000-1500000 issues (near-dup removed), got {}",
        total
    );
}

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

#[test]
fn test_all_testable_projects_zero_crashes() {
    if skip_unless_integration() {
        return;
    }
    let projects: Vec<(&str, Option<std::ops::RangeInclusive<u32>>)> = vec![
        ("../algo", Some(0..=10)),     // Algorithm example: minimal issues expected
        ("../gpu-code", Some(5..=60)), // 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!(&["analyze", 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() {
    if skip_unless_integration() {
        return;
    }
    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!(&["analyze", project_path, "--lang", "en-US"]);
    let duration = start.elapsed();

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

    assert!(
        duration.as_millis() < 30000,
        "Small project should complete under 30s, took {:?}",
        duration
    );
}

#[test]
fn test_medium_project_performance_under_20s() {
    if skip_unless_integration() {
        return;
    }
    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!(&["analyze", project_path, "--lang", "en-US"]);
    let duration = start.elapsed();

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

    assert!(
        duration.as_secs() < 60,
        "Medium project should complete under 60s, took {:?}",
        duration
    );
}

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

#[test]
fn test_markdown_output_format_valid() {
    let (stdout, _stderr, exit_code) =
        run_test!(&["analyze", ".", "--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() {
    if skip_unless_integration() {
        return;
    }
    let (stdout, _stderr, exit_code) =
        run_test!(&["analyze", "../system_alert", "--lang", "en-US", "--verbose"]);

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

    // Verbose output should show code quality score and categories
    assert!(
        stdout.contains("Score") || stdout.contains("Category"),
        "Verbose output should show code quality score or categories"
    );
}

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

#[test]
fn test_ui_context_reduces_false_positives() {
    if skip_unless_integration() {
        return;
    }
    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!(&["analyze", 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() {
    if skip_unless_integration() {
        return;
    }
    let regression_data: Vec<(&str, std::ops::RangeInclusive<u32>)> = vec![
        ("../system_alert", 50..=200),      // cross-file-near-duplicate removed
        ("../ReChat-server", 50..=300),     // cross-file-near-duplicate removed
        ("../AlgoGpuRust", 30..=100),       // cross-file-near-duplicate removed
        ("../memscope-rs", 1000..=1500000), // cross-file-near-duplicate removed
    ];

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

        let (stdout, _stderr, exit_code) = run_test!(&["analyze", 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
        );
    }
}