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
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::path::{Path, PathBuf};

// ---------------------------------------------------------------------------
// Domain types
// ---------------------------------------------------------------------------

/// A direct dependency from one repo to another (path or git reference).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DirectDep {
    pub from: String,
    pub to: String,
}

/// A pair of repos with their shared dependency information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DependencyCouplingPair {
    pub repo_a: String,
    pub repo_b: String,
    pub shared_deps: Vec<String>,
    pub shared_count: usize,
    pub dep_score: f64,
    pub direct_dependency: Option<DirectDep>,
}

/// A dependency consumed by 3+ repos (hub dependency).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BlastRadiusEntry {
    pub dependency_name: String,
    pub consumers: Vec<String>,
    pub consumer_count: usize,
}

/// Full result of dependency coupling analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DependencyAnalysis {
    pub pairs: Vec<DependencyCouplingPair>,
    pub blast_radius: Vec<BlastRadiusEntry>,
}

// ---------------------------------------------------------------------------
// Manifest file types
// ---------------------------------------------------------------------------

/// A Cargo.toml dependency that references another repo (via path or git).
#[derive(Debug, Clone)]
struct CargoDep {
    /// The crate/repo name this dependency references.
    references_repo: String,
}

// ---------------------------------------------------------------------------
// Manifest parsing — pure functions
// ---------------------------------------------------------------------------

/// Parse dependency names from a Cargo.toml file content.
/// Returns (regular dep names, direct-dep references to other repos).
fn parse_cargo_toml(content: &str) -> (Vec<String>, Vec<CargoDep>) {
    let parsed: toml::Value = match content.parse() {
        Ok(v) => v,
        Err(_) => return (Vec::new(), Vec::new()),
    };

    let mut dep_names = Vec::new();
    let mut direct_deps = Vec::new();

    let sections = ["dependencies", "dev-dependencies"];
    for section in &sections {
        if let Some(table) = parsed.get(section).and_then(|v| v.as_table()) {
            for (name, value) in table {
                let has_path = value.get("path").is_some();
                let has_git = value.get("git").is_some();

                if has_path || has_git {
                    direct_deps.push(CargoDep {
                        references_repo: name.clone(),
                    });
                } else {
                    dep_names.push(name.clone());
                }
            }
        }
    }

    (dep_names, direct_deps)
}

/// Parse dependency names from a package.json file content.
fn parse_package_json(content: &str) -> Vec<String> {
    let parsed: serde_json::Value = match serde_json::from_str(content) {
        Ok(v) => v,
        Err(_) => return Vec::new(),
    };

    let sections = ["dependencies", "devDependencies"];
    sections
        .iter()
        .flat_map(|section| {
            parsed
                .get(section)
                .and_then(|v| v.as_object())
                .map(|obj| obj.keys().cloned().collect::<Vec<_>>())
                .unwrap_or_default()
        })
        .collect()
}

/// Parse dependency names from a go.mod file content.
fn parse_go_mod(content: &str) -> Vec<String> {
    let mut deps = Vec::new();
    let mut in_require_block = false;

    for line in content.lines() {
        let trimmed = line.trim();

        if trimmed.starts_with("require (") || trimmed == "require (" {
            in_require_block = true;
            continue;
        }

        if in_require_block {
            if trimmed == ")" {
                in_require_block = false;
                continue;
            }
            // Lines like: github.com/gin-gonic/gin v1.9.0
            if let Some(module_path) = trimmed.split_whitespace().next() {
                if !module_path.is_empty() {
                    deps.push(module_path.to_string());
                }
            }
        }

        // Single-line require: require github.com/foo/bar v1.0.0
        if trimmed.starts_with("require ") && !trimmed.contains('(') {
            let rest = trimmed.strip_prefix("require ").unwrap_or("");
            if let Some(module_path) = rest.split_whitespace().next() {
                if !module_path.is_empty() {
                    deps.push(module_path.to_string());
                }
            }
        }
    }

    deps
}

/// Parse dependency names from a requirements.txt file content.
fn parse_requirements_txt(content: &str) -> Vec<String> {
    content
        .lines()
        .map(|line| line.trim())
        .filter(|line| !line.is_empty() && !line.starts_with('#') && !line.starts_with('-'))
        .filter_map(|line| {
            // Split on version specifiers: ==, >=, <=, !=, ~=, >, <, [
            let name = line
                .split(&['=', '>', '<', '!', '~', '['][..])
                .next()
                .map(|s| s.trim().to_lowercase());
            name.filter(|n| !n.is_empty())
        })
        .collect()
}

/// Parse NuGet package names from a Directory.Packages.props file.
/// Extracts `Include` attribute from `<PackageVersion Include="...">` elements.
fn parse_directory_packages_props(content: &str) -> Vec<String> {
    content
        .lines()
        .filter_map(|line| {
            let trimmed = line.trim();
            if !trimmed.contains("PackageVersion") && !trimmed.contains("PackageReference") {
                return None;
            }
            extract_xml_include_attr(trimmed)
        })
        .collect()
}

/// Parse NuGet package and project references from a .csproj file.
/// Returns (package_names, project_references).
fn parse_csproj(content: &str) -> (Vec<String>, Vec<String>) {
    let mut packages = Vec::new();
    let mut project_refs = Vec::new();

    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.contains("PackageReference") {
            if let Some(name) = extract_xml_include_attr(trimmed) {
                packages.push(name);
            }
        } else if trimmed.contains("ProjectReference") {
            if let Some(raw_path) = extract_xml_include_attr(trimmed) {
                // Extract project name from path. .NET uses backslash separators
                // even on Linux, so split on both / and \.
                // "..\Foo\Foo.csproj" → "Foo.csproj" → "Foo"
                let file_part = raw_path.rsplit(['/', '\\']).next().unwrap_or("");
                let stem = file_part
                    .strip_suffix(".csproj")
                    .or_else(|| file_part.strip_suffix(".fsproj"))
                    .or_else(|| file_part.strip_suffix(".vbproj"))
                    .unwrap_or(file_part);
                if !stem.is_empty() {
                    project_refs.push(stem.to_string());
                }
            }
        }
    }

    (packages, project_refs)
}

/// Extract the value of `Include="..."` from an XML element string.
fn extract_xml_include_attr(line: &str) -> Option<String> {
    let marker = "Include=\"";
    let start = line.find(marker)? + marker.len();
    let end = line[start..].find('"')? + start;
    let value = &line[start..end];
    if value.is_empty() {
        None
    } else {
        Some(value.to_string())
    }
}

// ---------------------------------------------------------------------------
// Repo dependency extraction — reads filesystem
// ---------------------------------------------------------------------------

/// Information about a single repo's dependencies (parsed from manifests).
#[derive(Debug)]
struct RepoDeps {
    name: String,
    deps: HashSet<String>,
    /// Direct references to other repos (from Cargo.toml path/git deps).
    direct_refs: Vec<CargoDep>,
}

/// Collect .NET NuGet dependencies from a repo.
///
/// Prefers `Directory.Packages.props` (central package management) if found
/// at depth 0-2. Falls back to scanning all `*.csproj` files for
/// `<PackageReference>` elements.
fn collect_dotnet_deps(repo_path: &Path) -> Vec<String> {
    // Look for Directory.Packages.props at root, or one/two levels down
    let candidates = [
        repo_path.join("Directory.Packages.props"),
        repo_path.join("src/Directory.Packages.props"),
    ];
    for path in &candidates {
        if let Ok(content) = std::fs::read_to_string(path) {
            let deps = parse_directory_packages_props(&content);
            if !deps.is_empty() {
                return deps;
            }
        }
    }

    // Fallback: scan *.csproj files up to depth 4
    let mut deps = Vec::new();
    collect_csproj_files(repo_path, 0, 4, &mut deps);
    deps
}

/// Recursively find and parse *.csproj files up to `max_depth`.
fn collect_csproj_files(dir: &Path, depth: usize, max_depth: usize, deps: &mut Vec<String>) {
    if depth > max_depth {
        return;
    }
    let entries = match std::fs::read_dir(dir) {
        Ok(e) => e,
        Err(_) => return,
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            collect_csproj_files(&path, depth + 1, max_depth, deps);
        } else if path.extension().and_then(|e| e.to_str()) == Some("csproj") {
            if let Ok(content) = std::fs::read_to_string(&path) {
                let (packages, _project_refs) = parse_csproj(&content);
                deps.extend(packages);
            }
        }
    }
}

/// Read all manifest files from a repo path and extract dependency names.
fn extract_repo_deps(repo_name: &str, repo_path: &Path) -> RepoDeps {
    let mut all_deps = HashSet::new();
    let mut direct_refs = Vec::new();

    // Try Cargo.toml
    let cargo_path = repo_path.join("Cargo.toml");
    if let Ok(content) = std::fs::read_to_string(&cargo_path) {
        let (deps, cargo_directs) = parse_cargo_toml(&content);
        all_deps.extend(deps);
        direct_refs.extend(cargo_directs);
    }

    // Try package.json
    let pkg_path = repo_path.join("package.json");
    if let Ok(content) = std::fs::read_to_string(&pkg_path) {
        all_deps.extend(parse_package_json(&content));
    }

    // Try go.mod
    let gomod_path = repo_path.join("go.mod");
    if let Ok(content) = std::fs::read_to_string(&gomod_path) {
        all_deps.extend(parse_go_mod(&content));
    }

    // Try requirements.txt
    let req_path = repo_path.join("requirements.txt");
    if let Ok(content) = std::fs::read_to_string(&req_path) {
        all_deps.extend(parse_requirements_txt(&content));
    }

    // Try .NET: Directory.Packages.props (search up to depth 2), then *.csproj
    let dotnet_deps = collect_dotnet_deps(repo_path);
    all_deps.extend(dotnet_deps);

    RepoDeps {
        name: repo_name.to_string(),
        deps: all_deps,
        direct_refs,
    }
}

// ---------------------------------------------------------------------------
// Coupling computation — pure functions
// ---------------------------------------------------------------------------

/// Compute shared dependencies between two repos.
fn compute_shared_deps(deps_a: &HashSet<String>, deps_b: &HashSet<String>) -> Vec<String> {
    let mut shared: Vec<String> = deps_a.intersection(deps_b).cloned().collect();
    shared.sort();
    shared
}

/// Compute dependency coupling score: shared / union.
fn compute_dep_score(
    shared_count: usize,
    deps_a: &HashSet<String>,
    deps_b: &HashSet<String>,
) -> f64 {
    let union_count = deps_a.union(deps_b).count();
    if union_count == 0 {
        return 0.0;
    }
    (shared_count as f64 / union_count as f64) * 100.0
}

/// Detect direct dependency between two repos based on Cargo.toml path/git references.
fn detect_direct_dependency(
    repo_a_name: &str,
    repo_a_refs: &[CargoDep],
    repo_b_name: &str,
    repo_b_refs: &[CargoDep],
) -> Option<DirectDep> {
    // Check if A references B
    if repo_a_refs.iter().any(|r| r.references_repo == repo_b_name) {
        return Some(DirectDep {
            from: repo_a_name.to_string(),
            to: repo_b_name.to_string(),
        });
    }

    // Check if B references A
    if repo_b_refs.iter().any(|r| r.references_repo == repo_a_name) {
        return Some(DirectDep {
            from: repo_b_name.to_string(),
            to: repo_a_name.to_string(),
        });
    }

    None
}

/// Compute blast radius: dependencies consumed by 3+ repos.
fn compute_blast_radius(repo_deps: &[RepoDeps]) -> Vec<BlastRadiusEntry> {
    let mut dep_consumers: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();

    for repo in repo_deps {
        for dep in &repo.deps {
            dep_consumers
                .entry(dep.clone())
                .or_default()
                .insert(repo.name.clone());
        }
    }

    dep_consumers
        .into_iter()
        .filter(|(_, consumers)| consumers.len() >= 3)
        .map(|(dep_name, consumers)| {
            let consumer_count = consumers.len();
            BlastRadiusEntry {
                dependency_name: dep_name,
                consumers: consumers.into_iter().collect(),
                consumer_count,
            }
        })
        .collect()
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Analyze dependency coupling across all provided repositories.
///
/// Scans manifest files (Cargo.toml, package.json, go.mod, requirements.txt,
/// Directory.Packages.props, *.csproj) in each repo path to detect shared
/// dependencies and direct repo-to-repo dependencies.
pub fn analyze_dependency_coupling(repo_paths: &[(String, PathBuf)]) -> DependencyAnalysis {
    let repo_deps: Vec<RepoDeps> = repo_paths
        .iter()
        .map(|(name, path)| extract_repo_deps(name, path))
        .collect();

    let pairs = build_coupling_pairs(&repo_deps);
    let blast_radius = compute_blast_radius(&repo_deps);

    DependencyAnalysis {
        pairs,
        blast_radius,
    }
}

/// Build coupling pairs for all repo combinations.
fn build_coupling_pairs(repo_deps: &[RepoDeps]) -> Vec<DependencyCouplingPair> {
    let mut pairs = Vec::new();

    for i in 0..repo_deps.len() {
        for j in (i + 1)..repo_deps.len() {
            let a = &repo_deps[i];
            let b = &repo_deps[j];

            let shared_deps = compute_shared_deps(&a.deps, &b.deps);
            let shared_count = shared_deps.len();
            let dep_score = compute_dep_score(shared_count, &a.deps, &b.deps);
            let direct_dependency =
                detect_direct_dependency(&a.name, &a.direct_refs, &b.name, &b.direct_refs);

            // Include pair if there are shared deps or a direct dependency
            if shared_count > 0 || direct_dependency.is_some() {
                pairs.push(DependencyCouplingPair {
                    repo_a: a.name.clone(),
                    repo_b: b.name.clone(),
                    shared_deps,
                    shared_count,
                    dep_score,
                    direct_dependency,
                });
            }
        }
    }

    // Sort by dep_score descending
    pairs.sort_by(|a, b| {
        b.dep_score
            .partial_cmp(&a.dep_score)
            .unwrap_or(std::cmp::Ordering::Equal)
    });

    pairs
}

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

    #[test]
    fn parse_cargo_toml_extracts_dependency_names() {
        let content = r#"
[package]
name = "my-crate"

[dependencies]
serde = "1"
tokio = { version = "1", features = ["full"] }

[dev-dependencies]
assert_cmd = "2"
"#;
        let (deps, directs) = parse_cargo_toml(content);
        assert!(deps.contains(&"serde".to_string()));
        assert!(deps.contains(&"tokio".to_string()));
        assert!(deps.contains(&"assert_cmd".to_string()));
        assert!(directs.is_empty());
    }

    #[test]
    fn parse_cargo_toml_detects_path_dependency() {
        let content = r#"
[dependencies]
other-crate = { path = "../other-crate" }
"#;
        let (deps, directs) = parse_cargo_toml(content);
        assert!(deps.is_empty());
        assert_eq!(directs.len(), 1);
        assert_eq!(directs[0].references_repo, "other-crate");
    }

    #[test]
    fn parse_cargo_toml_detects_git_dependency() {
        let content = r#"
[dependencies]
my-lib = { git = "https://github.com/org/my-lib.git" }
"#;
        let (deps, directs) = parse_cargo_toml(content);
        assert!(deps.is_empty());
        assert_eq!(directs.len(), 1);
        assert_eq!(directs[0].references_repo, "my-lib");
    }

    #[test]
    fn parse_package_json_extracts_all_deps() {
        let content = r#"{
  "dependencies": { "express": "^4.0", "lodash": "^4.0" },
  "devDependencies": { "jest": "^29.0" }
}"#;
        let deps = parse_package_json(content);
        assert_eq!(deps.len(), 3);
        assert!(deps.contains(&"express".to_string()));
        assert!(deps.contains(&"lodash".to_string()));
        assert!(deps.contains(&"jest".to_string()));
    }

    #[test]
    fn parse_go_mod_extracts_require_block() {
        let content = "module example.com/foo\n\nrequire (\n\tgithub.com/gin v1.0\n\tgithub.com/redis v2.0\n)\n";
        let deps = parse_go_mod(content);
        assert_eq!(deps.len(), 2);
        assert!(deps.contains(&"github.com/gin".to_string()));
        assert!(deps.contains(&"github.com/redis".to_string()));
    }

    #[test]
    fn parse_requirements_txt_extracts_package_names() {
        let content = "flask==2.3.0\nrequests>=2.28\nnumpy\n# comment\n";
        let deps = parse_requirements_txt(content);
        assert_eq!(deps.len(), 3);
        assert!(deps.contains(&"flask".to_string()));
        assert!(deps.contains(&"requests".to_string()));
        assert!(deps.contains(&"numpy".to_string()));
    }

    #[test]
    fn compute_shared_deps_finds_intersection() {
        let a: HashSet<String> = ["serde", "tokio", "anyhow"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        let b: HashSet<String> = ["serde", "tokio", "clap"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        let shared = compute_shared_deps(&a, &b);
        assert_eq!(shared, vec!["serde", "tokio"]);
    }

    #[test]
    fn compute_dep_score_with_overlap() {
        let a: HashSet<String> = ["serde", "tokio"].iter().map(|s| s.to_string()).collect();
        let b: HashSet<String> = ["serde", "clap"].iter().map(|s| s.to_string()).collect();
        // shared=1 (serde), union=3 (serde, tokio, clap) => 33.33%
        let score = compute_dep_score(1, &a, &b);
        assert!((score - 33.333).abs() < 0.1);
    }

    #[test]
    fn blast_radius_only_includes_3_plus_consumers() {
        let repos = vec![
            RepoDeps {
                name: "a".to_string(),
                deps: ["x", "y"].iter().map(|s| s.to_string()).collect(),
                direct_refs: Vec::new(),
            },
            RepoDeps {
                name: "b".to_string(),
                deps: ["x", "y"].iter().map(|s| s.to_string()).collect(),
                direct_refs: Vec::new(),
            },
            RepoDeps {
                name: "c".to_string(),
                deps: ["x", "z"].iter().map(|s| s.to_string()).collect(),
                direct_refs: Vec::new(),
            },
        ];

        let blast = compute_blast_radius(&repos);
        // x has 3 consumers, y has 2
        assert_eq!(blast.len(), 1);
        assert_eq!(blast[0].dependency_name, "x");
        assert_eq!(blast[0].consumer_count, 3);
    }

    #[test]
    fn parse_directory_packages_props_extracts_nuget_names() {
        let content = r#"
<Project>
  <ItemGroup>
    <PackageVersion Include="Newtonsoft.Json" Version="13.0.3" />
    <PackageVersion Include="Serilog" Version="4.0.0" />
  </ItemGroup>
</Project>
"#;
        let deps = parse_directory_packages_props(content);
        assert_eq!(deps, vec!["Newtonsoft.Json", "Serilog"]);
    }

    #[test]
    fn parse_csproj_extracts_package_and_project_refs() {
        let content = r#"
<Project Sdk="Microsoft.NET.Sdk">
  <ItemGroup>
    <PackageReference Include="Divalto.Exceptions" />
    <PackageReference Include="Microsoft.AspNetCore.OpenApi" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\Shared\MyLib.csproj" />
  </ItemGroup>
</Project>
"#;
        let (packages, project_refs) = parse_csproj(content);
        assert_eq!(
            packages,
            vec!["Divalto.Exceptions", "Microsoft.AspNetCore.OpenApi"]
        );
        assert_eq!(project_refs, vec!["MyLib"]);
    }

    #[test]
    fn extract_xml_include_attr_returns_value() {
        let line = r#"    <PackageReference Include="Foo.Bar" />"#;
        assert_eq!(extract_xml_include_attr(line), Some("Foo.Bar".to_string()));
    }

    #[test]
    fn extract_xml_include_attr_returns_none_without_include() {
        let line = r#"    <PropertyGroup>"#;
        assert_eq!(extract_xml_include_attr(line), None);
    }
}