barad-dur 0.13.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
use std::collections::{HashMap, HashSet};

use crate::metrics::coupling::extract_component;
use crate::snapshot::RepoSnapshot;

use super::actions::score_commit_message;
use super::types::{AuthorCard, AuthorShare, CouplingPair, FileAge, FileOwnership, HotspotFile};

const BUG_KEYWORDS: &[&str] = &["fix", "bug", "broken", "crash", "regression"];

pub(super) fn build_hotspots(snapshot: &RepoSnapshot) -> Vec<HotspotFile> {
    // Pre-classify bug-fix commits by ID to avoid O(files × commits) message scanning.
    let bug_commit_ids: HashSet<crate::snapshot::CommitId> = snapshot
        .commits
        .iter()
        .filter(|c| {
            let msg = c.message.to_lowercase();
            BUG_KEYWORDS.iter().any(|kw| msg.contains(kw))
        })
        .map(|c| c.id)
        .collect();

    let mut files: Vec<HotspotFile> = snapshot
        .files
        .iter()
        .filter(|f| !f.is_binary)
        .map(|f| {
            let commit_ids = snapshot.commits_by_file.get(&f.path);
            let churn = commit_ids.map(|v| v.len()).unwrap_or(0);
            let bug_commit_count = commit_ids
                .map(|ids| ids.iter().filter(|id| bug_commit_ids.contains(id)).count())
                .unwrap_or(0);
            let metrics = snapshot
                .file_metrics
                .get(&f.path)
                .cloned()
                .unwrap_or_default();
            HotspotFile {
                path: f.path.to_string_lossy().to_string(),
                churn_count: churn,
                bug_commit_count,
                loc: metrics.loc,
                total_lines: metrics.total_lines,
                cyclomatic_complexity: metrics.cyclomatic_complexity,
                public_methods: metrics.public_methods,
                properties: metrics.properties,
                hotspot_score: 0.0,
            }
        })
        .collect();

    if files.is_empty() {
        return files;
    }

    let max_churn = files
        .iter()
        .map(|f| f.churn_count)
        .max()
        .unwrap_or(1)
        .max(1);
    let max_cc = files
        .iter()
        .map(|f| f.cyclomatic_complexity as usize)
        .max()
        .unwrap_or(1)
        .max(1);
    let max_loc = files.iter().map(|f| f.loc).max().unwrap_or(1).max(1);

    for f in &mut files {
        let churn_norm = f.churn_count as f64 / max_churn as f64;
        let cc_norm = f.cyclomatic_complexity as f64 / max_cc as f64;
        let loc_norm = f.loc as f64 / max_loc as f64;
        f.hotspot_score = (churn_norm * 0.5 + cc_norm * 0.3 + loc_norm * 0.2) * 100.0;
    }

    files.sort_by(|a, b| b.hotspot_score.partial_cmp(&a.hotspot_score).unwrap());
    files
}

pub(super) fn build_coupling_pairs(
    snapshot: &RepoSnapshot,
    component_depth: usize,
) -> Vec<CouplingPair> {
    snapshot
        .file_change_pairs
        .iter()
        .map(|(a, b, co)| {
            let a_changes = snapshot
                .commits_by_file
                .get(a)
                .map(|v| v.len())
                .unwrap_or(0);
            let b_changes = snapshot
                .commits_by_file
                .get(b)
                .map(|v| v.len())
                .unwrap_or(0);
            let min_changes = a_changes.min(b_changes).max(1);
            let coupling_pct = (*co as f64 / min_changes as f64 * 100.0).min(100.0);
            let cross_boundary =
                extract_component(a, component_depth) != extract_component(b, component_depth);
            CouplingPair {
                file_a: a.to_string_lossy().to_string(),
                file_b: b.to_string_lossy().to_string(),
                co_changes: *co,
                coupling_pct,
                cross_boundary,
            }
        })
        .collect()
}

pub(super) fn build_author_ownership(snapshot: &RepoSnapshot) -> Vec<FileOwnership> {
    snapshot
        .blame_map
        .iter()
        .map(|(path, lines)| {
            let mut author_counts: HashMap<usize, usize> = HashMap::new();
            for line in lines {
                *author_counts.entry(line.author_id).or_insert(0) += line.line_count;
            }
            let total: usize = lines.iter().map(|l| l.line_count).sum::<usize>().max(1);
            let mut authors: Vec<AuthorShare> = author_counts
                .into_iter()
                .map(|(id, count)| {
                    let name = snapshot
                        .authors
                        .get(id)
                        .map(|a| a.name.clone())
                        .unwrap_or_else(|| format!("author-{}", id));
                    AuthorShare {
                        name,
                        pct: count as f64 / total as f64 * 100.0,
                    }
                })
                .collect();
            authors.sort_by(|a, b| b.pct.partial_cmp(&a.pct).unwrap());
            FileOwnership {
                path: path.to_string_lossy().to_string(),
                authors,
            }
        })
        .collect()
}

pub(super) fn build_file_ages(snapshot: &RepoSnapshot) -> Vec<FileAge> {
    let now = chrono::Utc::now();
    let fallback = snapshot.created_at - chrono::Duration::days(365 * 5);
    let mut ages: Vec<FileAge> = snapshot
        .files
        .iter()
        .filter(|f| !f.is_binary)
        .map(|f| {
            let last_modified = snapshot
                .commits_by_file
                .get(&f.path)
                .and_then(|commit_ids| {
                    commit_ids
                        .iter()
                        .filter_map(|cid| snapshot.commits.iter().find(|c| c.id == *cid))
                        .map(|c| c.timestamp)
                        .max()
                })
                .unwrap_or(fallback);
            let days = (now - last_modified).num_days().max(0);
            FileAge {
                path: f.path.to_string_lossy().to_string(),
                last_modified,
                days_since_modified: days,
            }
        })
        .collect();
    ages.sort_by(|a, b| b.days_since_modified.cmp(&a.days_since_modified));
    ages
}

pub(super) fn build_author_cards(snapshot: &RepoSnapshot) -> Vec<AuthorCard> {
    let now = chrono::Utc::now();

    // Pre-compute per-author blame lines across all files
    let mut author_lines: HashMap<usize, usize> = HashMap::new();
    let mut author_file_pcts: HashMap<usize, Vec<(String, f64)>> = HashMap::new();
    let mut author_files_owned: HashMap<usize, usize> = HashMap::new();

    for (path, blame_lines) in &snapshot.blame_map {
        let total: usize = blame_lines
            .iter()
            .map(|b| b.line_count)
            .sum::<usize>()
            .max(1);
        let mut counts: HashMap<usize, usize> = HashMap::new();
        for bl in blame_lines {
            *counts.entry(bl.author_id).or_insert(0) += bl.line_count;
        }
        for (&author_id, &count) in &counts {
            *author_lines.entry(author_id).or_insert(0) += count;
            let pct = count as f64 / total as f64 * 100.0;
            author_file_pcts
                .entry(author_id)
                .or_default()
                .push((path.to_string_lossy().to_string(), pct));
            if pct > 50.0 {
                *author_files_owned.entry(author_id).or_insert(0) += 1;
            }
        }
    }

    let mut cards: Vec<AuthorCard> = snapshot
        .authors
        .iter()
        .map(|author| {
            let commit_ids = snapshot
                .commits_by_author
                .get(&author.id)
                .cloned()
                .unwrap_or_default();

            let author_commits: Vec<&crate::snapshot::Commit> = commit_ids
                .iter()
                .filter_map(|cid| snapshot.commits.iter().find(|c| c.id == *cid))
                .collect();

            let commit_count = author_commits.len();

            let last_active = author_commits
                .iter()
                .map(|c| c.timestamp)
                .max()
                .unwrap_or(snapshot.created_at);
            let days_since_active = (now - last_active).num_days().max(0);

            let avg_commit_quality = if author_commits.is_empty() {
                0.0
            } else {
                let total_q: f64 = author_commits
                    .iter()
                    .map(|c| score_commit_message(&c.message))
                    .sum();
                total_q / author_commits.len() as f64
            };

            let mut file_pcts = author_file_pcts
                .get(&author.id)
                .cloned()
                .unwrap_or_default();
            file_pcts.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
            let top_files: Vec<String> = file_pcts.iter().take(5).map(|(p, _)| p.clone()).collect();

            let mut dirs = std::collections::HashSet::new();
            for commit in &author_commits {
                for fc in &commit.files_changed {
                    if let Some(parent) = fc.path.parent() {
                        dirs.insert(parent.to_string_lossy().to_string());
                    }
                }
            }

            AuthorCard {
                name: author.name.clone(),
                email: author.email.clone(),
                commit_count,
                files_owned: *author_files_owned.get(&author.id).unwrap_or(&0),
                lines_owned: *author_lines.get(&author.id).unwrap_or(&0),
                avg_commit_quality,
                top_files,
                last_active,
                days_since_active,
                directories_touched: dirs.len(),
            }
        })
        .collect();

    cards.sort_by(|a, b| b.commit_count.cmp(&a.commit_count));
    cards
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::snapshot::{Author, BlameLine, Commit, CommitId, FileEntry, TimeWindow};
    use chrono::Utc;
    use std::path::PathBuf;

    fn make_commit(id: u32, message: &str) -> Commit {
        Commit {
            id: CommitId(id),
            author: 0,
            timestamp: Utc::now(),
            message: message.to_string(),
            files_changed: vec![],
            is_merge: false,
            parent_count: 1,
        }
    }

    fn make_file_entry(path: &str) -> FileEntry {
        FileEntry {
            path: PathBuf::from(path),
            size_bytes: 100,
            is_binary: false,
            depth: 1,
            blob_oid: String::new(),
        }
    }

    #[test]
    fn bug_commit_count_is_zero_when_no_bug_commits() {
        let mut snapshot = RepoSnapshot::new(
            PathBuf::from("/tmp/test"),
            "test".into(),
            "main".into(),
            TimeWindow::default(),
        );
        let path = PathBuf::from("src/lib.rs");
        snapshot.files = vec![make_file_entry("src/lib.rs")];
        snapshot.commits = vec![
            make_commit(0, "feat: add new endpoint"),
            make_commit(1, "refactor: extract helper"),
        ];
        snapshot
            .commits_by_file
            .insert(path, vec![CommitId(0), CommitId(1)]);

        let hotspots = build_hotspots(&snapshot);
        assert_eq!(hotspots.len(), 1);
        assert_eq!(hotspots[0].bug_commit_count, 0);
    }

    #[test]
    fn bug_commit_count_detects_all_keywords() {
        for (keyword, label) in &[
            ("fix: broken auth", "fix"),
            ("bug in parser found", "bug"),
            ("broken after merge", "broken"),
            ("crash on startup", "crash"),
            ("regression in login", "regression"),
        ] {
            let mut snapshot = RepoSnapshot::new(
                PathBuf::from("/tmp/test"),
                "test".into(),
                "main".into(),
                TimeWindow::default(),
            );
            let path = PathBuf::from("src/lib.rs");
            snapshot.files = vec![make_file_entry("src/lib.rs")];
            snapshot.commits = vec![make_commit(0, keyword)];
            snapshot.commits_by_file.insert(path, vec![CommitId(0)]);

            let hotspots = build_hotspots(&snapshot);
            assert_eq!(
                hotspots[0].bug_commit_count, 1,
                "keyword '{}' should be detected",
                label
            );
        }
    }

    #[test]
    fn bug_commit_count_is_case_insensitive() {
        let mut snapshot = RepoSnapshot::new(
            PathBuf::from("/tmp/test"),
            "test".into(),
            "main".into(),
            TimeWindow::default(),
        );
        let path = PathBuf::from("src/lib.rs");
        snapshot.files = vec![make_file_entry("src/lib.rs")];
        snapshot.commits = vec![make_commit(0, "FIX: uppercase message")];
        snapshot.commits_by_file.insert(path, vec![CommitId(0)]);

        let hotspots = build_hotspots(&snapshot);
        assert_eq!(hotspots[0].bug_commit_count, 1);
    }

    #[test]
    fn bug_commit_count_only_counts_commits_touching_that_file() {
        let mut snapshot = RepoSnapshot::new(
            PathBuf::from("/tmp/test"),
            "test".into(),
            "main".into(),
            TimeWindow::default(),
        );
        snapshot.files = vec![make_file_entry("src/a.rs"), make_file_entry("src/b.rs")];
        snapshot.commits = vec![
            make_commit(0, "fix: broken in a"), // bug commit touching a only
            make_commit(1, "feat: add to b"),   // normal commit touching b only
        ];
        snapshot
            .commits_by_file
            .insert(PathBuf::from("src/a.rs"), vec![CommitId(0)]);
        snapshot
            .commits_by_file
            .insert(PathBuf::from("src/b.rs"), vec![CommitId(1)]);

        let hotspots = build_hotspots(&snapshot);
        let a = hotspots.iter().find(|f| f.path == "src/a.rs").unwrap();
        let b = hotspots.iter().find(|f| f.path == "src/b.rs").unwrap();
        assert_eq!(a.bug_commit_count, 1, "a.rs should have 1 bug commit");
        assert_eq!(b.bug_commit_count, 0, "b.rs should have 0 bug commits");
    }

    #[test]
    fn bug_commit_count_zero_for_file_not_in_commits_by_file() {
        let mut snapshot = RepoSnapshot::new(
            PathBuf::from("/tmp/test"),
            "test".into(),
            "main".into(),
            TimeWindow::default(),
        );
        snapshot.files = vec![make_file_entry("src/new.rs")];
        snapshot.commits = vec![make_commit(0, "fix: something")];
        // commits_by_file intentionally left empty — file not linked to any commit

        let hotspots = build_hotspots(&snapshot);
        assert_eq!(hotspots[0].bug_commit_count, 0);
    }

    fn make_test_snapshot_with_blame(
        authors: Vec<(&str, &str)>,
        blame_entries: Vec<(&str, Vec<BlameLine>)>,
    ) -> RepoSnapshot {
        let mut snapshot = RepoSnapshot::new(
            PathBuf::from("/tmp/test"),
            "test".into(),
            "main".into(),
            TimeWindow::default(),
        );
        snapshot.authors = authors
            .into_iter()
            .enumerate()
            .map(|(i, (name, email))| Author {
                id: i,
                name: name.to_string(),
                email: email.to_string(),
            })
            .collect();
        snapshot.blame_map = blame_entries
            .into_iter()
            .map(|(path, lines)| (PathBuf::from(path), lines))
            .collect();
        snapshot
    }

    fn blame(author_id: usize, line_count: usize) -> BlameLine {
        BlameLine {
            author_id,
            timestamp: Utc::now(),
            line_count,
        }
    }

    #[test]
    fn ownership_single_author_uncompressed() {
        let snapshot = make_test_snapshot_with_blame(
            vec![("Alice", "alice@x.com")],
            vec![("main.rs", vec![blame(0, 1), blame(0, 1), blame(0, 1)])],
        );

        let ownership = build_author_ownership(&snapshot);
        assert_eq!(ownership.len(), 1);
        assert_eq!(ownership[0].authors.len(), 1);
        assert!((ownership[0].authors[0].pct - 100.0).abs() < f64::EPSILON);
    }

    #[test]
    fn ownership_single_author_rle_compressed() {
        let snapshot = make_test_snapshot_with_blame(
            vec![("Alice", "alice@x.com")],
            vec![("main.rs", vec![blame(0, 50)])],
        );

        let ownership = build_author_ownership(&snapshot);
        assert_eq!(ownership[0].authors[0].pct, 100.0);
    }

    #[test]
    fn ownership_two_authors_uncompressed() {
        let snapshot = make_test_snapshot_with_blame(
            vec![("Alice", "alice@x.com"), ("Bob", "bob@x.com")],
            vec![(
                "main.rs",
                vec![blame(0, 1), blame(0, 1), blame(0, 1), blame(1, 1)],
            )],
        );

        let ownership = build_author_ownership(&snapshot);
        let file = &ownership[0];
        // Alice: 3/4 = 75%, Bob: 1/4 = 25%
        assert_eq!(file.authors[0].name, "Alice");
        assert!((file.authors[0].pct - 75.0).abs() < f64::EPSILON);
        assert_eq!(file.authors[1].name, "Bob");
        assert!((file.authors[1].pct - 25.0).abs() < f64::EPSILON);
    }

    #[test]
    fn ownership_two_authors_rle_gives_same_result_as_uncompressed() {
        // RLE: Alice owns 30 lines, Bob owns 10 lines → 75% / 25%
        let snapshot_rle = make_test_snapshot_with_blame(
            vec![("Alice", "alice@x.com"), ("Bob", "bob@x.com")],
            vec![("main.rs", vec![blame(0, 30), blame(1, 10)])],
        );
        // Uncompressed equivalent: same 40 lines, one entry per line
        let mut uncompressed_lines = vec![blame(0, 1); 30];
        uncompressed_lines.extend(vec![blame(1, 1); 10]);
        let snapshot_flat = make_test_snapshot_with_blame(
            vec![("Alice", "alice@x.com"), ("Bob", "bob@x.com")],
            vec![("main.rs", uncompressed_lines)],
        );

        let own_rle = build_author_ownership(&snapshot_rle);
        let own_flat = build_author_ownership(&snapshot_flat);

        for (r, f) in own_rle[0].authors.iter().zip(own_flat[0].authors.iter()) {
            assert_eq!(r.name, f.name);
            assert!((r.pct - f.pct).abs() < f64::EPSILON);
        }
    }

    #[test]
    fn ownership_empty_blame_map_returns_empty() {
        let snapshot = make_test_snapshot_with_blame(vec![("Alice", "alice@x.com")], vec![]);
        let ownership = build_author_ownership(&snapshot);
        assert!(ownership.is_empty());
    }
}