sephera_graph 0.7.1

Dependency graph core: resolver, declarations, blast radius, rendering.
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
//! Blast-radius counting rules.
//!
//! These were moved here from the CLI crate along with the code they test. The
//! counting rules are graph analysis -- they are what a CI threshold compares
//! against and what the MCP server reports -- so the tests belong next to the
//! code rather than next to the terminal renderer.

use std::path::PathBuf;

use crate::types::{
    GraphEdge, GraphMetrics, GraphNode, GraphReport, ImportKind,
};

use super::GraphQuery;

fn edge(from: &str, to: &str, path: &str) -> GraphEdge {
    GraphEdge {
        from: from.to_owned(),
        to: Some(to.to_owned()),
        import_path: path.to_owned(),
        resolved: true,
        kind: ImportKind::Dependency,
        local_gap: false,
        cfg_gated: false,
    }
}

fn node(path: &str) -> GraphNode {
    GraphNode {
        file_path: path.to_owned(),
        language: Some("Rust"),
        imports_count: 1,
        imported_by_count: 1,
    }
}

fn empty_metrics() -> GraphMetrics {
    GraphMetrics {
        total_files: 0,
        total_internal_edges: 0,
        self_references: 0,
        total_external_edges: 0,
        unresolved_local_edges: 0,
        unresolved_local_samples: Vec::new(),
        cfg_gated_edges: 0,
        dependencies: Vec::new(),
        declared_dependency_edges: 0,
        local_crate_edges: 0,
        builtin_edges: 0,
        circular_dependencies: 0,
        most_importing: vec![],
        most_imported: vec![],
        cycles: vec![],
    }
}

fn report(nodes: &[&str], edges: &[(&str, &str, &str)]) -> GraphReport {
    GraphReport {
        base_path: PathBuf::from("."),
        focus_paths: vec![],
        depth: None,
        query: None,
        nodes: nodes.iter().copied().map(node).collect(),
        edges: edges
            .iter()
            .map(|(from, to, path)| edge(from, to, path))
            .collect(),
        metrics: empty_metrics(),
    }
}

/// `b` and `c` import `a`; `d` imports `b`, so it also reaches `a`.
fn repo_report() -> GraphReport {
    report(
        &["a.rs", "b.rs", "c.rs", "d.rs"],
        &[
            ("b.rs", "a.rs", "crate::a"),
            ("c.rs", "a.rs", "crate::a"),
            ("d.rs", "b.rs", "crate::b"),
        ],
    )
}

/// A file to report on, with dependents spread over two packages plus a
/// near-miss package whose name shares a prefix.
fn scoped_report() -> GraphReport {
    report(
        &[
            "target.rs",
            "crates/one/a.rs",
            "crates/one/b.rs",
            "crates/two/user.rs",
            "crates/twone/extra.rs",
        ],
        &[
            ("crates/one/a.rs", "target.rs", "crate::target"),
            ("crates/one/b.rs", "target.rs", "crate::target"),
            ("crates/two/user.rs", "target.rs", "crate::target"),
            ("crates/twone/extra.rs", "target.rs", "crate::target"),
        ],
    )
}

/// A scope path in the graph's spelling, as `build_focus_set` would
/// hand it over.
fn path(value: &str) -> String {
    value.to_owned()
}

use super::measure as measure_raw;
use super::{
    BlastRadius, dependent_count, match_path, measure_all,
    measure_scoped as measure_scoped_raw,
};
use crate::resolver::build_focus_set;

/// Measure a target that the fixture report definitely describes.
///
/// The real functions return `Result` because a query-filtered report cannot
/// describe a second file, which is one test's subject. Shallowing them here
/// keeps that check in one place instead of a `?` on every one of the other
/// twenty-odd assertions, where it would be noise.
fn measure(
    report: &GraphReport,
    target: &str,
    depth: Option<u32>,
) -> BlastRadius {
    measure_raw(report, target, depth)
        .expect("the fixture report describes this target")
}

fn measure_scoped(
    report: &GraphReport,
    target: &str,
    depth: Option<u32>,
    focus: &[String],
) -> BlastRadius {
    measure_scoped_raw(report, target, depth, focus)
        .expect("the fixture report describes this target")
}

#[test]
fn the_target_is_never_a_dependent_of_itself() {
    // The graph always contains the target node. Counting it would inflate every
    // radius by exactly one and make a threshold fire on a file nothing depends
    // on.
    let with_self_edge = report(
        &["a.rs", "b.rs"],
        &[("a.rs", "a.rs", "crate::a"), ("b.rs", "a.rs", "crate::a")],
    );
    let radius = measure(&with_self_edge, "a.rs", None);

    assert_eq!(dependent_count(&radius), 1);
    assert_eq!(radius.dependents[0].file, "b.rs");
}

#[test]
fn a_file_depending_by_two_names_is_counted_once() {
    // `b` reaches `a` under two import paths. Counting paths instead of files
    // would report three dependents where there are two, and the two answers
    // mean different things to a reviewer.
    let report = report(
        &["a.rs", "b.rs", "c.rs"],
        &[
            ("b.rs", "a.rs", "crate::a"),
            ("b.rs", "a.rs", "crate::a::Thing"),
            ("c.rs", "a.rs", "crate::a"),
        ],
    );

    let radius = measure(&report, "a.rs", None);

    assert_eq!(dependent_count(&radius), 2, "{radius:?}");
    let b = radius
        .dependents
        .iter()
        .find(|dependent| dependent.file == "b.rs")
        .expect("b.rs is a dependent");
    assert_eq!(b.imports, vec!["crate::a", "crate::a::Thing"]);
}

#[test]
fn a_file_reaching_the_target_two_ways_is_counted_once() {
    // `d` is imported by both `b` and `c`, so it depends on `a` twice.
    let radius = measure(&repo_report(), "a.rs", None);

    assert_eq!(dependent_count(&radius), 3, "{radius:?}");
}

#[test]
fn a_transitive_dependent_lists_no_direct_import_of_the_target() {
    // `d` depends on `a` through `b`, not by naming it. Its import list is
    // empty, and a renderer must fall back to naming the file alone rather than
    // inventing an import that does not exist.
    let radius = measure(&repo_report(), "a.rs", None);
    let d = radius
        .dependents
        .iter()
        .find(|dependent| dependent.file == "d.rs")
        .expect("d.rs is a transitive dependent");

    assert!(d.imports.is_empty(), "{d:?}");
}

#[test]
fn an_unresolved_edge_does_not_create_a_dependent() {
    let report = GraphReport {
        edges: vec![GraphEdge {
            from: "b.rs".to_owned(),
            to: Some("a.rs".to_owned()),
            import_path: "crate::a".to_owned(),
            resolved: false,
            kind: ImportKind::Dependency,
            local_gap: true,
            cfg_gated: false,
        }],
        ..report(&["a.rs", "b.rs"], &[])
    };

    // `b` is in the node list but no *resolved* edge joins it to `a`. Treating
    // the node list as proof of dependence would report a radius of 1 for a
    // coupling the resolver never established, which is the one thing a blast
    // radius must not do.
    let radius = measure(&report, "a.rs", None);

    assert_eq!(dependent_count(&radius), 0, "{radius:?}");
}

#[test]
fn an_unresolved_edge_is_ignored_alongside_a_real_one() {
    let report = GraphReport {
        edges: vec![
            edge("b.rs", "a.rs", "crate::a"),
            GraphEdge {
                from: "c.rs".to_owned(),
                to: Some("a.rs".to_owned()),
                import_path: "crate::missing".to_owned(),
                resolved: false,
                kind: ImportKind::Dependency,
                local_gap: true,
                cfg_gated: false,
            },
        ],
        ..report(&["a.rs", "b.rs", "c.rs"], &[])
    };

    let radius = measure(&report, "a.rs", None);

    assert_eq!(dependent_count(&radius), 1, "{radius:?}");
    assert_eq!(radius.dependents[0].file, "b.rs");
    assert_eq!(radius.dependents[0].imports, vec!["crate::a"]);
}

#[test]
fn a_cycle_back_to_the_target_still_terminates() {
    // A ring-shaped dependency graph is the pathological input for a
    // reachability walk. If it terminates here it terminates everywhere.
    let ring = report(
        &["a.rs", "b.rs", "c.rs"],
        &[
            ("b.rs", "a.rs", "crate::a"),
            ("c.rs", "b.rs", "crate::b"),
            ("a.rs", "c.rs", "crate::c"),
        ],
    );

    let radius = measure(&ring, "a.rs", None);

    assert_eq!(dependent_count(&radius), 2, "{radius:?}");
}

#[test]
fn depth_bounds_the_walk_and_is_reported() {
    // A limit accepted, documented, and ignored would be worse than one absent.
    let report = repo_report();
    let requested: Vec<String> = vec!["a.rs".to_owned()];

    let full = measure_all(&report, &requested, "", None, &[]).unwrap();
    let one_hop = measure_all(&report, &requested, "", Some(1), &[]).unwrap();
    let two_hops = measure_all(&report, &requested, "", Some(2), &[]).unwrap();

    assert_eq!(dependent_count(&full[0]), 3);
    assert_eq!(
        dependent_count(&one_hop[0]),
        2,
        "depth 1 must stop at direct importers"
    );
    assert_eq!(dependent_count(&two_hops[0]), 3);

    assert_eq!(one_hop[0].depth, Some(1));
    assert_eq!(full[0].depth, None);
}

#[test]
fn depth_applies_to_every_target_not_just_the_first() {
    // With several targets, a bound that leaked past the first would make the
    // ranking a mixture of two different questions.
    let report = repo_report();
    let requested: Vec<String> = vec!["a.rs".to_owned(), "d.rs".to_owned()];

    let radii = measure_all(&report, &requested, "", Some(1), &[]).unwrap();

    for radius in &radii {
        assert_eq!(radius.depth, Some(1), "{radius:?}");
    }
    assert_eq!(radii.iter().map(dependent_count).sum::<u64>(), 2);
}

#[test]
fn several_targets_come_back_widest_first() {
    let requested: Vec<String> =
        vec!["d.rs".to_owned(), "b.rs".to_owned(), "a.rs".to_owned()];

    let radii = measure_all(&repo_report(), &requested, "", None, &[]).unwrap();

    assert_eq!(
        radii.iter().map(dependent_count).collect::<Vec<_>>(),
        vec![3, 1, 0],
        "a reader asking about three files wants the widest at the top"
    );
    assert_eq!(
        radii.iter().map(|r| r.target.as_str()).collect::<Vec<_>>(),
        vec!["a.rs", "b.rs", "d.rs"]
    );
}

#[test]
fn batching_does_not_change_any_answer() {
    // The point of accepting several paths is that the graph is built once.
    // Answering each separately re-reads and re-parses the whole repository per
    // target.
    let requested: Vec<String> =
        vec!["a.rs".to_owned(), "b.rs".to_owned(), "d.rs".to_owned()];
    let report = repo_report();

    let together = measure_all(&report, &requested, "", None, &[]).unwrap();
    let mut together_counts: Vec<u64> =
        together.iter().map(dependent_count).collect();
    together_counts.sort_unstable();

    let mut apart: Vec<u64> = requested
        .iter()
        .map(|p| dependent_count(&measure(&report, p, None)))
        .collect();
    apart.sort_unstable();

    assert_eq!(together_counts, apart);
}

#[test]
fn one_unknown_path_aborts_and_names_all_of_them() {
    // A caller who mistyped two paths in a list of ten should learn about both
    // at once, not discover the second one on the next run.
    let requested: Vec<String> = vec![
        "a.rs".to_owned(),
        "typo_one.rs".to_owned(),
        "typo_two.rs".to_owned(),
    ];

    let error = measure_all(&repo_report(), &requested, "", None, &[])
        .unwrap_err()
        .to_string();

    assert!(error.contains("typo_one.rs"), "{error}");
    assert!(error.contains("typo_two.rs"), "{error}");
    assert!(
        !error.contains("`a.rs`"),
        "a path that resolved must not be reported as missing: {error}"
    );
}

#[test]
fn focus_narrows_the_answer_without_moving_the_target() {
    // Scoping to one package and reporting on a file in another is a question,
    // not a mistake. Dropping the target would leave a report that reads
    // "nothing here" rather than "nothing in this scope depends on it".
    let radius = measure_scoped(
        &scoped_report(),
        "target.rs",
        None,
        &[path("crates/other")],
    );

    assert_eq!(radius.target, "target.rs");
    assert_eq!(dependent_count(&radius), 0);
}

#[test]
fn focus_keeps_only_the_dependents_inside_the_scope() {
    let report = scoped_report();

    let everything = measure_scoped(&report, "target.rs", None, &[]);
    let one_package =
        measure_scoped(&report, "target.rs", None, &[path("crates/one")]);
    let both = measure_scoped(
        &report,
        "target.rs",
        None,
        &[path("crates/one"), path("crates/two")],
    );

    assert_eq!(dependent_count(&everything), 4);
    assert_eq!(dependent_count(&one_package), 2);
    assert_eq!(dependent_count(&both), 3);
    assert!(
        one_package
            .dependents
            .iter()
            .all(|dependent| dependent.file.starts_with("crates/one/")),
        "{:?}",
        one_package.dependents
    );
}

#[test]
fn focus_is_a_directory_boundary_not_a_string_prefix() {
    // `crates/two` must not match `crates/twone/extra.rs`, which is what a bare
    // `starts_with` would do.
    let radius = measure_scoped(
        &scoped_report(),
        "target.rs",
        None,
        &[path("crates/two")],
    );

    assert_eq!(dependent_count(&radius), 1);
    assert_eq!(radius.dependents[0].file, "crates/two/user.rs");
}

#[test]
fn focus_and_depth_bound_the_same_walk() {
    // Two independent limits: which files count, and how far away they may be.
    // A dependent inside the scope but two hops out is excluded by depth, not
    // by scope.
    let mut report = scoped_report();
    report.nodes.push(node("crates/one/far.rs"));
    report.edges.push(edge(
        "crates/one/far.rs",
        "crates/two/user.rs",
        "crate::two",
    ));

    let scoped_and_bounded =
        measure_scoped(&report, "target.rs", Some(1), &[path("crates/one")]);
    assert_eq!(dependent_count(&scoped_and_bounded), 2);

    let scoped_unbounded =
        measure_scoped(&report, "target.rs", None, &[path("crates/one")]);
    assert_eq!(dependent_count(&scoped_unbounded), 3);
}

#[test]
fn an_empty_scope_means_everything() {
    let report = scoped_report();

    assert_eq!(
        dependent_count(&measure_scoped(&report, "target.rs", None, &[])),
        dependent_count(&measure(&report, "target.rs", None)),
    );
}

#[test]
fn a_windows_style_git_path_matches_the_graph() {
    // Git reports `src\a.rs` on Windows; the graph spells it `src/a.rs`.
    //
    // Per platform, because a backslash is a separator on one and a legal
    // file-name character on the other. On Unix the two are different files, and
    // matching them would report the radius of a file git never named.
    let report = report(
        &["src/a.rs", "src/b.rs"],
        &[("src/b.rs", "src/a.rs", "crate::a")],
    );

    let matched = match_path(&report, "src\\a.rs", "");

    if cfg!(windows) {
        assert_eq!(matched.as_deref(), Some("src/a.rs"));
    } else {
        assert_eq!(
            matched, None,
            "on Unix `src\\a.rs` is one file name, not a path into `src`"
        );
    }
}

#[test]
fn a_path_relative_to_the_repository_root_matches_when_analysing_a_subdirectory()
 {
    // `--path crates/demo --diff origin/master` reports `crates/demo/a.rs`
    // while the graph spells it `a.rs`.
    let report = report(&["a.rs", "b.rs"], &[("b.rs", "a.rs", "crate::a")]);

    assert_eq!(
        match_path(&report, "crates/demo/a.rs", "crates/demo").as_deref(),
        Some("a.rs"),
        "the analysis base prefix must be stripped before matching"
    );
}

#[test]
fn a_basename_collision_outside_the_base_does_not_match() {
    // Stripping progressively shorter tails instead of the exact prefix would
    // attach `elsewhere/a.rs` to `a.rs` and report impact for a file the caller
    // never asked about.
    assert_eq!(match_path(&repo_report(), "elsewhere/a.rs", ""), None);
}

#[test]
fn a_leading_dot_slash_does_not_defeat_matching() {
    assert_eq!(
        match_path(&repo_report(), "./a.rs", "").as_deref(),
        Some("a.rs")
    );
}

#[test]
fn measuring_the_query_target_is_not_treated_as_a_different_file() {
    // The refusal below is about asking for a *different* file. A request that
    // differs from the query target only in separators is the same file, and
    // separating the two is the whole difference between a useful check and one
    // that breaks on Windows.
    let filtered = GraphReport {
        query: Some(GraphQuery::DependsOn("a.rs".to_owned())),
        ..repo_report()
    };

    let same_file = measure_raw(&filtered, "a.rs", None);

    assert_eq!(
        same_file
            .expect("the query target itself is measurable")
            .target,
        "a.rs"
    );
}

#[test]
fn measuring_a_second_file_on_a_query_filtered_report_is_refused() {
    // `measure` takes the target from `report.query` when there is one. Asking
    // about a different file would therefore answer about the query's file and
    // say nothing, which is the worst shape a wrong answer can take. Rejected.
    let filtered = GraphReport {
        query: Some(GraphQuery::DependsOn("a.rs".to_owned())),
        ..repo_report()
    };

    let error = measure_all(&filtered, &["b.rs".to_owned()], "", None, &[])
        .unwrap_err()
        .to_string();

    assert!(
        error.contains("a.rs"),
        "the error must name the file the report actually describes: {error}"
    );
}

#[test]
fn measuring_the_query_target_itself_is_allowed() {
    // The refusal above is about a mismatch, not about query-filtered reports
    // as such.
    let filtered = GraphReport {
        query: Some(GraphQuery::DependsOn("a.rs".to_owned())),
        ..repo_report()
    };

    let radii =
        measure_all(&filtered, &["a.rs".to_owned()], "", None, &[]).unwrap();

    assert_eq!(radii[0].target, "a.rs");
    assert_eq!(dependent_count(&radii[0]), 3);
}

#[test]
fn an_absolute_scope_path_is_normalised_before_matching() {
    // Comparing an absolute `--focus` string against base-relative node paths
    // matches nothing and the radius comes back as zero with no explanation.
    // `build_focus_set` is what prevents that, so the measurement takes
    // already-normalised scopes. This pins the two halves fit together.
    //
    // The base is built from the real current directory rather than written as
    // `/repo`, because a leading slash is not an absolute path on Windows and
    // the normalisation under test keys off exactly that.
    let base = std::env::temp_dir().join("repo");
    let inside = base.join("crates").join("one");

    let scope = build_focus_set(&base, &[inside])
        .into_iter()
        .collect::<Vec<_>>();

    assert_eq!(
        scope,
        vec!["crates/one".to_owned()],
        "an absolute scope must be rewritten base-relative, or it matches \
         nothing"
    );

    let radius = measure_scoped(&scoped_report(), "target.rs", None, &scope);
    assert_eq!(
        dependent_count(&radius),
        2,
        "a normalised absolute scope must reach the same files a relative \
         one does"
    );
}

#[test]
fn a_relative_base_still_accepts_an_absolute_scope() {
    // `--path .` leaves the base relative, which is the case that made an
    // absolute `--focus` match nothing at all: zero dependents, no warning.
    //
    // Built under the working directory because the scope has to be inside the
    // base for the claim to mean anything -- a path elsewhere is out of scope
    // however the base is spelled.
    let base = std::env::current_dir().expect("a working directory");
    let absolute = base.join("crates").join("one");

    let scope = build_focus_set(
        std::path::Path::new("."),
        std::slice::from_ref(&absolute),
    )
    .into_iter()
    .collect::<Vec<_>>();

    assert_eq!(scope, vec!["crates/one".to_owned()]);

    let radius = measure_scoped(&scoped_report(), "target.rs", None, &scope);
    assert_eq!(
        dependent_count(&radius),
        2,
        "an absolute scope under `--path .` must reach the same dependents"
    );
}

#[test]
fn the_repository_prefix_is_empty_when_analysis_starts_at_the_root() {
    assert_eq!(
        super::base_prefix_for(
            std::path::Path::new("/repo"),
            std::path::Path::new("/repo")
        ),
        ""
    );
    assert_eq!(
        super::base_prefix_for(
            std::path::Path::new("/repo"),
            std::path::Path::new("/repo/crates/demo")
        ),
        "crates/demo"
    );
}

#[test]
fn the_repository_prefix_is_empty_when_the_paths_do_not_nest() {
    // A base outside the repository is not a crash; it just means no prefix to
    // strip.
    assert_eq!(
        super::base_prefix_for(
            std::path::Path::new("/repo"),
            std::path::Path::new("/elsewhere")
        ),
        ""
    );
}