barad-dur 0.18.0

The all-seeing repository analyzer
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
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
use crate::metrics::{CategoryResult, MetricValue, RawValue};
use crate::snapshot::RepoSnapshot;

pub fn compute_hygiene(
    snapshot: &RepoSnapshot,
    thresholds: &crate::config::HygieneThresholds,
) -> CategoryResult {
    let metrics = vec![
        commit_message_quality(snapshot, thresholds),
        history_cleanliness(snapshot, thresholds),
        gitignore_coverage(snapshot, thresholds),
        firefighting_ratio(snapshot, thresholds),
    ];

    CategoryResult {
        name: "Git Hygiene".to_string(),
        score: 0,
        metrics,
    }
    .compute_score()
}

const CONVENTIONAL_PREFIXES: &[&str] = &[
    "feat:",
    "fix:",
    "docs:",
    "style:",
    "refactor:",
    "perf:",
    "test:",
    "chore:",
    "ci:",
    "build:",
    "revert:",
    "feat(",
    "fix(",
    "docs(",
    "style(",
    "refactor(",
    "perf(",
    "test(",
    "chore(",
    "ci(",
    "build(",
    "revert(",
];

/// Evaluate commit message quality.
fn commit_message_quality(
    snapshot: &RepoSnapshot,
    _thresholds: &crate::config::HygieneThresholds,
) -> MetricValue {
    if snapshot.commits.is_empty() {
        return MetricValue {
            name: "Commit message quality".to_string(),
            description: "No commits".to_string(),
            raw_value: RawValue::Text("N/A".to_string()),
            score: None,
        };
    }

    let window_commits: Vec<_> = snapshot
        .commits
        .iter()
        .filter(|c| snapshot.time_window.contains(&c.timestamp))
        .collect();

    if window_commits.is_empty() {
        return MetricValue {
            name: "Commit message quality".to_string(),
            description: "No commits in window".to_string(),
            raw_value: RawValue::Text("N/A".to_string()),
            score: None,
        };
    }

    let total = window_commits.len();
    let good = window_commits
        .iter()
        .filter(|c| is_good_commit_message(&c.message))
        .count();
    let conventional = window_commits
        .iter()
        .filter(|c| is_conventional_commit(&c.message))
        .count();

    let quality_pct = (good as f64 / total as f64) * 100.0;
    let conventional_pct = (conventional as f64 / total as f64) * 100.0;

    let score = if quality_pct > 80.0 {
        90
    } else if quality_pct > 60.0 {
        70
    } else if quality_pct > 40.0 {
        50
    } else {
        30
    };

    MetricValue {
        name: "Commit message quality".to_string(),
        description: format!(
            "{:.0}% good messages, {:.0}% conventional commits",
            quality_pct, conventional_pct
        ),
        raw_value: RawValue::Percentage(quality_pct),
        score: Some(score),
    }
}

fn is_good_commit_message(msg: &str) -> bool {
    let first_line = msg.lines().next().unwrap_or("");
    if first_line.len() < 10 {
        return false;
    }
    // Check for capitalization (after any conventional prefix)
    let subject = if let Some(pos) = first_line.find(": ") {
        &first_line[pos + 2..]
    } else {
        first_line
    };
    if subject.is_empty() {
        return false;
    }
    let first_char = subject.chars().next().unwrap();
    if !first_char.is_uppercase() && !is_conventional_commit(first_line) {
        return false;
    }
    // Not just "wip", "fix", "update" etc.
    let lower = first_line.to_lowercase();
    if lower == "wip" || lower == "fix" || lower == "update" || lower == "changes" {
        return false;
    }
    true
}

fn is_conventional_commit(msg: &str) -> bool {
    let lower = msg.to_lowercase();
    CONVENTIONAL_PREFIXES.iter().any(|p| lower.starts_with(p))
}

/// History cleanliness based on merge hygiene.
fn history_cleanliness(
    snapshot: &RepoSnapshot,
    _thresholds: &crate::config::HygieneThresholds,
) -> MetricValue {
    if snapshot.commits.is_empty() {
        return MetricValue {
            name: "History cleanliness".to_string(),
            description: "No commits".to_string(),
            raw_value: RawValue::Text("N/A".to_string()),
            score: None,
        };
    }

    let total = snapshot.commits.len();
    let merge_count = snapshot.commits.iter().filter(|c| c.is_merge).count();
    let octopus_merges = snapshot
        .commits
        .iter()
        .filter(|c| c.parent_count > 2)
        .count();

    // Check for empty commit messages
    let empty_messages = snapshot
        .commits
        .iter()
        .filter(|c| c.message.trim().is_empty())
        .count();

    let merge_pct = if total > 0 {
        (merge_count as f64 / total as f64) * 100.0
    } else {
        0.0
    };

    let issues = octopus_merges + empty_messages;

    let score = if issues > 5 || merge_pct > 60.0 {
        30
    } else if issues > 2 || merge_pct > 40.0 {
        55
    } else if merge_pct > 20.0 {
        75
    } else {
        90
    };

    MetricValue {
        name: "History cleanliness".to_string(),
        description: format!(
            "{:.0}% merges, {} octopus merges, {} empty messages",
            merge_pct, octopus_merges, empty_messages
        ),
        raw_value: RawValue::Count(issues),
        score: Some(score),
    }
}

const SUSPICIOUS_PATTERNS: &[&str] = &[
    ".env",
    ".env.",
    "credentials",
    "secret",
    ".key",
    ".pem",
    ".p12",
    ".pfx",
    "node_modules/",
    "__pycache__/",
    ".DS_Store",
    "Thumbs.db",
    ".pyc",
];

/// Check tracked files for suspicious patterns that should be in .gitignore.
fn gitignore_coverage(
    snapshot: &RepoSnapshot,
    _thresholds: &crate::config::HygieneThresholds,
) -> MetricValue {
    let suspicious: Vec<String> = snapshot
        .files
        .iter()
        .filter(|f| {
            let path_str = f.path.to_string_lossy().to_lowercase();
            let file_name = f
                .path
                .file_name()
                .map(|n| n.to_string_lossy().to_lowercase())
                .unwrap_or_default();

            SUSPICIOUS_PATTERNS
                .iter()
                .any(|pat| path_str.contains(pat) || file_name.ends_with(pat) || file_name == *pat)
        })
        .map(|f| f.path.display().to_string())
        .collect();

    let count = suspicious.len();

    let score = match count {
        0 => 100,
        1..=2 => 70,
        3..=5 => 45,
        _ => 20,
    };

    MetricValue {
        name: "Gitignore coverage".to_string(),
        description: if count > 0 {
            format!("{} suspicious tracked files", count)
        } else {
            "No suspicious tracked files".to_string()
        },
        raw_value: if suspicious.is_empty() {
            RawValue::Count(0)
        } else {
            RawValue::List(suspicious)
        },
        score: Some(score),
    }
}

const FIREFIGHTING_KEYWORDS: &[&str] = &["revert", "hotfix", "emergency", "rollback"];

/// Percentage of commits that are reactive firefighting work (reverts, hotfixes, rollbacks).
/// High ratios signal unreliable tests, missing staging, or deploy process issues.
fn firefighting_ratio(
    snapshot: &RepoSnapshot,
    _thresholds: &crate::config::HygieneThresholds,
) -> MetricValue {
    let window_commits: Vec<_> = snapshot
        .commits
        .iter()
        .filter(|c| !c.is_merge && snapshot.time_window.contains(&c.timestamp))
        .collect();

    if window_commits.is_empty() {
        return MetricValue {
            name: "Firefighting ratio".to_string(),
            description: "No commits in window".to_string(),
            raw_value: RawValue::Text("N/A".to_string()),
            score: None,
        };
    }

    let firefighting = window_commits
        .iter()
        .filter(|c| {
            let msg = c.message.to_lowercase();
            FIREFIGHTING_KEYWORDS.iter().any(|kw| msg.contains(kw))
        })
        .count();

    let total = window_commits.len();
    let pct = (firefighting as f64 / total as f64) * 100.0;

    let score = if pct < 2.0 {
        90
    } else if pct < 5.0 {
        75
    } else if pct < 10.0 {
        55
    } else if pct < 20.0 {
        35
    } else {
        20
    };

    MetricValue {
        name: "Firefighting ratio".to_string(),
        description: format!(
            "{firefighting} firefighting commits ({pct:.1}% of {total} non-merge commits)"
        ),
        raw_value: RawValue::Percentage(pct),
        score: Some(score),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::snapshot::*;
    use chrono::{Duration, Utc};
    use std::path::PathBuf;

    #[test]
    fn firefighting_ratio_detects_reactive_commits() {
        let mut snapshot = RepoSnapshot::new(
            PathBuf::from("/tmp"),
            "test".into(),
            "main".into(),
            TimeWindow::default(),
        );

        let now = Utc::now();
        let messages = [
            "feat: add login page",       // normal
            "revert: undo bad deploy",    // firefighting
            "fix: typo in README",        // normal
            "hotfix: prod is down",       // firefighting
            "refactor: clean up modules", // normal
        ];

        for (i, msg) in messages.iter().enumerate() {
            snapshot.commits.push(Commit {
                id: CommitId(i as u32),
                author: 0,
                timestamp: now - Duration::days(i as i64 + 1),
                message: msg.to_string(),
                files_changed: vec![],
                is_merge: false,
                parent_count: 1,
            });
        }

        let result = firefighting_ratio(&snapshot, &crate::config::HygieneThresholds::default());
        // 2 out of 5 non-merge commits = 40%
        match result.raw_value {
            RawValue::Percentage(p) => assert!((p - 40.0).abs() < 1.0, "Expected 40%, got {}", p),
            _ => panic!("Expected Percentage"),
        }
        assert!(
            result.score.unwrap() <= 35,
            "40% firefighting should score ≤35, got {:?}",
            result.score
        );
    }

    #[test]
    fn firefighting_ratio_ignores_merge_commits() {
        let mut snapshot = RepoSnapshot::new(
            PathBuf::from("/tmp"),
            "test".into(),
            "main".into(),
            TimeWindow::default(),
        );

        let now = Utc::now();
        // Merge commits should not count toward total
        snapshot.commits = vec![
            Commit {
                id: CommitId(0),
                author: 0,
                timestamp: now - Duration::days(1),
                message: "Merge branch main".into(),
                files_changed: vec![],
                is_merge: true,
                parent_count: 2,
            },
            Commit {
                id: CommitId(1),
                author: 0,
                timestamp: now - Duration::days(2),
                message: "revert bad change".into(),
                files_changed: vec![],
                is_merge: false,
                parent_count: 1,
            },
            Commit {
                id: CommitId(2),
                author: 0,
                timestamp: now - Duration::days(3),
                message: "feat: new feature".into(),
                files_changed: vec![],
                is_merge: false,
                parent_count: 1,
            },
        ];

        let result = firefighting_ratio(&snapshot, &crate::config::HygieneThresholds::default());
        // 1 firefighting out of 2 non-merge = 50%
        match result.raw_value {
            RawValue::Percentage(p) => assert!((p - 50.0).abs() < 1.0, "Expected 50%, got {}", p),
            _ => panic!("Expected Percentage"),
        }
    }

    #[test]
    fn firefighting_ratio_all_keywords_detected() {
        let now = Utc::now();
        for (msg, label) in &[
            ("revert: undo bad deploy", "revert"),
            ("hotfix: prod outage", "hotfix"),
            ("emergency: patch xss", "emergency"),
            ("rollback: bad migration", "rollback"),
        ] {
            let mut snapshot = RepoSnapshot::new(
                PathBuf::from("/tmp"),
                "test".into(),
                "main".into(),
                TimeWindow::default(),
            );
            snapshot.commits = vec![
                Commit {
                    id: CommitId(0),
                    author: 0,
                    timestamp: now - Duration::days(1),
                    message: msg.to_string(),
                    files_changed: vec![],
                    is_merge: false,
                    parent_count: 1,
                },
                Commit {
                    id: CommitId(1),
                    author: 0,
                    timestamp: now - Duration::days(2),
                    message: "feat: normal commit".into(),
                    files_changed: vec![],
                    is_merge: false,
                    parent_count: 1,
                },
            ];
            let result =
                firefighting_ratio(&snapshot, &crate::config::HygieneThresholds::default());
            match result.raw_value {
                RawValue::Percentage(p) => assert!(
                    (p - 50.0).abs() < 1.0,
                    "keyword '{}' should yield 50%, got {}",
                    label,
                    p
                ),
                _ => panic!("Expected Percentage for keyword '{}'", label),
            }
        }
    }

    #[test]
    fn firefighting_ratio_zero_percent_scores_highest() {
        let mut snapshot = RepoSnapshot::new(
            PathBuf::from("/tmp"),
            "test".into(),
            "main".into(),
            TimeWindow::default(),
        );
        let now = Utc::now();
        snapshot.commits = vec![
            Commit {
                id: CommitId(0),
                author: 0,
                timestamp: now - Duration::days(1),
                message: "feat: add login".into(),
                files_changed: vec![],
                is_merge: false,
                parent_count: 1,
            },
            Commit {
                id: CommitId(1),
                author: 0,
                timestamp: now - Duration::days(2),
                message: "refactor: extract module".into(),
                files_changed: vec![],
                is_merge: false,
                parent_count: 1,
            },
        ];
        let result = firefighting_ratio(&snapshot, &crate::config::HygieneThresholds::default());
        assert_eq!(result.score, Some(90), "0% firefighting should score 90");
    }

    #[test]
    fn firefighting_ratio_returns_na_when_no_commits_in_window() {
        let snapshot = RepoSnapshot::new(
            PathBuf::from("/tmp"),
            "test".into(),
            "main".into(),
            TimeWindow::default(),
        );
        // No commits added — window_commits will be empty
        let result = firefighting_ratio(&snapshot, &crate::config::HygieneThresholds::default());
        match result.raw_value {
            RawValue::Text(ref s) => assert_eq!(s, "N/A"),
            _ => panic!("Expected Text(N/A) for empty commit list"),
        }
        assert_eq!(result.score, None);
    }

    #[test]
    fn firefighting_ratio_is_case_insensitive() {
        let mut snapshot = RepoSnapshot::new(
            PathBuf::from("/tmp"),
            "test".into(),
            "main".into(),
            TimeWindow::default(),
        );
        let now = Utc::now();
        snapshot.commits = vec![Commit {
            id: CommitId(0),
            author: 0,
            timestamp: now - Duration::days(1),
            message: "HOTFIX: PROD IS ON FIRE".into(),
            files_changed: vec![],
            is_merge: false,
            parent_count: 1,
        }];
        let result = firefighting_ratio(&snapshot, &crate::config::HygieneThresholds::default());
        match result.raw_value {
            RawValue::Percentage(p) => assert!((p - 100.0).abs() < 1.0),
            _ => panic!("Expected Percentage"),
        }
    }

    #[test]
    fn commit_message_quality_scores() {
        let mut snapshot = RepoSnapshot::new(
            PathBuf::from("/tmp"),
            "test".into(),
            "main".into(),
            TimeWindow::default(),
        );

        let now = Utc::now();
        let messages = [
            "Add login feature with OAuth support",  // good
            "fix",                                   // bad (too short)
            "Update README with installation steps", // good
            "wip",                                   // bad
        ];

        for (i, msg) in messages.iter().enumerate() {
            snapshot.commits.push(Commit {
                id: CommitId(i as u32),
                author: 0,
                timestamp: now - Duration::days(i as i64 + 1),
                message: msg.to_string(),
                files_changed: vec![],
                is_merge: false,
                parent_count: 1,
            });
        }

        let result =
            commit_message_quality(&snapshot, &crate::config::HygieneThresholds::default());
        match result.raw_value {
            RawValue::Percentage(p) => assert!((p - 50.0).abs() < 1.0, "Expected ~50%, got {}", p),
            _ => panic!("Expected Percentage"),
        }
    }

    #[test]
    fn history_cleanliness_flags_issues() {
        let mut snapshot = RepoSnapshot::new(
            PathBuf::from("/tmp"),
            "test".into(),
            "main".into(),
            TimeWindow::default(),
        );

        let now = Utc::now();
        // 1 octopus merge + 1 empty message
        snapshot.commits = vec![
            Commit {
                id: CommitId(0),
                author: 0,
                timestamp: now,
                message: "msg".into(),
                files_changed: vec![],
                is_merge: true,
                parent_count: 3, // octopus
            },
            Commit {
                id: CommitId(1),
                author: 0,
                timestamp: now,
                message: "".into(), // empty
                files_changed: vec![],
                is_merge: false,
                parent_count: 1,
            },
            Commit {
                id: CommitId(2),
                author: 0,
                timestamp: now,
                message: "Normal commit".into(),
                files_changed: vec![],
                is_merge: false,
                parent_count: 1,
            },
        ];

        let result = history_cleanliness(&snapshot, &crate::config::HygieneThresholds::default());
        match result.raw_value {
            RawValue::Count(c) => assert_eq!(c, 2, "1 octopus + 1 empty = 2 issues"),
            _ => panic!("Expected Count"),
        }
    }

    #[test]
    fn gitignore_detects_suspicious_files() {
        let mut snapshot = RepoSnapshot::new(
            PathBuf::from("/tmp"),
            "test".into(),
            "main".into(),
            TimeWindow::default(),
        );

        snapshot.files = vec![
            FileEntry {
                path: ".env".into(),
                size_bytes: 50,
                is_binary: false,
                depth: 0,
                blob_oid: String::new(),
            },
            FileEntry {
                path: "node_modules/package.json".into(),
                size_bytes: 100,
                is_binary: false,
                depth: 1,
                blob_oid: String::new(),
            },
            FileEntry {
                path: "app.log".into(),
                size_bytes: 1000,
                is_binary: false,
                depth: 0,
                blob_oid: String::new(),
            },
            FileEntry {
                path: "src/main.rs".into(),
                size_bytes: 200,
                is_binary: false,
                depth: 1,
                blob_oid: String::new(),
            },
        ];

        let result = gitignore_coverage(&snapshot, &crate::config::HygieneThresholds::default());
        // .env and node_modules/ should be flagged
        match &result.raw_value {
            RawValue::List(items) => assert!(
                items.len() >= 2,
                "Expected at least 2 suspicious files, got {:?}",
                items
            ),
            _ => panic!("Expected List"),
        }
        assert!(result.score.unwrap() < 100);
    }
}