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 claims::assert_ok;
231    use pretty_assertions::assert_eq;
232    use rstest::rstest;
233
234    use super::DependencyCount;
235    use super::DependencyKind;
236    use super::FileEdge;
237    use super::FileGraph;
238    use super::FileNode;
239    use super::FolderEdge;
240    use super::FolderGraph;
241    use super::FolderNode;
242    use crate::SourcePath;
243    use crate::graph::exclusions::Exclusions;
244
245    #[rstest]
246    #[case(0, 1)]
247    #[case(7, 8)]
248    #[case(usize::MAX - 1, usize::MAX)]
249    fn test_dependency_count_increment(#[case] initial: usize, #[case] expected: usize) {
250        let mut system_under_test = DependencyCount::new(initial);
251
252        system_under_test.increment();
253
254        assert_eq!(expected, system_under_test.value(), "Dependency count did not increase by one");
255    }
256
257    #[test]
258    fn test_dependency_count_overflow() {
259        let mut system_under_test = DependencyCount::new(usize::MAX);
260
261        let result = catch_unwind(AssertUnwindSafe(|| system_under_test.increment()));
262
263        assert!(result.is_err(), "Dependency count overflow must violate the input-edge bound");
264        assert_eq!(usize::MAX, system_under_test.value(), "Overflow changed the dependency count");
265    }
266
267    fn file_graph_fixture() -> Result<(BTreeSet<FileNode>, BTreeSet<FileEdge>)> {
268        let source_directory = Path::new("src");
269        let service_module = FileNode::new(SourcePath::new(source_directory.join("api").join("service.rs"))?);
270        let http_module = FileNode::new(SourcePath::new(source_directory.join("api").join("http.rs"))?);
271        let routes_module = FileNode::new(SourcePath::new(source_directory.join("api").join("v1").join("routes.rs"))?);
272        let request_module = FileNode::new(SourcePath::new(source_directory.join("domain").join("request.rs"))?);
273        let rules_module = FileNode::new(SourcePath::new(source_directory.join("domain").join("rules.rs"))?);
274        let database_module = FileNode::new(SourcePath::new(source_directory.join("storage").join("db.rs"))?);
275        let calls_module = FileNode::new(SourcePath::new(source_directory.join("body_only").join("calls.rs"))?);
276        let files = BTreeSet::from([
277            FileNode::new(SourcePath::new(source_directory.join("lib.rs"))?),
278            FileNode::new(SourcePath::new(source_directory.join("api").join("mod.rs"))?),
279            service_module.clone(),
280            http_module.clone(),
281            FileNode::new(SourcePath::new(source_directory.join("api").join("v1").join("mod.rs"))?),
282            routes_module.clone(),
283            FileNode::new(SourcePath::new(source_directory.join("domain").join("mod.rs"))?),
284            request_module.clone(),
285            rules_module.clone(),
286            database_module.clone(),
287            FileNode::new(SourcePath::new(source_directory.join("body_only").join("mod.rs"))?),
288            calls_module.clone(),
289            FileNode::new(SourcePath::new(source_directory.join("isolated").join("mod.rs"))?),
290            FileNode::new(SourcePath::new(source_directory.join("isolated").join("sample.rs"))?),
291        ]);
292        let dependencies = BTreeSet::from([
293            FileEdge::new(service_module.clone(), http_module.clone(), DependencyKind::Production),
294            FileEdge::new(service_module, routes_module.clone(), DependencyKind::Production),
295            FileEdge::new(http_module.clone(), request_module.clone(), DependencyKind::Production),
296            FileEdge::new(http_module, database_module.clone(), DependencyKind::Production),
297            FileEdge::new(routes_module.clone(), request_module.clone(), DependencyKind::Production),
298            FileEdge::new(routes_module, database_module.clone(), DependencyKind::Production),
299            FileEdge::new(request_module, rules_module.clone(), DependencyKind::Production),
300            FileEdge::new(rules_module, database_module.clone(), DependencyKind::Production),
301            FileEdge::new(calls_module, database_module, DependencyKind::Production),
302        ]);
303        Ok((files, dependencies))
304    }
305
306    #[must_use]
307    fn folder_edges(values: &[(&str, &str, usize)], kind: DependencyKind) -> BTreeMap<FolderEdge, DependencyCount> {
308        values.iter().map(|&(source, destination, weight)| {
309            let edge = FolderEdge::new(FolderNode::new(source.into()), FolderNode::new(destination.into()), kind);
310            (edge, DependencyCount::new(weight))
311        }).collect()
312    }
313
314    #[must_use]
315    fn folder_nodes(values: &[&str]) -> BTreeSet<FolderNode> {
316        values.iter().map(|&label| FolderNode::new(label.into())).collect()
317    }
318
319    fn mixed_dependency_fixture() -> Result<(BTreeSet<FileNode>, BTreeSet<FileEdge>)> {
320        let source_directory = Path::new("src");
321        let http_module = FileNode::new(SourcePath::new(source_directory.join("api").join("http.rs"))?);
322        let routes_module = FileNode::new(SourcePath::new(source_directory.join("api").join("v1").join("routes.rs"))?);
323        let request_module = FileNode::new(SourcePath::new(source_directory.join("domain").join("request.rs"))?);
324        let checks_module = FileNode::new(SourcePath::new(source_directory.join("tests").join("checks.rs"))?);
325        let files = BTreeSet::from([
326            http_module.clone(),
327            routes_module.clone(),
328            request_module.clone(),
329            checks_module.clone(),
330            FileNode::new(SourcePath::new(source_directory.join("isolated").join("sample.rs"))?),
331        ]);
332        let dependencies = BTreeSet::from([
333            FileEdge::new(http_module.clone(), request_module.clone(), DependencyKind::Production),
334            FileEdge::new(routes_module.clone(), request_module.clone(), DependencyKind::Production),
335            FileEdge::new(http_module.clone(), request_module.clone(), DependencyKind::Test),
336            FileEdge::new(http_module.clone(), request_module.clone(), DependencyKind::Test),
337            FileEdge::new(routes_module, request_module.clone(), DependencyKind::Test),
338            FileEdge::new(request_module.clone(), http_module, DependencyKind::Test),
339            FileEdge::new(checks_module, request_module, DependencyKind::Test),
340        ]);
341        Ok((files, dependencies))
342    }
343
344    #[test]
345    fn test_physical_directories_and_isolated_files() {
346        let fixture = file_graph_fixture();
347        let (files, dependencies) = assert_ok!(fixture, "Physical-directory fixture paths must be valid");
348        let system_under_test = FileGraph::new(files, dependencies);
349        let system_under_test = assert_ok!(system_under_test, "Physical-directory fixture must form a valid file graph");
350        let expected_nodes = folder_nodes(&[".", "api", "api/v1", "body_only", "domain", "isolated", "storage"]);
351        let expected_edges = folder_edges(
352            &[
353                ("api", "api/v1", 1),
354                ("api", "domain", 1),
355                ("api", "storage", 1),
356                ("api/v1", "domain", 1),
357                ("api/v1", "storage", 1),
358                ("body_only", "storage", 1),
359                ("domain", "storage", 1),
360            ],
361            DependencyKind::Production,
362        );
363
364        let graph = system_under_test.folders(Path::new("src"), None, false);
365        let graph = assert_ok!(graph, "Physical directories must aggregate under the source root");
366
367        assert_eq!(&expected_nodes, graph.nodes(), "Physical directory nodes differ");
368        assert_eq!(&expected_edges, graph.edges(), "Physical directory dependencies differ");
369        assert!(!graph.nodes().contains(&FolderNode::new("persistence".into())), "Module name replaced physical folder");
370    }
371
372    #[rstest]
373    #[case(None)]
374    #[case(Some(2))]
375    #[case(Some(10))]
376    fn test_depth_beyond_existing_folders(#[case] depth: Option<usize>) {
377        let fixture = file_graph_fixture();
378        let (files, dependencies) = assert_ok!(fixture, "Depth fixture paths must be valid");
379        let system_under_test = FileGraph::new(files, dependencies);
380        let system_under_test = assert_ok!(system_under_test, "Depth fixture must form a valid file graph");
381        let complete_graph = system_under_test.folders(Path::new("src"), None, false);
382        let complete_graph = assert_ok!(complete_graph, "Unbounded folder aggregation must succeed");
383
384        let graph = system_under_test.folders(Path::new("src"), depth, false);
385        let graph = assert_ok!(graph, "Folder aggregation must succeed at depth {depth:?}");
386
387        assert_eq!(complete_graph.nodes(), graph.nodes(), "Depth {depth:?} changed nodes in a shallower graph");
388        assert_eq!(complete_graph.edges(), graph.edges(), "Depth {depth:?} changed dependencies in a shallower graph");
389    }
390
391    #[rstest]
392    #[case(
393        0, &["."], &[],
394    )]
395    #[case(
396        1, &[".", "api", "body_only", "domain", "isolated", "storage"], &[
397            ("api", "domain", 2), ("api", "storage", 2),
398            ("body_only", "storage", 1), ("domain", "storage", 1),
399        ],
400    )]
401    fn test_depth_grouping_and_distinct_file_pair_weights(
402        #[case] depth: usize,
403        #[case] expected_nodes: &[&str],
404        #[case] expected_edges: &[(&str, &str, usize)],
405    ) {
406        let fixture = file_graph_fixture();
407        let (files, dependencies) = assert_ok!(fixture, "Depth-grouping fixture paths must be valid");
408        let system_under_test = FileGraph::new(files, dependencies);
409        let system_under_test = assert_ok!(system_under_test, "Depth-grouping fixture must form a valid file graph");
410
411        let graph = system_under_test.folders(Path::new("src"), Some(depth), false);
412        let graph = assert_ok!(graph, "Folder grouping must succeed at depth {depth}");
413
414        assert_eq!(&folder_nodes(expected_nodes), graph.nodes(), "Depth {depth} grouped nodes incorrectly");
415        assert_eq!(&folder_edges(expected_edges, DependencyKind::Production), graph.edges(), "Depth {depth}: misgrouped edges");
416    }
417
418    #[rstest]
419    #[case(
420        None, &[
421            ("api", "api", 1), ("api", "api/v1", 1),
422            ("api", "domain", 1), ("api", "storage", 1),
423            ("api/v1", "domain", 1), ("api/v1", "storage", 1),
424            ("body_only", "storage", 1), ("domain", "domain", 1),
425            ("domain", "storage", 1),
426        ],
427    )]
428    #[case(
429        Some(0), &[(".", ".", 9)],
430    )]
431    #[case(
432        Some(1), &[
433            ("api", "api", 2), ("api", "domain", 2),
434            ("api", "storage", 2), ("body_only", "storage", 1),
435            ("domain", "domain", 1), ("domain", "storage", 1),
436        ],
437    )]
438    fn test_self_edges_between_distinct_files(#[case] depth: Option<usize>, #[case] expected_edges: &[(&str, &str, usize)]) {
439        let fixture = file_graph_fixture();
440        let (files, mut dependencies) = assert_ok!(fixture, "Self-edge fixture paths must be valid");
441        let request_path = SourcePath::new(Path::new("src").join("domain").join("request.rs"));
442        let request_path = assert_ok!(request_path, "Self-dependent request module must have a valid source path");
443        let request_module = FileNode::new(request_path);
444        dependencies.insert(FileEdge::new(request_module.clone(), request_module, DependencyKind::Production));
445        let system_under_test = FileGraph::new(files, dependencies);
446        let system_under_test = assert_ok!(system_under_test, "Self-edge fixture must form a valid file graph");
447
448        let graph = system_under_test.folders(Path::new("src"), depth, true);
449        let graph = assert_ok!(graph, "Folder aggregation with self-edges must succeed at depth {depth:?}");
450
451        assert_eq!(
452            &folder_edges(expected_edges, DependencyKind::Production),
453            graph.edges(),
454            "Self-edge handling at depth {depth:?} differs"
455        );
456    }
457
458    #[test]
459    fn test_scope_boundaries_use_path_components() {
460        let fixture = file_graph_fixture();
461        let (mut files, mut dependencies) = assert_ok!(fixture, "Scope-boundary fixture paths must be valid");
462        let outside_path = SourcePath::new(Path::new("src2").join("outside.rs"));
463        let outside_path = assert_ok!(outside_path, "Outside module must have a valid project-relative source path");
464        let outside_module = FileNode::new(outside_path);
465        files.insert(outside_module.clone());
466        let service_path = SourcePath::new(Path::new("src").join("api").join("service.rs"));
467        let service_path = assert_ok!(service_path, "Service module must have a valid source path");
468        dependencies.insert(FileEdge::new(outside_module, FileNode::new(service_path), DependencyKind::Production));
469        let system_under_test = FileGraph::new(files, dependencies);
470        let system_under_test = assert_ok!(system_under_test, "Cross-scope dependencies must form a valid file graph");
471
472        let api_graph = system_under_test.folders(&Path::new("src").join("api"), None, false);
473        let api_graph = assert_ok!(api_graph, "API folder scope must aggregate successfully");
474        let source_graph = system_under_test.folders(Path::new("src"), None, false);
475        let source_graph = assert_ok!(source_graph, "Source folder scope must aggregate successfully");
476
477        assert_eq!(&folder_nodes(&[".", "v1"]), api_graph.nodes(), "API scope contains unexpected folders");
478        assert_eq!(&folder_edges(&[(".", "v1", 1)], DependencyKind::Production), api_graph.edges(), "API scope edges differ");
479        assert!(!source_graph.nodes().contains(&FolderNode::new("src2".into())), "Scope included a shared-prefix sibling");
480        assert_eq!(7, source_graph.edges().len(), "Scope changed the seven dependencies internal to the source tree");
481    }
482
483    #[rstest]
484    #[case(
485        1, &["src"], &[],
486    )]
487    #[case(
488        2, &["src", "src/api", "src/body_only", "src/domain", "src/isolated", "src/storage"], &[
489            ("src/api", "src/domain", 2), ("src/api", "src/storage", 2),
490            ("src/body_only", "src/storage", 1), ("src/domain", "src/storage", 1),
491        ],
492    )]
493    fn test_default_depth_origin(
494        #[case] depth: usize,
495        #[case] expected_nodes: &[&str],
496        #[case] expected_edges: &[(&str, &str, usize)],
497    ) {
498        let fixture = file_graph_fixture();
499        let (files, dependencies) = assert_ok!(fixture, "Default-root fixture paths must be valid");
500        let system_under_test = FileGraph::new(files, dependencies);
501        let system_under_test = assert_ok!(system_under_test, "Default-root fixture must form a valid file graph");
502
503        let graph = system_under_test.folders(Path::new(""), Some(depth), false);
504        let graph = assert_ok!(graph, "Default-root aggregation must succeed at depth {depth}");
505
506        assert_eq!(&folder_nodes(expected_nodes), graph.nodes(), "Default root produced incorrect nodes at depth {depth}");
507        assert_eq!(
508            &folder_edges(expected_edges, DependencyKind::Production),
509            graph.edges(),
510            "Default root produced incorrect dependencies at depth {depth}"
511        );
512    }
513
514    #[test]
515    fn test_isolated_folder_scope() {
516        let fixture = file_graph_fixture();
517        let (files, dependencies) = assert_ok!(fixture, "Isolated-folder fixture paths must be valid");
518        let system_under_test = FileGraph::new(files, dependencies);
519        let system_under_test = assert_ok!(system_under_test, "Isolated-folder fixture must form a valid file graph");
520
521        let graph = system_under_test.folders(&Path::new("src").join("isolated"), None, true);
522        let graph = assert_ok!(graph, "An isolated folder must be a valid aggregation scope");
523
524        assert_eq!(&folder_nodes(&["."]), graph.nodes(), "Isolated scope contains unexpected folders");
525        assert!(graph.edges().is_empty(), "An isolated folder acquired dependencies");
526    }
527
528    #[rstest]
529    #[case(
530        None, &[("api", "domain", 1), ("api/v1", "domain", 1)], &[
531            ("api", "domain", 1), ("api/v1", "domain", 1), ("domain", "api", 1), ("tests", "domain", 1),
532        ],
533    )]
534    #[case(
535        Some(1), &[("api", "domain", 2)], &[("api", "domain", 2), ("domain", "api", 1), ("tests", "domain", 1)],
536    )]
537    #[case(
538        Some(0), &[(".", ".", 2)], &[(".", ".", 4)],
539    )]
540    fn test_dependency_kinds_deduplication_and_depth_aggregation(
541        #[case] depth: Option<usize>,
542        #[case] expected_production: &[(&str, &str, usize)],
543        #[case] expected_tests: &[(&str, &str, usize)],
544    ) {
545        let fixture = mixed_dependency_fixture();
546        let (files, dependencies) = assert_ok!(fixture, "Mixed-dependency fixture paths must be valid");
547        let system_under_test = FileGraph::new(files, dependencies);
548        let system_under_test = assert_ok!(system_under_test, "Mixed dependency kinds must form a valid file graph");
549        let mut expected_edges = folder_edges(expected_production, DependencyKind::Production);
550        expected_edges.extend(folder_edges(expected_tests, DependencyKind::Test));
551
552        let graph = system_under_test.folders(Path::new("src"), depth, true);
553        let graph = assert_ok!(graph, "Mixed dependency kinds must aggregate at depth {depth:?}");
554
555        assert_eq!(6, system_under_test.edges().len(), "Duplicate occurrences retained or dependency kinds merged");
556        assert_eq!(&expected_edges, graph.edges(), "Depth {depth:?} changed dependency kinds or distinct file-pair counts");
557    }
558
559    #[test]
560    fn test_many_file_pairs_aggregate_by_folder_and_dependency_kind() {
561        let mut files = BTreeSet::new();
562        let mut dependencies = BTreeSet::new();
563        for index in 0..16 {
564            let source_path = SourcePath::new(Path::new("src").join("api").join(format!("source_{index}.rs")));
565            let source_path = assert_ok!(source_path, "Repeated-edge source path must be valid");
566            let target_path = SourcePath::new(Path::new("src").join("domain").join(format!("target_{index}.rs")));
567            let target_path = assert_ok!(target_path, "Repeated-edge target path must be valid");
568            let source = FileNode::new(source_path);
569            let target = FileNode::new(target_path);
570            files.insert(source.clone());
571            files.insert(target.clone());
572            dependencies.insert(FileEdge::new(source.clone(), target.clone(), DependencyKind::Production));
573            if index < 8 {
574                dependencies.insert(FileEdge::new(source, target, DependencyKind::Test));
575            }
576        }
577        let system_under_test = FileGraph::new(files, dependencies);
578        let system_under_test = assert_ok!(system_under_test, "Repeated folder edges must form a valid file graph");
579        let mut expected_edges = folder_edges(&[("api", "domain", 16)], DependencyKind::Production);
580        expected_edges.extend(folder_edges(&[("api", "domain", 8)], DependencyKind::Test));
581
582        let graph = system_under_test.folders(Path::new("src"), Some(1), false);
583        let graph = assert_ok!(graph, "Repeated mixed-kind file dependencies must aggregate successfully");
584
585        assert_eq!(&folder_nodes(&["api", "domain"]), graph.nodes(), "Repeated endpoints changed folder membership");
586        assert_eq!(&expected_edges, graph.edges(), "Repeated endpoints lost weights or merged dependency kinds");
587    }
588
589    #[test]
590    fn test_dependency_kind_filtering() {
591        let fixture = mixed_dependency_fixture();
592        let (files, dependencies) = assert_ok!(fixture, "Dependency-filtering fixture paths must be valid");
593        let expected_files = files.clone();
594        let system_under_test = FileGraph::new(files, dependencies);
595        let system_under_test = assert_ok!(system_under_test, "Dependency-filtering fixture must form a valid file graph");
596        let expected_edges = folder_edges(&[("api", "domain", 1), ("api/v1", "domain", 1)], DependencyKind::Production);
597        let expected_nodes = folder_nodes(&["api", "api/v1", "domain", "isolated", "tests"]);
598
599        let graph = system_under_test.without_test_dependencies();
600        let folders = graph.folders(Path::new("src"), None, false);
601        let folders = assert_ok!(folders, "Production-only dependencies must support folder aggregation");
602
603        assert_eq!(&expected_files, graph.files(), "Excluding test dependencies removed source files");
604        assert_eq!(2, graph.edges().len(), "Excluding test dependencies lost production edges or retained test edges");
605        assert_eq!(&expected_edges, folders.edges(), "Excluding test dependencies changed production dependencies or counts");
606        assert_eq!(&expected_nodes, folders.nodes(), "Excluding test dependencies removed isolated or test-only source folders");
607    }
608
609    fn exclusions_fixture(patterns: &[&str]) -> Result<Exclusions> {
610        Exclusions::new(&patterns.iter().map(|pattern| (*pattern).to_owned()).collect::<Vec<_>>())
611    }
612
613    #[rstest]
614    #[case(&[])]
615    #[case(&["missing/**"])]
616    fn test_file_exclusions_without_matches(#[case] patterns: &[&str]) {
617        let fixture = mixed_dependency_fixture();
618        let (files, dependencies) = assert_ok!(fixture, "Unmatched-exclusion fixture paths must be valid");
619        let system_under_test = FileGraph::new(files, dependencies);
620        let system_under_test = assert_ok!(system_under_test, "Unmatched-exclusion fixture must form a valid graph");
621        let expected = mixed_dependency_fixture();
622        let (expected_files, expected_edges) = assert_ok!(expected, "Expected unfiltered graph paths must be valid");
623        let exclusions = exclusions_fixture(patterns);
624        let exclusions = assert_ok!(exclusions, "Empty and unmatched exclusion patterns must compile");
625
626        let graph = system_under_test.excluding(&exclusions);
627        let graph = graph.excluding(&exclusions);
628
629        assert_eq!(&expected_files, graph.files(), "Unmatched exclusions changed graph nodes");
630        assert_eq!(&expected_edges, graph.edges(), "Unmatched exclusions changed graph dependencies");
631    }
632
633    #[test]
634    fn test_file_exclusions_incident_edges_and_isolates() {
635        let fixture = mixed_dependency_fixture();
636        let (files, dependencies) = assert_ok!(fixture, "Incident-edge exclusion fixture paths must be valid");
637        let system_under_test = FileGraph::new(files, dependencies);
638        let system_under_test = assert_ok!(system_under_test, "Incident-edge exclusion fixture must form a valid graph");
639        let exclusions = exclusions_fixture(&["src/domain/request.rs", "src/isolated/**"]);
640        let exclusions = assert_ok!(exclusions, "Exact-file and isolated-directory exclusions must compile");
641        let expected_paths = BTreeSet::from([
642            PathBuf::from_iter(["src", "api", "http.rs"]),
643            PathBuf::from_iter(["src", "api", "v1", "routes.rs"]),
644            PathBuf::from_iter(["src", "tests", "checks.rs"]),
645        ]);
646        let expected_nodes = folder_nodes(&["api", "api/v1", "tests"]);
647
648        let graph = system_under_test.excluding(&exclusions);
649        let paths: BTreeSet<_> = graph.files().iter().map(|file| file.path().clone()).collect();
650        let folders = graph.folders(Path::new("src"), None, false);
651        let folders = assert_ok!(folders, "Exclusions must preserve folder aggregation invariants");
652
653        assert_eq!(expected_paths, paths, "Excluded isolates must disappear while newly isolated files remain");
654        assert!(graph.edges().is_empty(), "Incident edges of both kinds must disappear without transitive reconnection");
655        assert_eq!(&expected_nodes, folders.nodes(), "Excluded files left stale folder nodes");
656        assert!(folders.edges().is_empty(), "Removed dependencies contributed folder edges");
657    }
658
659    #[rstest]
660    #[case(None, &["api/v1", "domain", "isolated"], &[("api/v1", "domain", 1)])]
661    #[case(Some(1), &["api", "domain", "isolated"], &[("api", "domain", 1)])]
662    #[case(Some(0), &["."], &[(".", ".", 1)])]
663    fn test_file_exclusions_folder_weights(
664        #[case] depth: Option<usize>,
665        #[case] expected_nodes: &[&str],
666        #[case] expected_pairs: &[(&str, &str, usize)],
667    ) {
668        let fixture = mixed_dependency_fixture();
669        let (files, dependencies) = assert_ok!(fixture, "Exclusion-weight fixture paths must be valid");
670        let system_under_test = FileGraph::new(files, dependencies);
671        let system_under_test = assert_ok!(system_under_test, "Exclusion-weight fixture must form a valid graph");
672        let exclusions = exclusions_fixture(&["src/api/http.rs", "src/tests/**"]);
673        let exclusions = assert_ok!(exclusions, "Folder-weight exclusion patterns must compile");
674        let mut expected_edges = folder_edges(expected_pairs, DependencyKind::Production);
675        expected_edges.extend(folder_edges(expected_pairs, DependencyKind::Test));
676        let expected_nodes = folder_nodes(expected_nodes);
677
678        let graph = system_under_test.excluding(&exclusions);
679        let folders = graph.folders(Path::new("src"), depth, true);
680        let folders = assert_ok!(folders, "Filtered files must aggregate at depth {depth:?}");
681
682        assert_eq!(3, graph.files().len(), "Exclusion removed unmatched files or retained matched files");
683        assert_eq!(2, graph.edges().len(), "Exclusion lost dependency kinds or retained incident edges");
684        assert_eq!(&expected_nodes, folders.nodes(), "Depth grouping retained excluded folder nodes");
685        assert_eq!(&expected_edges, folders.edges(), "Excluded file pairs still contributed to folder weights");
686    }
687
688    #[test]
689    fn test_file_exclusions_all_files() {
690        let fixture = mixed_dependency_fixture();
691        let (files, dependencies) = assert_ok!(fixture, "Full-exclusion fixture paths must be valid");
692        let system_under_test = FileGraph::new(files, dependencies);
693        let system_under_test = assert_ok!(system_under_test, "Full-exclusion fixture must form a valid graph");
694        let exclusions = exclusions_fixture(&["**"]);
695        let exclusions = assert_ok!(exclusions, "A recursive all-file exclusion must compile");
696
697        let graph = system_under_test.excluding(&exclusions);
698        let folders = graph.folders(Path::new("src"), None, true);
699        let folders = assert_ok!(folders, "An entirely excluded graph must support folder aggregation");
700
701        assert!(graph.files().is_empty(), "Recursive exclusion retained source files");
702        assert!(graph.edges().is_empty(), "An empty file graph retained dependencies");
703        assert!(folders.nodes().is_empty(), "An empty file graph retained folder nodes");
704        assert!(folders.edges().is_empty(), "An empty file graph retained folder dependencies");
705    }
706
707    #[rstest]
708    #[case(PathBuf::from("source.rs"), PathBuf::new())]
709    #[case(Path::new("src").join("source.rs"), PathBuf::from("src"))]
710    #[case(PathBuf::from("src//source.rs/"), PathBuf::from("src"))]
711    #[case(PathBuf::from("src/./source.rs"), PathBuf::from("src"))]
712    fn test_file_node_source_path(#[case] path: PathBuf, #[case] directory: PathBuf) {
713        let source_path = SourcePath::new(path.clone());
714        let source_path = assert_ok!(source_path, "File-node fixture path must be lexically valid: {path:?}");
715
716        let system_under_test = FileNode::new(source_path);
717
718        assert_eq!(path.as_os_str(), system_under_test.path().as_os_str(), "File node changed its source path");
719        assert_eq!(directory, system_under_test.directory(), "File node has the wrong parent directory");
720    }
721
722    #[rstest]
723    #[case("", true)]
724    #[case(".", true)]
725    #[case("source.rs", false)]
726    #[case("src", false)]
727    fn test_project_root_file_scope(#[case] root: &str, #[case] included: bool) {
728        let source_path = SourcePath::new(PathBuf::from("source.rs"));
729        let source_path = assert_ok!(source_path, "Root-level file must have a valid source path");
730        let file = FileNode::new(source_path);
731        let system_under_test = FileGraph::new(BTreeSet::from([file.clone()]), BTreeSet::new());
732        let system_under_test = assert_ok!(system_under_test, "A root-level file must form a valid graph");
733        let expected_folders = if included { folder_nodes(&["."]) } else { BTreeSet::new() };
734
735        let folders = system_under_test.folders(Path::new(root), None, false);
736        let folders = assert_ok!(folders, "Root-level folder aggregation must accept scope {root:?}");
737        let scoped_files = system_under_test.within_root(Path::new(root));
738        let scoped_files = assert_ok!(scoped_files, "File scoping must accept root {root:?}");
739
740        assert_eq!(included, scoped_files.files().contains(&file), "Root filtering changed root-level file membership");
741        assert_eq!(&expected_folders, folders.nodes(), "Folder aggregation changed root-level file membership");
742    }
743
744    #[rstest]
745    #[case("..")]
746    #[case("../src")]
747    #[case("/src")]
748    fn test_folder_scope_preconditions(#[case] root: &str) {
749        let fixture = file_graph_fixture();
750        let (files, dependencies) = assert_ok!(fixture, "Scope-precondition fixture paths must be valid");
751        let system_under_test = FileGraph::new(files, dependencies);
752        let system_under_test = assert_ok!(system_under_test, "Scope-precondition fixture must form a valid file graph");
753
754        let graph = system_under_test.folders(Path::new(root), None, false);
755
756        assert!(graph.is_err(), "Invalid folder scope was accepted: {root}");
757    }
758
759    #[rstest]
760    #[case("known.rs", "missing.rs")]
761    #[case("missing.rs", "known.rs")]
762    fn test_file_graph_endpoint_membership(#[case] source: &str, #[case] destination: &str) {
763        let known_path = SourcePath::new(PathBuf::from("known.rs"));
764        let known_path = assert_ok!(known_path, "Known graph file must have a valid source path");
765        let files = BTreeSet::from([FileNode::new(known_path)]);
766        let source_path = SourcePath::new(PathBuf::from(source));
767        let source_path = assert_ok!(source_path, "Dependency source path must be valid: {source}");
768        let destination_path = SourcePath::new(PathBuf::from(destination));
769        let destination_path = assert_ok!(destination_path, "Dependency destination path must be valid: {destination}");
770        let dependencies = BTreeSet::from([FileEdge::new(
771            FileNode::new(source_path), FileNode::new(destination_path), DependencyKind::Production,
772        )]);
773
774        let system_under_test = FileGraph::new(files, dependencies);
775
776        assert!(system_under_test.is_err(), "File graph accepted an unknown dependency endpoint");
777    }
778
779    #[rstest]
780    #[case("known.rs", "missing.rs")]
781    #[case("missing.rs", "known.rs")]
782    fn test_file_dependency_insertion_membership(#[case] source: &str, #[case] target: &str) {
783        let known_path = SourcePath::new(PathBuf::from("known.rs"));
784        let known_path = assert_ok!(known_path, "Known insertion-fixture file must have a valid source path");
785        let files = BTreeSet::from([FileNode::new(known_path)]);
786        let source_path = SourcePath::new(PathBuf::from(source));
787        let source_path = assert_ok!(source_path, "Inserted dependency source path must be valid: {source}");
788        let target_path = SourcePath::new(PathBuf::from(target));
789        let target_path = assert_ok!(target_path, "Inserted dependency target path must be valid: {target}");
790        let dependency = FileEdge::new(FileNode::new(source_path), FileNode::new(target_path), DependencyKind::Production);
791        let mut system_under_test = FileGraph::from_files(files.clone());
792
793        let result = catch_unwind(AssertUnwindSafe(|| system_under_test.insert_dependency(dependency)));
794
795        assert!(result.is_err(), "Inserting an unknown dependency endpoint must violate the graph invariant");
796        assert_eq!(&files, system_under_test.files(), "Invalid dependency insertion changed graph files");
797        assert!(system_under_test.edges().is_empty(), "Invalid dependency insertion changed graph edges");
798    }
799
800    #[rstest]
801    #[case("known", "missing")]
802    #[case("missing", "known")]
803    fn test_folder_graph_endpoint_membership(#[case] source: &str, #[case] destination: &str) {
804        let nodes = folder_nodes(&["known"]);
805        let dependencies = folder_edges(&[(source, destination, 1)], DependencyKind::Production);
806
807        let system_under_test = FolderGraph::new(nodes, dependencies);
808
809        assert!(system_under_test.is_err(), "Folder graph accepted an unknown dependency endpoint");
810    }
811}