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