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        for edge in &self.edges {
186            let (source, target) = (edge.source(), edge.target());
187            if source == target {
188                continue;
189            }
190            if let (Some(source_folder), Some(target_folder)) = (file_folders.get(source), file_folders.get(target))
191                && (include_self || source_folder != target_folder)
192            {
193                let folder_edge = FolderEdge::new(source_folder.clone(), target_folder.clone(), edge.kind());
194                folder_graph.edges.entry(folder_edge).or_default().increment();
195            }
196        }
197        Ok(folder_graph)
198    }
199}
200
201fn relative_directory_root(root: &Path) -> Result<PathBuf> {
202    ensure!(
203        root.components().all(|component| matches!(component, Component::Normal(_) | Component::CurDir)),
204        "--root must be a relative directory inside the indexed project (no '..')"
205    );
206    Ok(root.components().filter(|component| !matches!(component, Component::CurDir)).collect())
207}
208
209#[cfg(test)]
210mod tests {
211    use std::collections::BTreeMap;
212    use std::collections::BTreeSet;
213    use std::panic::AssertUnwindSafe;
214    use std::panic::catch_unwind;
215    use std::path::Path;
216    use std::path::PathBuf;
217
218    use anyhow::Result;
219    use claims::assert_ok;
220    use pretty_assertions::assert_eq;
221    use rstest::rstest;
222
223    use super::DependencyCount;
224    use super::DependencyKind;
225    use super::FileEdge;
226    use super::FileGraph;
227    use super::FileNode;
228    use super::FolderEdge;
229    use super::FolderGraph;
230    use super::FolderNode;
231    use crate::SourcePath;
232
233    #[rstest]
234    #[case(0, 1)]
235    #[case(7, 8)]
236    #[case(usize::MAX - 1, usize::MAX)]
237    fn test_dependency_count_increment(#[case] initial: usize, #[case] expected: usize) {
238        let mut system_under_test = DependencyCount::new(initial);
239
240        system_under_test.increment();
241
242        assert_eq!(expected, system_under_test.value(), "Dependency count did not increase by one");
243    }
244
245    #[test]
246    fn test_dependency_count_overflow() {
247        let mut system_under_test = DependencyCount::new(usize::MAX);
248
249        let result = catch_unwind(AssertUnwindSafe(|| system_under_test.increment()));
250
251        assert!(result.is_err(), "Dependency count overflow must violate the input-edge bound");
252        assert_eq!(usize::MAX, system_under_test.value(), "Overflow changed the dependency count");
253    }
254
255    fn file_graph_fixture() -> Result<(BTreeSet<FileNode>, BTreeSet<FileEdge>)> {
256        let source_directory = Path::new("src");
257        let service_module = FileNode::new(SourcePath::new(source_directory.join("api").join("service.rs"))?);
258        let http_module = FileNode::new(SourcePath::new(source_directory.join("api").join("http.rs"))?);
259        let routes_module = FileNode::new(SourcePath::new(source_directory.join("api").join("v1").join("routes.rs"))?);
260        let request_module = FileNode::new(SourcePath::new(source_directory.join("domain").join("request.rs"))?);
261        let rules_module = FileNode::new(SourcePath::new(source_directory.join("domain").join("rules.rs"))?);
262        let database_module = FileNode::new(SourcePath::new(source_directory.join("storage").join("db.rs"))?);
263        let calls_module = FileNode::new(SourcePath::new(source_directory.join("body_only").join("calls.rs"))?);
264        let files = BTreeSet::from([
265            FileNode::new(SourcePath::new(source_directory.join("lib.rs"))?),
266            FileNode::new(SourcePath::new(source_directory.join("api").join("mod.rs"))?),
267            service_module.clone(),
268            http_module.clone(),
269            FileNode::new(SourcePath::new(source_directory.join("api").join("v1").join("mod.rs"))?),
270            routes_module.clone(),
271            FileNode::new(SourcePath::new(source_directory.join("domain").join("mod.rs"))?),
272            request_module.clone(),
273            rules_module.clone(),
274            database_module.clone(),
275            FileNode::new(SourcePath::new(source_directory.join("body_only").join("mod.rs"))?),
276            calls_module.clone(),
277            FileNode::new(SourcePath::new(source_directory.join("isolated").join("mod.rs"))?),
278            FileNode::new(SourcePath::new(source_directory.join("isolated").join("sample.rs"))?),
279        ]);
280        let dependencies = BTreeSet::from([
281            FileEdge::new(service_module.clone(), http_module.clone(), DependencyKind::Production),
282            FileEdge::new(service_module, routes_module.clone(), DependencyKind::Production),
283            FileEdge::new(http_module.clone(), request_module.clone(), DependencyKind::Production),
284            FileEdge::new(http_module, database_module.clone(), DependencyKind::Production),
285            FileEdge::new(routes_module.clone(), request_module.clone(), DependencyKind::Production),
286            FileEdge::new(routes_module, database_module.clone(), DependencyKind::Production),
287            FileEdge::new(request_module, rules_module.clone(), DependencyKind::Production),
288            FileEdge::new(rules_module, database_module.clone(), DependencyKind::Production),
289            FileEdge::new(calls_module, database_module, DependencyKind::Production),
290        ]);
291        Ok((files, dependencies))
292    }
293
294    #[must_use]
295    fn folder_edges(values: &[(&str, &str, usize)], kind: DependencyKind) -> BTreeMap<FolderEdge, DependencyCount> {
296        values.iter().map(|&(source, destination, weight)| {
297            let edge = FolderEdge::new(FolderNode::new(source.into()), FolderNode::new(destination.into()), kind);
298            (edge, DependencyCount::new(weight))
299        }).collect()
300    }
301
302    #[must_use]
303    fn folder_nodes(values: &[&str]) -> BTreeSet<FolderNode> {
304        values.iter().map(|&label| FolderNode::new(label.into())).collect()
305    }
306
307    fn mixed_dependency_fixture() -> Result<(BTreeSet<FileNode>, BTreeSet<FileEdge>)> {
308        let source_directory = Path::new("src");
309        let http_module = FileNode::new(SourcePath::new(source_directory.join("api").join("http.rs"))?);
310        let routes_module = FileNode::new(SourcePath::new(source_directory.join("api").join("v1").join("routes.rs"))?);
311        let request_module = FileNode::new(SourcePath::new(source_directory.join("domain").join("request.rs"))?);
312        let checks_module = FileNode::new(SourcePath::new(source_directory.join("tests").join("checks.rs"))?);
313        let files = BTreeSet::from([
314            http_module.clone(),
315            routes_module.clone(),
316            request_module.clone(),
317            checks_module.clone(),
318            FileNode::new(SourcePath::new(source_directory.join("isolated").join("sample.rs"))?),
319        ]);
320        let dependencies = BTreeSet::from([
321            FileEdge::new(http_module.clone(), request_module.clone(), DependencyKind::Production),
322            FileEdge::new(routes_module.clone(), request_module.clone(), DependencyKind::Production),
323            FileEdge::new(http_module.clone(), request_module.clone(), DependencyKind::Test),
324            FileEdge::new(http_module.clone(), request_module.clone(), DependencyKind::Test),
325            FileEdge::new(routes_module, request_module.clone(), DependencyKind::Test),
326            FileEdge::new(request_module.clone(), http_module, DependencyKind::Test),
327            FileEdge::new(checks_module, request_module, DependencyKind::Test),
328        ]);
329        Ok((files, dependencies))
330    }
331
332    #[test]
333    fn test_physical_directories_and_isolated_files() {
334        let fixture = file_graph_fixture();
335        let (files, dependencies) = assert_ok!(fixture, "Physical-directory fixture paths must be valid");
336        let system_under_test = FileGraph::new(files, dependencies);
337        let system_under_test = assert_ok!(system_under_test, "Physical-directory fixture must form a valid file graph");
338        let expected_nodes = folder_nodes(&[".", "api", "api/v1", "body_only", "domain", "isolated", "storage"]);
339        let expected_edges = folder_edges(
340            &[
341                ("api", "api/v1", 1),
342                ("api", "domain", 1),
343                ("api", "storage", 1),
344                ("api/v1", "domain", 1),
345                ("api/v1", "storage", 1),
346                ("body_only", "storage", 1),
347                ("domain", "storage", 1),
348            ],
349            DependencyKind::Production,
350        );
351
352        let graph = system_under_test.folders(Path::new("src"), None, false);
353        let graph = assert_ok!(graph, "Physical directories must aggregate under the source root");
354
355        assert_eq!(&expected_nodes, graph.nodes(), "Physical directory nodes differ");
356        assert_eq!(&expected_edges, graph.edges(), "Physical directory dependencies differ");
357        assert!(!graph.nodes().contains(&FolderNode::new("persistence".into())), "Module name replaced physical folder");
358    }
359
360    #[rstest]
361    #[case(None)]
362    #[case(Some(2))]
363    #[case(Some(10))]
364    fn test_depth_beyond_existing_folders(#[case] depth: Option<usize>) {
365        let fixture = file_graph_fixture();
366        let (files, dependencies) = assert_ok!(fixture, "Depth fixture paths must be valid");
367        let system_under_test = FileGraph::new(files, dependencies);
368        let system_under_test = assert_ok!(system_under_test, "Depth fixture must form a valid file graph");
369        let complete_graph = system_under_test.folders(Path::new("src"), None, false);
370        let complete_graph = assert_ok!(complete_graph, "Unbounded folder aggregation must succeed");
371
372        let graph = system_under_test.folders(Path::new("src"), depth, false);
373        let graph = assert_ok!(graph, "Folder aggregation must succeed at depth {depth:?}");
374
375        assert_eq!(complete_graph.nodes(), graph.nodes(), "Depth {depth:?} changed nodes in a shallower graph");
376        assert_eq!(complete_graph.edges(), graph.edges(), "Depth {depth:?} changed dependencies in a shallower graph");
377    }
378
379    #[rstest]
380    #[case(0, &["."], &[])]
381    #[case(1, &[".", "api", "body_only", "domain", "isolated", "storage"], &[
382        ("api", "domain", 2), ("api", "storage", 2),
383        ("body_only", "storage", 1), ("domain", "storage", 1),
384    ])]
385    fn test_depth_grouping_and_distinct_file_pair_weights(
386        #[case] depth: usize,
387        #[case] expected_nodes: &[&str],
388        #[case] expected_edges: &[(&str, &str, usize)],
389    ) {
390        let fixture = file_graph_fixture();
391        let (files, dependencies) = assert_ok!(fixture, "Depth-grouping fixture paths must be valid");
392        let system_under_test = FileGraph::new(files, dependencies);
393        let system_under_test = assert_ok!(system_under_test, "Depth-grouping fixture must form a valid file graph");
394
395        let graph = system_under_test.folders(Path::new("src"), Some(depth), false);
396        let graph = assert_ok!(graph, "Folder grouping must succeed at depth {depth}");
397
398        assert_eq!(&folder_nodes(expected_nodes), graph.nodes(), "Depth {depth} grouped nodes incorrectly");
399        assert_eq!(&folder_edges(expected_edges, DependencyKind::Production), graph.edges(), "Depth {depth}: misgrouped edges");
400    }
401
402    #[rstest]
403    #[case(None, &[
404        ("api", "api", 1), ("api", "api/v1", 1),
405        ("api", "domain", 1), ("api", "storage", 1),
406        ("api/v1", "domain", 1), ("api/v1", "storage", 1),
407        ("body_only", "storage", 1), ("domain", "domain", 1),
408        ("domain", "storage", 1),
409    ])]
410    #[case(Some(0), &[(".", ".", 9)])]
411    #[case(Some(1), &[
412        ("api", "api", 2), ("api", "domain", 2),
413        ("api", "storage", 2), ("body_only", "storage", 1),
414        ("domain", "domain", 1), ("domain", "storage", 1),
415    ])]
416    fn test_self_edges_between_distinct_files(#[case] depth: Option<usize>, #[case] expected_edges: &[(&str, &str, usize)]) {
417        let fixture = file_graph_fixture();
418        let (files, mut dependencies) = assert_ok!(fixture, "Self-edge fixture paths must be valid");
419        let request_path = SourcePath::new(Path::new("src").join("domain").join("request.rs"));
420        let request_path = assert_ok!(request_path, "Self-dependent request module must have a valid source path");
421        let request_module = FileNode::new(request_path);
422        dependencies.insert(FileEdge::new(request_module.clone(), request_module, DependencyKind::Production));
423        let system_under_test = FileGraph::new(files, dependencies);
424        let system_under_test = assert_ok!(system_under_test, "Self-edge fixture must form a valid file graph");
425
426        let graph = system_under_test.folders(Path::new("src"), depth, true);
427        let graph = assert_ok!(graph, "Folder aggregation with self-edges must succeed at depth {depth:?}");
428
429        assert_eq!(
430            &folder_edges(expected_edges, DependencyKind::Production),
431            graph.edges(),
432            "Self-edge handling at depth {depth:?} differs"
433        );
434    }
435
436    #[test]
437    fn test_scope_boundaries_use_path_components() {
438        let fixture = file_graph_fixture();
439        let (mut files, mut dependencies) = assert_ok!(fixture, "Scope-boundary fixture paths must be valid");
440        let outside_path = SourcePath::new(Path::new("src2").join("outside.rs"));
441        let outside_path = assert_ok!(outside_path, "Outside module must have a valid project-relative source path");
442        let outside_module = FileNode::new(outside_path);
443        files.insert(outside_module.clone());
444        let service_path = SourcePath::new(Path::new("src").join("api").join("service.rs"));
445        let service_path = assert_ok!(service_path, "Service module must have a valid source path");
446        dependencies.insert(FileEdge::new(outside_module, FileNode::new(service_path), DependencyKind::Production));
447        let system_under_test = FileGraph::new(files, dependencies);
448        let system_under_test = assert_ok!(system_under_test, "Cross-scope dependencies must form a valid file graph");
449
450        let api_graph = system_under_test.folders(&Path::new("src").join("api"), None, false);
451        let api_graph = assert_ok!(api_graph, "API folder scope must aggregate successfully");
452        let source_graph = system_under_test.folders(Path::new("src"), None, false);
453        let source_graph = assert_ok!(source_graph, "Source folder scope must aggregate successfully");
454
455        assert_eq!(&folder_nodes(&[".", "v1"]), api_graph.nodes(), "API scope contains unexpected folders");
456        assert_eq!(&folder_edges(&[(".", "v1", 1)], DependencyKind::Production), api_graph.edges(), "API scope edges differ");
457        assert!(!source_graph.nodes().contains(&FolderNode::new("src2".into())), "Scope included a shared-prefix sibling");
458        assert_eq!(7, source_graph.edges().len(), "Scope changed the seven dependencies internal to the source tree");
459    }
460
461    #[rstest]
462    #[case(1, &["src"], &[])]
463    #[case(2, &["src", "src/api", "src/body_only", "src/domain", "src/isolated", "src/storage"], &[
464        ("src/api", "src/domain", 2), ("src/api", "src/storage", 2),
465        ("src/body_only", "src/storage", 1), ("src/domain", "src/storage", 1),
466    ])]
467    fn test_default_depth_origin(
468        #[case] depth: usize,
469        #[case] expected_nodes: &[&str],
470        #[case] expected_edges: &[(&str, &str, usize)],
471    ) {
472        let fixture = file_graph_fixture();
473        let (files, dependencies) = assert_ok!(fixture, "Default-root fixture paths must be valid");
474        let system_under_test = FileGraph::new(files, dependencies);
475        let system_under_test = assert_ok!(system_under_test, "Default-root fixture must form a valid file graph");
476
477        let graph = system_under_test.folders(Path::new(""), Some(depth), false);
478        let graph = assert_ok!(graph, "Default-root aggregation must succeed at depth {depth}");
479
480        assert_eq!(&folder_nodes(expected_nodes), graph.nodes(), "Default root produced incorrect nodes at depth {depth}");
481        assert_eq!(
482            &folder_edges(expected_edges, DependencyKind::Production),
483            graph.edges(),
484            "Default root produced incorrect dependencies at depth {depth}"
485        );
486    }
487
488    #[test]
489    fn test_isolated_folder_scope() {
490        let fixture = file_graph_fixture();
491        let (files, dependencies) = assert_ok!(fixture, "Isolated-folder fixture paths must be valid");
492        let system_under_test = FileGraph::new(files, dependencies);
493        let system_under_test = assert_ok!(system_under_test, "Isolated-folder fixture must form a valid file graph");
494
495        let graph = system_under_test.folders(&Path::new("src").join("isolated"), None, true);
496        let graph = assert_ok!(graph, "An isolated folder must be a valid aggregation scope");
497
498        assert_eq!(&folder_nodes(&["."]), graph.nodes(), "Isolated scope contains unexpected folders");
499        assert!(graph.edges().is_empty(), "An isolated folder acquired dependencies");
500    }
501
502    #[rstest]
503    #[case(None, &[("api", "domain", 1), ("api/v1", "domain", 1)], &[
504        ("api", "domain", 1), ("api/v1", "domain", 1), ("domain", "api", 1), ("tests", "domain", 1),
505    ])]
506    #[case(Some(1), &[("api", "domain", 2)], &[("api", "domain", 2), ("domain", "api", 1), ("tests", "domain", 1)])]
507    #[case(Some(0), &[(".", ".", 2)], &[(".", ".", 4)])]
508    fn test_dependency_kinds_deduplication_and_depth_aggregation(
509        #[case] depth: Option<usize>,
510        #[case] expected_production: &[(&str, &str, usize)],
511        #[case] expected_tests: &[(&str, &str, usize)],
512    ) {
513        let fixture = mixed_dependency_fixture();
514        let (files, dependencies) = assert_ok!(fixture, "Mixed-dependency fixture paths must be valid");
515        let system_under_test = FileGraph::new(files, dependencies);
516        let system_under_test = assert_ok!(system_under_test, "Mixed dependency kinds must form a valid file graph");
517        let mut expected_edges = folder_edges(expected_production, DependencyKind::Production);
518        expected_edges.extend(folder_edges(expected_tests, DependencyKind::Test));
519
520        let graph = system_under_test.folders(Path::new("src"), depth, true);
521        let graph = assert_ok!(graph, "Mixed dependency kinds must aggregate at depth {depth:?}");
522
523        assert_eq!(6, system_under_test.edges().len(), "Duplicate occurrences retained or dependency kinds merged");
524        assert_eq!(&expected_edges, graph.edges(), "Depth {depth:?} changed dependency kinds or distinct file-pair counts");
525    }
526
527    #[test]
528    fn test_dependency_kind_filtering() {
529        let fixture = mixed_dependency_fixture();
530        let (files, dependencies) = assert_ok!(fixture, "Dependency-filtering fixture paths must be valid");
531        let expected_files = files.clone();
532        let system_under_test = FileGraph::new(files, dependencies);
533        let system_under_test = assert_ok!(system_under_test, "Dependency-filtering fixture must form a valid file graph");
534        let expected_edges = folder_edges(&[("api", "domain", 1), ("api/v1", "domain", 1)], DependencyKind::Production);
535
536        let graph = system_under_test.without_test_dependencies();
537        let folders = graph.folders(Path::new("src"), None, false);
538        let folders = assert_ok!(folders, "Production-only dependencies must support folder aggregation");
539
540        assert_eq!(&expected_files, graph.files(), "Excluding test dependencies removed source files");
541        assert_eq!(2, graph.edges().len(), "Excluding test dependencies lost production edges or retained test edges");
542        assert_eq!(&expected_edges, folders.edges(), "Excluding test dependencies changed production dependencies or counts");
543        assert_eq!(
544            &folder_nodes(&["api", "api/v1", "domain", "isolated", "tests"]),
545            folders.nodes(),
546            "Excluding test dependencies removed isolated or test-only source folders"
547        );
548    }
549
550    #[rstest]
551    #[case(PathBuf::from("source.rs"), PathBuf::new())]
552    #[case(Path::new("src").join("source.rs"), PathBuf::from("src"))]
553    #[case(PathBuf::from("src//source.rs/"), PathBuf::from("src"))]
554    #[case(PathBuf::from("src/./source.rs"), PathBuf::from("src"))]
555    fn test_file_node_source_path(#[case] path: PathBuf, #[case] directory: PathBuf) {
556        let source_path = SourcePath::new(path.clone());
557        let source_path = assert_ok!(source_path, "File-node fixture path must be lexically valid: {path:?}");
558
559        let system_under_test = FileNode::new(source_path);
560
561        assert_eq!(path.as_os_str(), system_under_test.path().as_os_str(), "File node changed its source path");
562        assert_eq!(directory, system_under_test.directory(), "File node has the wrong parent directory");
563    }
564
565    #[rstest]
566    #[case("", true)]
567    #[case(".", true)]
568    #[case("source.rs", false)]
569    #[case("src", false)]
570    fn test_project_root_file_scope(#[case] root: &str, #[case] included: bool) {
571        let source_path = SourcePath::new(PathBuf::from("source.rs"));
572        let source_path = assert_ok!(source_path, "Root-level file must have a valid source path");
573        let file = FileNode::new(source_path);
574        let system_under_test = FileGraph::new(BTreeSet::from([file.clone()]), BTreeSet::new());
575        let system_under_test = assert_ok!(system_under_test, "A root-level file must form a valid graph");
576        let expected_folders = if included { folder_nodes(&["."]) } else { BTreeSet::new() };
577
578        let folders = system_under_test.folders(Path::new(root), None, false);
579        let folders = assert_ok!(folders, "Root-level folder aggregation must accept scope {root:?}");
580        let scoped_files = system_under_test.within_root(Path::new(root));
581        let scoped_files = assert_ok!(scoped_files, "File scoping must accept root {root:?}");
582
583        assert_eq!(included, scoped_files.files().contains(&file), "Root filtering changed root-level file membership");
584        assert_eq!(&expected_folders, folders.nodes(), "Folder aggregation changed root-level file membership");
585    }
586
587    #[rstest]
588    #[case("..")]
589    #[case("../src")]
590    #[case("/src")]
591    fn test_folder_scope_preconditions(#[case] root: &str) {
592        let fixture = file_graph_fixture();
593        let (files, dependencies) = assert_ok!(fixture, "Scope-precondition fixture paths must be valid");
594        let system_under_test = FileGraph::new(files, dependencies);
595        let system_under_test = assert_ok!(system_under_test, "Scope-precondition fixture must form a valid file graph");
596
597        let graph = system_under_test.folders(Path::new(root), None, false);
598
599        assert!(graph.is_err(), "Invalid folder scope was accepted: {root}");
600    }
601
602    #[rstest]
603    #[case("known.rs", "missing.rs")]
604    #[case("missing.rs", "known.rs")]
605    fn test_file_graph_endpoint_membership(#[case] source: &str, #[case] destination: &str) {
606        let known_path = SourcePath::new(PathBuf::from("known.rs"));
607        let known_path = assert_ok!(known_path, "Known graph file must have a valid source path");
608        let files = BTreeSet::from([FileNode::new(known_path)]);
609        let source_path = SourcePath::new(PathBuf::from(source));
610        let source_path = assert_ok!(source_path, "Dependency source path must be valid: {source}");
611        let destination_path = SourcePath::new(PathBuf::from(destination));
612        let destination_path = assert_ok!(destination_path, "Dependency destination path must be valid: {destination}");
613        let dependencies = BTreeSet::from([FileEdge::new(
614            FileNode::new(source_path), FileNode::new(destination_path), DependencyKind::Production,
615        )]);
616
617        let system_under_test = FileGraph::new(files, dependencies);
618
619        assert!(system_under_test.is_err(), "File graph accepted an unknown dependency endpoint");
620    }
621
622    #[rstest]
623    #[case("known.rs", "missing.rs")]
624    #[case("missing.rs", "known.rs")]
625    fn test_file_dependency_insertion_membership(#[case] source: &str, #[case] target: &str) {
626        let known_path = SourcePath::new(PathBuf::from("known.rs"));
627        let known_path = assert_ok!(known_path, "Known insertion-fixture file must have a valid source path");
628        let files = BTreeSet::from([FileNode::new(known_path)]);
629        let source_path = SourcePath::new(PathBuf::from(source));
630        let source_path = assert_ok!(source_path, "Inserted dependency source path must be valid: {source}");
631        let target_path = SourcePath::new(PathBuf::from(target));
632        let target_path = assert_ok!(target_path, "Inserted dependency target path must be valid: {target}");
633        let dependency = FileEdge::new(FileNode::new(source_path), FileNode::new(target_path), DependencyKind::Production);
634        let mut system_under_test = FileGraph::from_files(files.clone());
635
636        let result = catch_unwind(AssertUnwindSafe(|| system_under_test.insert_dependency(dependency)));
637
638        assert!(result.is_err(), "Inserting an unknown dependency endpoint must violate the graph invariant");
639        assert_eq!(&files, system_under_test.files(), "Invalid dependency insertion changed graph files");
640        assert!(system_under_test.edges().is_empty(), "Invalid dependency insertion changed graph edges");
641    }
642
643    #[rstest]
644    #[case("known", "missing")]
645    #[case("missing", "known")]
646    fn test_folder_graph_endpoint_membership(#[case] source: &str, #[case] destination: &str) {
647        let nodes = folder_nodes(&["known"]);
648        let dependencies = folder_edges(&[(source, destination, 1)], DependencyKind::Production);
649
650        let system_under_test = FolderGraph::new(nodes, dependencies);
651
652        assert!(system_under_test.is_err(), "Folder graph accepted an unknown dependency endpoint");
653    }
654}