Skip to main content

source_mesh_core/graph/
model.rs

1use std::collections::BTreeMap;
2use std::collections::BTreeSet;
3use std::path::Component;
4use std::path::Path;
5use std::path::PathBuf;
6
7use anyhow::Context as _;
8use anyhow::Result;
9use anyhow::ensure;
10use derive_new::new;
11use getset::CopyGetters;
12use getset::Getters;
13
14use crate::SourcePath;
15
16/**
17```compile_fail
18use std::path::PathBuf;
19use source_mesh_core::model::FileNode;
20
21let node = FileNode::new(PathBuf::from("source.rs"));
22```
23*/
24#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Getters)]
25#[getset(get = "pub")]
26pub struct FileNode {
27    path: PathBuf,
28}
29
30impl FileNode {
31    #[must_use]
32    pub fn new(path: SourcePath) -> Self {
33        Self { path: path.into_path() }
34    }
35
36    #[must_use]
37    fn directory(&self) -> &Path {
38        let Some(directory) = self.path.parent() else {
39            unreachable!("A validated source file path always has a parent directory");
40        };
41        directory
42    }
43}
44
45#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Getters, new)]
46#[getset(get = "pub")]
47pub struct FolderNode {
48    label: String,
49}
50
51#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
52pub enum DependencyKind {
53    Production,
54    Test,
55}
56
57#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, CopyGetters, Getters, new)]
58pub struct Edge<Node> {
59    #[getset(get = "pub")]
60    source: Node,
61    #[getset(get = "pub")]
62    target: Node,
63    #[getset(get_copy = "pub")]
64    kind: DependencyKind,
65}
66
67pub type FileEdge = Edge<FileNode>;
68pub type FolderEdge = Edge<FolderNode>;
69
70/** Counts distinct directed file pairs of the same dependency kind.
71
72```compile_fail
73use std::collections::BTreeMap;
74use std::collections::BTreeSet;
75use source_mesh_core::model::DependencyKind;
76use source_mesh_core::model::FolderEdge;
77use source_mesh_core::model::FolderGraph;
78use source_mesh_core::model::FolderNode;
79
80let folder = FolderNode::new("src".into());
81let edge = FolderEdge::new(folder.clone(), folder.clone(), DependencyKind::Production);
82let depth = 2_usize;
83let graph = FolderGraph::new(BTreeSet::from([folder]), BTreeMap::from([(edge, depth)]));
84```
85*/
86#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, CopyGetters, new)]
87#[getset(get_copy = "pub")]
88pub struct DependencyCount {
89    value: usize,
90}
91
92impl DependencyCount {
93    const fn increment(&mut self) {
94        assert!(self.value < usize::MAX, "Dependency counts are bounded by the number of input edges");
95        self.value += 1;
96    }
97}
98
99#[derive(Default, PartialEq, Getters)]
100#[getset(get = "pub")]
101pub struct FolderGraph {
102    nodes: BTreeSet<FolderNode>,
103    edges: BTreeMap<FolderEdge, DependencyCount>,
104}
105
106impl FolderGraph {
107    pub fn new(nodes: BTreeSet<FolderNode>, edges: BTreeMap<FolderEdge, DependencyCount>) -> Result<Self> {
108        ensure!(
109            edges.keys().all(|edge| nodes.contains(edge.source()) && nodes.contains(edge.target())),
110            "Folder graph has an unknown dependency endpoint"
111        );
112        Ok(Self { nodes, edges })
113    }
114}
115
116/**
117
118```compile_fail
119use std::collections::BTreeSet;
120use std::path::PathBuf;
121use source_mesh_core::model::FileGraph;
122
123let files = BTreeSet::from([PathBuf::from("lib.rs")]);
124let graph = FileGraph::new(files, BTreeSet::new());
125```
126*/
127#[derive(PartialEq, Getters)]
128#[getset(get = "pub")]
129pub struct FileGraph {
130    files: BTreeSet<FileNode>,
131    edges: BTreeSet<FileEdge>,
132}
133
134impl FileGraph {
135    pub fn new(files: BTreeSet<FileNode>, edges: BTreeSet<FileEdge>) -> Result<Self> {
136        ensure!(
137            edges.iter().all(|edge| files.contains(edge.source()) && files.contains(edge.target())),
138            "File graph has an unknown dependency endpoint"
139        );
140        Ok(Self { files, edges })
141    }
142
143    #[must_use]
144    pub(crate) const fn from_files(files: BTreeSet<FileNode>) -> Self {
145        Self { files, edges: BTreeSet::new() }
146    }
147
148    pub(crate) fn insert_dependency(&mut self, dependency: FileEdge) {
149        assert!(
150            self.files.contains(dependency.source()) && self.files.contains(dependency.target()),
151            "File dependency endpoints must belong to the graph"
152        );
153        self.edges.insert(dependency);
154    }
155
156    #[must_use]
157    pub fn without_test_dependencies(mut self) -> Self {
158        self.edges.retain(|edge| edge.kind() == DependencyKind::Production);
159        self
160    }
161
162    pub fn within_root(mut self, root: &Path) -> Result<Self> {
163        let root = relative_directory_root(root)?;
164        self.files.retain(|file| file.directory().starts_with(&root));
165        self.edges.retain(|edge| self.files.contains(edge.source()) && self.files.contains(edge.target()));
166        Ok(self)
167    }
168
169    pub fn folders(&self, root: &Path, depth: Option<usize>, include_self: bool) -> Result<FolderGraph> {
170        let root = relative_directory_root(root)?;
171        let mut folder_graph = FolderGraph::default();
172        let mut file_folders = BTreeMap::new();
173        for file in &self.files {
174            let Ok(relative) = file.directory().strip_prefix(&root) else {
175                continue;
176            };
177            let directory_components = relative.components().take(depth.unwrap_or(usize::MAX));
178            let parts = directory_components.map(|part| part.as_os_str().to_str().context("Folder path is not UTF-8"));
179            let parts = parts.collect::<Result<Vec<_>>>()?;
180            let label = if parts.is_empty() { ".".into() } else { parts.join("/") };
181            let folder = FolderNode::new(label);
182            folder_graph.nodes.insert(folder.clone());
183            file_folders.insert(file, folder);
184        }
185        let mut folder_edges: BTreeMap<_, DependencyCount> = BTreeMap::new();
186        for edge in &self.edges {
187            let (source, target) = (edge.source(), edge.target());
188            if source == target {
189                continue;
190            }
191            if let (Some(source_folder), Some(target_folder)) = (file_folders.get(source), file_folders.get(target))
192                && (include_self || source_folder != target_folder)
193            {
194                folder_edges.entry((source_folder, target_folder, edge.kind())).or_default().increment();
195            }
196        }
197        folder_graph.edges = folder_edges.into_iter().map(|((source, target, kind), count)| {
198            (FolderEdge::new(source.clone(), target.clone(), kind), count)
199        }).collect();
200        Ok(folder_graph)
201    }
202}
203
204fn relative_directory_root(root: &Path) -> Result<PathBuf> {
205    ensure!(
206        root.components().all(|component| matches!(component, Component::Normal(_) | Component::CurDir)),
207        "--root must be a relative directory inside the indexed project (no '..')"
208    );
209    Ok(root.components().filter(|component| !matches!(component, Component::CurDir)).collect())
210}
211
212#[cfg(test)]
213mod tests {
214    use std::collections::BTreeMap;
215    use std::collections::BTreeSet;
216    use std::panic::AssertUnwindSafe;
217    use std::panic::catch_unwind;
218    use std::path::Path;
219    use std::path::PathBuf;
220
221    use anyhow::Result;
222    use claims::assert_ok;
223    use pretty_assertions::assert_eq;
224    use rstest::rstest;
225
226    use super::DependencyCount;
227    use super::DependencyKind;
228    use super::FileEdge;
229    use super::FileGraph;
230    use super::FileNode;
231    use super::FolderEdge;
232    use super::FolderGraph;
233    use super::FolderNode;
234    use crate::SourcePath;
235
236    #[rstest]
237    #[case(0, 1)]
238    #[case(7, 8)]
239    #[case(usize::MAX - 1, usize::MAX)]
240    fn test_dependency_count_increment(#[case] initial: usize, #[case] expected: usize) {
241        let mut system_under_test = DependencyCount::new(initial);
242
243        system_under_test.increment();
244
245        assert_eq!(expected, system_under_test.value(), "Dependency count did not increase by one");
246    }
247
248    #[test]
249    fn test_dependency_count_overflow() {
250        let mut system_under_test = DependencyCount::new(usize::MAX);
251
252        let result = catch_unwind(AssertUnwindSafe(|| system_under_test.increment()));
253
254        assert!(result.is_err(), "Dependency count overflow must violate the input-edge bound");
255        assert_eq!(usize::MAX, system_under_test.value(), "Overflow changed the dependency count");
256    }
257
258    fn file_graph_fixture() -> Result<(BTreeSet<FileNode>, BTreeSet<FileEdge>)> {
259        let source_directory = Path::new("src");
260        let service_module = FileNode::new(SourcePath::new(source_directory.join("api").join("service.rs"))?);
261        let http_module = FileNode::new(SourcePath::new(source_directory.join("api").join("http.rs"))?);
262        let routes_module = FileNode::new(SourcePath::new(source_directory.join("api").join("v1").join("routes.rs"))?);
263        let request_module = FileNode::new(SourcePath::new(source_directory.join("domain").join("request.rs"))?);
264        let rules_module = FileNode::new(SourcePath::new(source_directory.join("domain").join("rules.rs"))?);
265        let database_module = FileNode::new(SourcePath::new(source_directory.join("storage").join("db.rs"))?);
266        let calls_module = FileNode::new(SourcePath::new(source_directory.join("body_only").join("calls.rs"))?);
267        let files = BTreeSet::from([
268            FileNode::new(SourcePath::new(source_directory.join("lib.rs"))?),
269            FileNode::new(SourcePath::new(source_directory.join("api").join("mod.rs"))?),
270            service_module.clone(),
271            http_module.clone(),
272            FileNode::new(SourcePath::new(source_directory.join("api").join("v1").join("mod.rs"))?),
273            routes_module.clone(),
274            FileNode::new(SourcePath::new(source_directory.join("domain").join("mod.rs"))?),
275            request_module.clone(),
276            rules_module.clone(),
277            database_module.clone(),
278            FileNode::new(SourcePath::new(source_directory.join("body_only").join("mod.rs"))?),
279            calls_module.clone(),
280            FileNode::new(SourcePath::new(source_directory.join("isolated").join("mod.rs"))?),
281            FileNode::new(SourcePath::new(source_directory.join("isolated").join("sample.rs"))?),
282        ]);
283        let dependencies = BTreeSet::from([
284            FileEdge::new(service_module.clone(), http_module.clone(), DependencyKind::Production),
285            FileEdge::new(service_module, routes_module.clone(), DependencyKind::Production),
286            FileEdge::new(http_module.clone(), request_module.clone(), DependencyKind::Production),
287            FileEdge::new(http_module, database_module.clone(), DependencyKind::Production),
288            FileEdge::new(routes_module.clone(), request_module.clone(), DependencyKind::Production),
289            FileEdge::new(routes_module, database_module.clone(), DependencyKind::Production),
290            FileEdge::new(request_module, rules_module.clone(), DependencyKind::Production),
291            FileEdge::new(rules_module, database_module.clone(), DependencyKind::Production),
292            FileEdge::new(calls_module, database_module, DependencyKind::Production),
293        ]);
294        Ok((files, dependencies))
295    }
296
297    #[must_use]
298    fn folder_edges(values: &[(&str, &str, usize)], kind: DependencyKind) -> BTreeMap<FolderEdge, DependencyCount> {
299        values.iter().map(|&(source, destination, weight)| {
300            let edge = FolderEdge::new(FolderNode::new(source.into()), FolderNode::new(destination.into()), kind);
301            (edge, DependencyCount::new(weight))
302        }).collect()
303    }
304
305    #[must_use]
306    fn folder_nodes(values: &[&str]) -> BTreeSet<FolderNode> {
307        values.iter().map(|&label| FolderNode::new(label.into())).collect()
308    }
309
310    fn mixed_dependency_fixture() -> Result<(BTreeSet<FileNode>, BTreeSet<FileEdge>)> {
311        let source_directory = Path::new("src");
312        let http_module = FileNode::new(SourcePath::new(source_directory.join("api").join("http.rs"))?);
313        let routes_module = FileNode::new(SourcePath::new(source_directory.join("api").join("v1").join("routes.rs"))?);
314        let request_module = FileNode::new(SourcePath::new(source_directory.join("domain").join("request.rs"))?);
315        let checks_module = FileNode::new(SourcePath::new(source_directory.join("tests").join("checks.rs"))?);
316        let files = BTreeSet::from([
317            http_module.clone(),
318            routes_module.clone(),
319            request_module.clone(),
320            checks_module.clone(),
321            FileNode::new(SourcePath::new(source_directory.join("isolated").join("sample.rs"))?),
322        ]);
323        let dependencies = BTreeSet::from([
324            FileEdge::new(http_module.clone(), request_module.clone(), DependencyKind::Production),
325            FileEdge::new(routes_module.clone(), request_module.clone(), DependencyKind::Production),
326            FileEdge::new(http_module.clone(), request_module.clone(), DependencyKind::Test),
327            FileEdge::new(http_module.clone(), request_module.clone(), DependencyKind::Test),
328            FileEdge::new(routes_module, request_module.clone(), DependencyKind::Test),
329            FileEdge::new(request_module.clone(), http_module, DependencyKind::Test),
330            FileEdge::new(checks_module, request_module, DependencyKind::Test),
331        ]);
332        Ok((files, dependencies))
333    }
334
335    #[test]
336    fn test_physical_directories_and_isolated_files() {
337        let fixture = file_graph_fixture();
338        let (files, dependencies) = assert_ok!(fixture, "Physical-directory fixture paths must be valid");
339        let system_under_test = FileGraph::new(files, dependencies);
340        let system_under_test = assert_ok!(system_under_test, "Physical-directory fixture must form a valid file graph");
341        let expected_nodes = folder_nodes(&[".", "api", "api/v1", "body_only", "domain", "isolated", "storage"]);
342        let expected_edges = folder_edges(
343            &[
344                ("api", "api/v1", 1),
345                ("api", "domain", 1),
346                ("api", "storage", 1),
347                ("api/v1", "domain", 1),
348                ("api/v1", "storage", 1),
349                ("body_only", "storage", 1),
350                ("domain", "storage", 1),
351            ],
352            DependencyKind::Production,
353        );
354
355        let graph = system_under_test.folders(Path::new("src"), None, false);
356        let graph = assert_ok!(graph, "Physical directories must aggregate under the source root");
357
358        assert_eq!(&expected_nodes, graph.nodes(), "Physical directory nodes differ");
359        assert_eq!(&expected_edges, graph.edges(), "Physical directory dependencies differ");
360        assert!(!graph.nodes().contains(&FolderNode::new("persistence".into())), "Module name replaced physical folder");
361    }
362
363    #[rstest]
364    #[case(None)]
365    #[case(Some(2))]
366    #[case(Some(10))]
367    fn test_depth_beyond_existing_folders(#[case] depth: Option<usize>) {
368        let fixture = file_graph_fixture();
369        let (files, dependencies) = assert_ok!(fixture, "Depth fixture paths must be valid");
370        let system_under_test = FileGraph::new(files, dependencies);
371        let system_under_test = assert_ok!(system_under_test, "Depth fixture must form a valid file graph");
372        let complete_graph = system_under_test.folders(Path::new("src"), None, false);
373        let complete_graph = assert_ok!(complete_graph, "Unbounded folder aggregation must succeed");
374
375        let graph = system_under_test.folders(Path::new("src"), depth, false);
376        let graph = assert_ok!(graph, "Folder aggregation must succeed at depth {depth:?}");
377
378        assert_eq!(complete_graph.nodes(), graph.nodes(), "Depth {depth:?} changed nodes in a shallower graph");
379        assert_eq!(complete_graph.edges(), graph.edges(), "Depth {depth:?} changed dependencies in a shallower graph");
380    }
381
382    #[rstest]
383    #[case(0, &["."], &[])]
384    #[case(1, &[".", "api", "body_only", "domain", "isolated", "storage"], &[
385        ("api", "domain", 2), ("api", "storage", 2),
386        ("body_only", "storage", 1), ("domain", "storage", 1),
387    ])]
388    fn test_depth_grouping_and_distinct_file_pair_weights(
389        #[case] depth: usize,
390        #[case] expected_nodes: &[&str],
391        #[case] expected_edges: &[(&str, &str, usize)],
392    ) {
393        let fixture = file_graph_fixture();
394        let (files, dependencies) = assert_ok!(fixture, "Depth-grouping fixture paths must be valid");
395        let system_under_test = FileGraph::new(files, dependencies);
396        let system_under_test = assert_ok!(system_under_test, "Depth-grouping fixture must form a valid file graph");
397
398        let graph = system_under_test.folders(Path::new("src"), Some(depth), false);
399        let graph = assert_ok!(graph, "Folder grouping must succeed at depth {depth}");
400
401        assert_eq!(&folder_nodes(expected_nodes), graph.nodes(), "Depth {depth} grouped nodes incorrectly");
402        assert_eq!(&folder_edges(expected_edges, DependencyKind::Production), graph.edges(), "Depth {depth}: misgrouped edges");
403    }
404
405    #[rstest]
406    #[case(None, &[
407        ("api", "api", 1), ("api", "api/v1", 1),
408        ("api", "domain", 1), ("api", "storage", 1),
409        ("api/v1", "domain", 1), ("api/v1", "storage", 1),
410        ("body_only", "storage", 1), ("domain", "domain", 1),
411        ("domain", "storage", 1),
412    ])]
413    #[case(Some(0), &[(".", ".", 9)])]
414    #[case(Some(1), &[
415        ("api", "api", 2), ("api", "domain", 2),
416        ("api", "storage", 2), ("body_only", "storage", 1),
417        ("domain", "domain", 1), ("domain", "storage", 1),
418    ])]
419    fn test_self_edges_between_distinct_files(#[case] depth: Option<usize>, #[case] expected_edges: &[(&str, &str, usize)]) {
420        let fixture = file_graph_fixture();
421        let (files, mut dependencies) = assert_ok!(fixture, "Self-edge fixture paths must be valid");
422        let request_path = SourcePath::new(Path::new("src").join("domain").join("request.rs"));
423        let request_path = assert_ok!(request_path, "Self-dependent request module must have a valid source path");
424        let request_module = FileNode::new(request_path);
425        dependencies.insert(FileEdge::new(request_module.clone(), request_module, DependencyKind::Production));
426        let system_under_test = FileGraph::new(files, dependencies);
427        let system_under_test = assert_ok!(system_under_test, "Self-edge fixture must form a valid file graph");
428
429        let graph = system_under_test.folders(Path::new("src"), depth, true);
430        let graph = assert_ok!(graph, "Folder aggregation with self-edges must succeed at depth {depth:?}");
431
432        assert_eq!(
433            &folder_edges(expected_edges, DependencyKind::Production),
434            graph.edges(),
435            "Self-edge handling at depth {depth:?} differs"
436        );
437    }
438
439    #[test]
440    fn test_scope_boundaries_use_path_components() {
441        let fixture = file_graph_fixture();
442        let (mut files, mut dependencies) = assert_ok!(fixture, "Scope-boundary fixture paths must be valid");
443        let outside_path = SourcePath::new(Path::new("src2").join("outside.rs"));
444        let outside_path = assert_ok!(outside_path, "Outside module must have a valid project-relative source path");
445        let outside_module = FileNode::new(outside_path);
446        files.insert(outside_module.clone());
447        let service_path = SourcePath::new(Path::new("src").join("api").join("service.rs"));
448        let service_path = assert_ok!(service_path, "Service module must have a valid source path");
449        dependencies.insert(FileEdge::new(outside_module, FileNode::new(service_path), DependencyKind::Production));
450        let system_under_test = FileGraph::new(files, dependencies);
451        let system_under_test = assert_ok!(system_under_test, "Cross-scope dependencies must form a valid file graph");
452
453        let api_graph = system_under_test.folders(&Path::new("src").join("api"), None, false);
454        let api_graph = assert_ok!(api_graph, "API folder scope must aggregate successfully");
455        let source_graph = system_under_test.folders(Path::new("src"), None, false);
456        let source_graph = assert_ok!(source_graph, "Source folder scope must aggregate successfully");
457
458        assert_eq!(&folder_nodes(&[".", "v1"]), api_graph.nodes(), "API scope contains unexpected folders");
459        assert_eq!(&folder_edges(&[(".", "v1", 1)], DependencyKind::Production), api_graph.edges(), "API scope edges differ");
460        assert!(!source_graph.nodes().contains(&FolderNode::new("src2".into())), "Scope included a shared-prefix sibling");
461        assert_eq!(7, source_graph.edges().len(), "Scope changed the seven dependencies internal to the source tree");
462    }
463
464    #[rstest]
465    #[case(1, &["src"], &[])]
466    #[case(2, &["src", "src/api", "src/body_only", "src/domain", "src/isolated", "src/storage"], &[
467        ("src/api", "src/domain", 2), ("src/api", "src/storage", 2),
468        ("src/body_only", "src/storage", 1), ("src/domain", "src/storage", 1),
469    ])]
470    fn test_default_depth_origin(
471        #[case] depth: usize,
472        #[case] expected_nodes: &[&str],
473        #[case] expected_edges: &[(&str, &str, usize)],
474    ) {
475        let fixture = file_graph_fixture();
476        let (files, dependencies) = assert_ok!(fixture, "Default-root fixture paths must be valid");
477        let system_under_test = FileGraph::new(files, dependencies);
478        let system_under_test = assert_ok!(system_under_test, "Default-root fixture must form a valid file graph");
479
480        let graph = system_under_test.folders(Path::new(""), Some(depth), false);
481        let graph = assert_ok!(graph, "Default-root aggregation must succeed at depth {depth}");
482
483        assert_eq!(&folder_nodes(expected_nodes), graph.nodes(), "Default root produced incorrect nodes at depth {depth}");
484        assert_eq!(
485            &folder_edges(expected_edges, DependencyKind::Production),
486            graph.edges(),
487            "Default root produced incorrect dependencies at depth {depth}"
488        );
489    }
490
491    #[test]
492    fn test_isolated_folder_scope() {
493        let fixture = file_graph_fixture();
494        let (files, dependencies) = assert_ok!(fixture, "Isolated-folder fixture paths must be valid");
495        let system_under_test = FileGraph::new(files, dependencies);
496        let system_under_test = assert_ok!(system_under_test, "Isolated-folder fixture must form a valid file graph");
497
498        let graph = system_under_test.folders(&Path::new("src").join("isolated"), None, true);
499        let graph = assert_ok!(graph, "An isolated folder must be a valid aggregation scope");
500
501        assert_eq!(&folder_nodes(&["."]), graph.nodes(), "Isolated scope contains unexpected folders");
502        assert!(graph.edges().is_empty(), "An isolated folder acquired dependencies");
503    }
504
505    #[rstest]
506    #[case(None, &[("api", "domain", 1), ("api/v1", "domain", 1)], &[
507        ("api", "domain", 1), ("api/v1", "domain", 1), ("domain", "api", 1), ("tests", "domain", 1),
508    ])]
509    #[case(Some(1), &[("api", "domain", 2)], &[("api", "domain", 2), ("domain", "api", 1), ("tests", "domain", 1)])]
510    #[case(Some(0), &[(".", ".", 2)], &[(".", ".", 4)])]
511    fn test_dependency_kinds_deduplication_and_depth_aggregation(
512        #[case] depth: Option<usize>,
513        #[case] expected_production: &[(&str, &str, usize)],
514        #[case] expected_tests: &[(&str, &str, usize)],
515    ) {
516        let fixture = mixed_dependency_fixture();
517        let (files, dependencies) = assert_ok!(fixture, "Mixed-dependency fixture paths must be valid");
518        let system_under_test = FileGraph::new(files, dependencies);
519        let system_under_test = assert_ok!(system_under_test, "Mixed dependency kinds must form a valid file graph");
520        let mut expected_edges = folder_edges(expected_production, DependencyKind::Production);
521        expected_edges.extend(folder_edges(expected_tests, DependencyKind::Test));
522
523        let graph = system_under_test.folders(Path::new("src"), depth, true);
524        let graph = assert_ok!(graph, "Mixed dependency kinds must aggregate at depth {depth:?}");
525
526        assert_eq!(6, system_under_test.edges().len(), "Duplicate occurrences retained or dependency kinds merged");
527        assert_eq!(&expected_edges, graph.edges(), "Depth {depth:?} changed dependency kinds or distinct file-pair counts");
528    }
529
530    #[test]
531    fn test_many_file_pairs_aggregate_by_folder_and_dependency_kind() {
532        let mut files = BTreeSet::new();
533        let mut dependencies = BTreeSet::new();
534        for index in 0..16 {
535            let source_path = SourcePath::new(Path::new("src").join("api").join(format!("source_{index}.rs")));
536            let source_path = assert_ok!(source_path, "Repeated-edge source path must be valid");
537            let target_path = SourcePath::new(Path::new("src").join("domain").join(format!("target_{index}.rs")));
538            let target_path = assert_ok!(target_path, "Repeated-edge target path must be valid");
539            let source = FileNode::new(source_path);
540            let target = FileNode::new(target_path);
541            files.insert(source.clone());
542            files.insert(target.clone());
543            dependencies.insert(FileEdge::new(source.clone(), target.clone(), DependencyKind::Production));
544            if index < 8 {
545                dependencies.insert(FileEdge::new(source, target, DependencyKind::Test));
546            }
547        }
548        let system_under_test = FileGraph::new(files, dependencies);
549        let system_under_test = assert_ok!(system_under_test, "Repeated folder edges must form a valid file graph");
550        let mut expected_edges = folder_edges(&[("api", "domain", 16)], DependencyKind::Production);
551        expected_edges.extend(folder_edges(&[("api", "domain", 8)], DependencyKind::Test));
552
553        let graph = system_under_test.folders(Path::new("src"), Some(1), false);
554        let graph = assert_ok!(graph, "Repeated mixed-kind file dependencies must aggregate successfully");
555
556        assert_eq!(&folder_nodes(&["api", "domain"]), graph.nodes(), "Repeated endpoints changed folder membership");
557        assert_eq!(&expected_edges, graph.edges(), "Repeated endpoints lost weights or merged dependency kinds");
558    }
559
560    #[test]
561    fn test_dependency_kind_filtering() {
562        let fixture = mixed_dependency_fixture();
563        let (files, dependencies) = assert_ok!(fixture, "Dependency-filtering fixture paths must be valid");
564        let expected_files = files.clone();
565        let system_under_test = FileGraph::new(files, dependencies);
566        let system_under_test = assert_ok!(system_under_test, "Dependency-filtering fixture must form a valid file graph");
567        let expected_edges = folder_edges(&[("api", "domain", 1), ("api/v1", "domain", 1)], DependencyKind::Production);
568
569        let graph = system_under_test.without_test_dependencies();
570        let folders = graph.folders(Path::new("src"), None, false);
571        let folders = assert_ok!(folders, "Production-only dependencies must support folder aggregation");
572
573        assert_eq!(&expected_files, graph.files(), "Excluding test dependencies removed source files");
574        assert_eq!(2, graph.edges().len(), "Excluding test dependencies lost production edges or retained test edges");
575        assert_eq!(&expected_edges, folders.edges(), "Excluding test dependencies changed production dependencies or counts");
576        assert_eq!(
577            &folder_nodes(&["api", "api/v1", "domain", "isolated", "tests"]),
578            folders.nodes(),
579            "Excluding test dependencies removed isolated or test-only source folders"
580        );
581    }
582
583    #[rstest]
584    #[case(PathBuf::from("source.rs"), PathBuf::new())]
585    #[case(Path::new("src").join("source.rs"), PathBuf::from("src"))]
586    #[case(PathBuf::from("src//source.rs/"), PathBuf::from("src"))]
587    #[case(PathBuf::from("src/./source.rs"), PathBuf::from("src"))]
588    fn test_file_node_source_path(#[case] path: PathBuf, #[case] directory: PathBuf) {
589        let source_path = SourcePath::new(path.clone());
590        let source_path = assert_ok!(source_path, "File-node fixture path must be lexically valid: {path:?}");
591
592        let system_under_test = FileNode::new(source_path);
593
594        assert_eq!(path.as_os_str(), system_under_test.path().as_os_str(), "File node changed its source path");
595        assert_eq!(directory, system_under_test.directory(), "File node has the wrong parent directory");
596    }
597
598    #[rstest]
599    #[case("", true)]
600    #[case(".", true)]
601    #[case("source.rs", false)]
602    #[case("src", false)]
603    fn test_project_root_file_scope(#[case] root: &str, #[case] included: bool) {
604        let source_path = SourcePath::new(PathBuf::from("source.rs"));
605        let source_path = assert_ok!(source_path, "Root-level file must have a valid source path");
606        let file = FileNode::new(source_path);
607        let system_under_test = FileGraph::new(BTreeSet::from([file.clone()]), BTreeSet::new());
608        let system_under_test = assert_ok!(system_under_test, "A root-level file must form a valid graph");
609        let expected_folders = if included { folder_nodes(&["."]) } else { BTreeSet::new() };
610
611        let folders = system_under_test.folders(Path::new(root), None, false);
612        let folders = assert_ok!(folders, "Root-level folder aggregation must accept scope {root:?}");
613        let scoped_files = system_under_test.within_root(Path::new(root));
614        let scoped_files = assert_ok!(scoped_files, "File scoping must accept root {root:?}");
615
616        assert_eq!(included, scoped_files.files().contains(&file), "Root filtering changed root-level file membership");
617        assert_eq!(&expected_folders, folders.nodes(), "Folder aggregation changed root-level file membership");
618    }
619
620    #[rstest]
621    #[case("..")]
622    #[case("../src")]
623    #[case("/src")]
624    fn test_folder_scope_preconditions(#[case] root: &str) {
625        let fixture = file_graph_fixture();
626        let (files, dependencies) = assert_ok!(fixture, "Scope-precondition fixture paths must be valid");
627        let system_under_test = FileGraph::new(files, dependencies);
628        let system_under_test = assert_ok!(system_under_test, "Scope-precondition fixture must form a valid file graph");
629
630        let graph = system_under_test.folders(Path::new(root), None, false);
631
632        assert!(graph.is_err(), "Invalid folder scope was accepted: {root}");
633    }
634
635    #[rstest]
636    #[case("known.rs", "missing.rs")]
637    #[case("missing.rs", "known.rs")]
638    fn test_file_graph_endpoint_membership(#[case] source: &str, #[case] destination: &str) {
639        let known_path = SourcePath::new(PathBuf::from("known.rs"));
640        let known_path = assert_ok!(known_path, "Known graph file must have a valid source path");
641        let files = BTreeSet::from([FileNode::new(known_path)]);
642        let source_path = SourcePath::new(PathBuf::from(source));
643        let source_path = assert_ok!(source_path, "Dependency source path must be valid: {source}");
644        let destination_path = SourcePath::new(PathBuf::from(destination));
645        let destination_path = assert_ok!(destination_path, "Dependency destination path must be valid: {destination}");
646        let dependencies = BTreeSet::from([FileEdge::new(
647            FileNode::new(source_path), FileNode::new(destination_path), DependencyKind::Production,
648        )]);
649
650        let system_under_test = FileGraph::new(files, dependencies);
651
652        assert!(system_under_test.is_err(), "File graph accepted an unknown dependency endpoint");
653    }
654
655    #[rstest]
656    #[case("known.rs", "missing.rs")]
657    #[case("missing.rs", "known.rs")]
658    fn test_file_dependency_insertion_membership(#[case] source: &str, #[case] target: &str) {
659        let known_path = SourcePath::new(PathBuf::from("known.rs"));
660        let known_path = assert_ok!(known_path, "Known insertion-fixture file must have a valid source path");
661        let files = BTreeSet::from([FileNode::new(known_path)]);
662        let source_path = SourcePath::new(PathBuf::from(source));
663        let source_path = assert_ok!(source_path, "Inserted dependency source path must be valid: {source}");
664        let target_path = SourcePath::new(PathBuf::from(target));
665        let target_path = assert_ok!(target_path, "Inserted dependency target path must be valid: {target}");
666        let dependency = FileEdge::new(FileNode::new(source_path), FileNode::new(target_path), DependencyKind::Production);
667        let mut system_under_test = FileGraph::from_files(files.clone());
668
669        let result = catch_unwind(AssertUnwindSafe(|| system_under_test.insert_dependency(dependency)));
670
671        assert!(result.is_err(), "Inserting an unknown dependency endpoint must violate the graph invariant");
672        assert_eq!(&files, system_under_test.files(), "Invalid dependency insertion changed graph files");
673        assert!(system_under_test.edges().is_empty(), "Invalid dependency insertion changed graph edges");
674    }
675
676    #[rstest]
677    #[case("known", "missing")]
678    #[case("missing", "known")]
679    fn test_folder_graph_endpoint_membership(#[case] source: &str, #[case] destination: &str) {
680        let nodes = folder_nodes(&["known"]);
681        let dependencies = folder_edges(&[(source, destination, 1)], DependencyKind::Production);
682
683        let system_under_test = FolderGraph::new(nodes, dependencies);
684
685        assert!(system_under_test.is_err(), "Folder graph accepted an unknown dependency endpoint");
686    }
687}