use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
use anyhow::Context as _;
use anyhow::Result;
use anyhow::ensure;
use derive_new::new;
use getset::CopyGetters;
use getset::Getters;
use crate::SourcePath;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Getters)]
#[getset(get = "pub")]
pub struct FileNode {
path: PathBuf,
}
impl FileNode {
#[must_use]
pub fn new(path: SourcePath) -> Self {
Self { path: path.into_path() }
}
#[must_use]
fn directory(&self) -> &Path {
let Some(directory) = self.path.parent() else {
unreachable!("A validated source file path always has a parent directory");
};
directory
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Getters, new)]
#[getset(get = "pub")]
pub struct FolderNode {
label: String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum DependencyKind {
Production,
Test,
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, CopyGetters, Getters, new)]
pub struct Edge<Node> {
#[getset(get = "pub")]
source: Node,
#[getset(get = "pub")]
target: Node,
#[getset(get_copy = "pub")]
kind: DependencyKind,
}
pub type FileEdge = Edge<FileNode>;
pub type FolderEdge = Edge<FolderNode>;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, CopyGetters, new)]
#[getset(get_copy = "pub")]
pub struct DependencyCount {
value: usize,
}
impl DependencyCount {
const fn increment(&mut self) {
assert!(self.value < usize::MAX, "Dependency counts are bounded by the number of input edges");
self.value += 1;
}
}
#[derive(Default, PartialEq, Getters)]
#[getset(get = "pub")]
pub struct FolderGraph {
nodes: BTreeSet<FolderNode>,
edges: BTreeMap<FolderEdge, DependencyCount>,
}
impl FolderGraph {
pub fn new(nodes: BTreeSet<FolderNode>, edges: BTreeMap<FolderEdge, DependencyCount>) -> Result<Self> {
ensure!(
edges.keys().all(|edge| nodes.contains(edge.source()) && nodes.contains(edge.target())),
"Folder graph has an unknown dependency endpoint"
);
Ok(Self { nodes, edges })
}
}
#[derive(PartialEq, Getters)]
#[getset(get = "pub")]
pub struct FileGraph {
files: BTreeSet<FileNode>,
edges: BTreeSet<FileEdge>,
}
impl FileGraph {
pub fn new(files: BTreeSet<FileNode>, edges: BTreeSet<FileEdge>) -> Result<Self> {
ensure!(
edges.iter().all(|edge| files.contains(edge.source()) && files.contains(edge.target())),
"File graph has an unknown dependency endpoint"
);
Ok(Self { files, edges })
}
#[must_use]
pub(crate) const fn from_files(files: BTreeSet<FileNode>) -> Self {
Self { files, edges: BTreeSet::new() }
}
pub(crate) fn insert_dependency(&mut self, dependency: FileEdge) {
assert!(
self.files.contains(dependency.source()) && self.files.contains(dependency.target()),
"File dependency endpoints must belong to the graph"
);
self.edges.insert(dependency);
}
#[must_use]
pub fn without_test_dependencies(mut self) -> Self {
self.edges.retain(|edge| edge.kind() == DependencyKind::Production);
self
}
pub fn within_root(mut self, root: &Path) -> Result<Self> {
let root = relative_directory_root(root)?;
self.files.retain(|file| file.directory().starts_with(&root));
self.edges.retain(|edge| self.files.contains(edge.source()) && self.files.contains(edge.target()));
Ok(self)
}
pub fn folders(&self, root: &Path, depth: Option<usize>, include_self: bool) -> Result<FolderGraph> {
let root = relative_directory_root(root)?;
let mut folder_graph = FolderGraph::default();
let mut file_folders = BTreeMap::new();
for file in &self.files {
let Ok(relative) = file.directory().strip_prefix(&root) else {
continue;
};
let directory_components = relative.components().take(depth.unwrap_or(usize::MAX));
let parts = directory_components.map(|part| part.as_os_str().to_str().context("Folder path is not UTF-8"));
let parts = parts.collect::<Result<Vec<_>>>()?;
let label = if parts.is_empty() { ".".into() } else { parts.join("/") };
let folder = FolderNode::new(label);
folder_graph.nodes.insert(folder.clone());
file_folders.insert(file, folder);
}
for edge in &self.edges {
let (source, target) = (edge.source(), edge.target());
if source == target {
continue;
}
if let (Some(source_folder), Some(target_folder)) = (file_folders.get(source), file_folders.get(target))
&& (include_self || source_folder != target_folder)
{
let folder_edge = FolderEdge::new(source_folder.clone(), target_folder.clone(), edge.kind());
folder_graph.edges.entry(folder_edge).or_default().increment();
}
}
Ok(folder_graph)
}
}
fn relative_directory_root(root: &Path) -> Result<PathBuf> {
ensure!(
root.components().all(|component| matches!(component, Component::Normal(_) | Component::CurDir)),
"--root must be a relative directory inside the indexed project (no '..')"
);
Ok(root.components().filter(|component| !matches!(component, Component::CurDir)).collect())
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::panic::AssertUnwindSafe;
use std::panic::catch_unwind;
use std::path::Path;
use std::path::PathBuf;
use anyhow::Result;
use claims::assert_ok;
use pretty_assertions::assert_eq;
use rstest::rstest;
use super::DependencyCount;
use super::DependencyKind;
use super::FileEdge;
use super::FileGraph;
use super::FileNode;
use super::FolderEdge;
use super::FolderGraph;
use super::FolderNode;
use crate::SourcePath;
#[rstest]
#[case(0, 1)]
#[case(7, 8)]
#[case(usize::MAX - 1, usize::MAX)]
fn test_dependency_count_increment(#[case] initial: usize, #[case] expected: usize) {
let mut system_under_test = DependencyCount::new(initial);
system_under_test.increment();
assert_eq!(expected, system_under_test.value(), "Dependency count did not increase by one");
}
#[test]
fn test_dependency_count_overflow() {
let mut system_under_test = DependencyCount::new(usize::MAX);
let result = catch_unwind(AssertUnwindSafe(|| system_under_test.increment()));
assert!(result.is_err(), "Dependency count overflow must violate the input-edge bound");
assert_eq!(usize::MAX, system_under_test.value(), "Overflow changed the dependency count");
}
fn file_graph_fixture() -> Result<(BTreeSet<FileNode>, BTreeSet<FileEdge>)> {
let source_directory = Path::new("src");
let service_module = FileNode::new(SourcePath::new(source_directory.join("api").join("service.rs"))?);
let http_module = FileNode::new(SourcePath::new(source_directory.join("api").join("http.rs"))?);
let routes_module = FileNode::new(SourcePath::new(source_directory.join("api").join("v1").join("routes.rs"))?);
let request_module = FileNode::new(SourcePath::new(source_directory.join("domain").join("request.rs"))?);
let rules_module = FileNode::new(SourcePath::new(source_directory.join("domain").join("rules.rs"))?);
let database_module = FileNode::new(SourcePath::new(source_directory.join("storage").join("db.rs"))?);
let calls_module = FileNode::new(SourcePath::new(source_directory.join("body_only").join("calls.rs"))?);
let files = BTreeSet::from([
FileNode::new(SourcePath::new(source_directory.join("lib.rs"))?),
FileNode::new(SourcePath::new(source_directory.join("api").join("mod.rs"))?),
service_module.clone(),
http_module.clone(),
FileNode::new(SourcePath::new(source_directory.join("api").join("v1").join("mod.rs"))?),
routes_module.clone(),
FileNode::new(SourcePath::new(source_directory.join("domain").join("mod.rs"))?),
request_module.clone(),
rules_module.clone(),
database_module.clone(),
FileNode::new(SourcePath::new(source_directory.join("body_only").join("mod.rs"))?),
calls_module.clone(),
FileNode::new(SourcePath::new(source_directory.join("isolated").join("mod.rs"))?),
FileNode::new(SourcePath::new(source_directory.join("isolated").join("sample.rs"))?),
]);
let dependencies = BTreeSet::from([
FileEdge::new(service_module.clone(), http_module.clone(), DependencyKind::Production),
FileEdge::new(service_module, routes_module.clone(), DependencyKind::Production),
FileEdge::new(http_module.clone(), request_module.clone(), DependencyKind::Production),
FileEdge::new(http_module, database_module.clone(), DependencyKind::Production),
FileEdge::new(routes_module.clone(), request_module.clone(), DependencyKind::Production),
FileEdge::new(routes_module, database_module.clone(), DependencyKind::Production),
FileEdge::new(request_module, rules_module.clone(), DependencyKind::Production),
FileEdge::new(rules_module, database_module.clone(), DependencyKind::Production),
FileEdge::new(calls_module, database_module, DependencyKind::Production),
]);
Ok((files, dependencies))
}
#[must_use]
fn folder_edges(values: &[(&str, &str, usize)], kind: DependencyKind) -> BTreeMap<FolderEdge, DependencyCount> {
values.iter().map(|&(source, destination, weight)| {
let edge = FolderEdge::new(FolderNode::new(source.into()), FolderNode::new(destination.into()), kind);
(edge, DependencyCount::new(weight))
}).collect()
}
#[must_use]
fn folder_nodes(values: &[&str]) -> BTreeSet<FolderNode> {
values.iter().map(|&label| FolderNode::new(label.into())).collect()
}
fn mixed_dependency_fixture() -> Result<(BTreeSet<FileNode>, BTreeSet<FileEdge>)> {
let source_directory = Path::new("src");
let http_module = FileNode::new(SourcePath::new(source_directory.join("api").join("http.rs"))?);
let routes_module = FileNode::new(SourcePath::new(source_directory.join("api").join("v1").join("routes.rs"))?);
let request_module = FileNode::new(SourcePath::new(source_directory.join("domain").join("request.rs"))?);
let checks_module = FileNode::new(SourcePath::new(source_directory.join("tests").join("checks.rs"))?);
let files = BTreeSet::from([
http_module.clone(),
routes_module.clone(),
request_module.clone(),
checks_module.clone(),
FileNode::new(SourcePath::new(source_directory.join("isolated").join("sample.rs"))?),
]);
let dependencies = BTreeSet::from([
FileEdge::new(http_module.clone(), request_module.clone(), DependencyKind::Production),
FileEdge::new(routes_module.clone(), request_module.clone(), DependencyKind::Production),
FileEdge::new(http_module.clone(), request_module.clone(), DependencyKind::Test),
FileEdge::new(http_module.clone(), request_module.clone(), DependencyKind::Test),
FileEdge::new(routes_module, request_module.clone(), DependencyKind::Test),
FileEdge::new(request_module.clone(), http_module, DependencyKind::Test),
FileEdge::new(checks_module, request_module, DependencyKind::Test),
]);
Ok((files, dependencies))
}
#[test]
fn test_physical_directories_and_isolated_files() {
let fixture = file_graph_fixture();
let (files, dependencies) = assert_ok!(fixture, "Physical-directory fixture paths must be valid");
let system_under_test = FileGraph::new(files, dependencies);
let system_under_test = assert_ok!(system_under_test, "Physical-directory fixture must form a valid file graph");
let expected_nodes = folder_nodes(&[".", "api", "api/v1", "body_only", "domain", "isolated", "storage"]);
let expected_edges = folder_edges(
&[
("api", "api/v1", 1),
("api", "domain", 1),
("api", "storage", 1),
("api/v1", "domain", 1),
("api/v1", "storage", 1),
("body_only", "storage", 1),
("domain", "storage", 1),
],
DependencyKind::Production,
);
let graph = system_under_test.folders(Path::new("src"), None, false);
let graph = assert_ok!(graph, "Physical directories must aggregate under the source root");
assert_eq!(&expected_nodes, graph.nodes(), "Physical directory nodes differ");
assert_eq!(&expected_edges, graph.edges(), "Physical directory dependencies differ");
assert!(!graph.nodes().contains(&FolderNode::new("persistence".into())), "Module name replaced physical folder");
}
#[rstest]
#[case(None)]
#[case(Some(2))]
#[case(Some(10))]
fn test_depth_beyond_existing_folders(#[case] depth: Option<usize>) {
let fixture = file_graph_fixture();
let (files, dependencies) = assert_ok!(fixture, "Depth fixture paths must be valid");
let system_under_test = FileGraph::new(files, dependencies);
let system_under_test = assert_ok!(system_under_test, "Depth fixture must form a valid file graph");
let complete_graph = system_under_test.folders(Path::new("src"), None, false);
let complete_graph = assert_ok!(complete_graph, "Unbounded folder aggregation must succeed");
let graph = system_under_test.folders(Path::new("src"), depth, false);
let graph = assert_ok!(graph, "Folder aggregation must succeed at depth {depth:?}");
assert_eq!(complete_graph.nodes(), graph.nodes(), "Depth {depth:?} changed nodes in a shallower graph");
assert_eq!(complete_graph.edges(), graph.edges(), "Depth {depth:?} changed dependencies in a shallower graph");
}
#[rstest]
#[case(0, &["."], &[])]
#[case(1, &[".", "api", "body_only", "domain", "isolated", "storage"], &[
("api", "domain", 2), ("api", "storage", 2),
("body_only", "storage", 1), ("domain", "storage", 1),
])]
fn test_depth_grouping_and_distinct_file_pair_weights(
#[case] depth: usize,
#[case] expected_nodes: &[&str],
#[case] expected_edges: &[(&str, &str, usize)],
) {
let fixture = file_graph_fixture();
let (files, dependencies) = assert_ok!(fixture, "Depth-grouping fixture paths must be valid");
let system_under_test = FileGraph::new(files, dependencies);
let system_under_test = assert_ok!(system_under_test, "Depth-grouping fixture must form a valid file graph");
let graph = system_under_test.folders(Path::new("src"), Some(depth), false);
let graph = assert_ok!(graph, "Folder grouping must succeed at depth {depth}");
assert_eq!(&folder_nodes(expected_nodes), graph.nodes(), "Depth {depth} grouped nodes incorrectly");
assert_eq!(&folder_edges(expected_edges, DependencyKind::Production), graph.edges(), "Depth {depth}: misgrouped edges");
}
#[rstest]
#[case(None, &[
("api", "api", 1), ("api", "api/v1", 1),
("api", "domain", 1), ("api", "storage", 1),
("api/v1", "domain", 1), ("api/v1", "storage", 1),
("body_only", "storage", 1), ("domain", "domain", 1),
("domain", "storage", 1),
])]
#[case(Some(0), &[(".", ".", 9)])]
#[case(Some(1), &[
("api", "api", 2), ("api", "domain", 2),
("api", "storage", 2), ("body_only", "storage", 1),
("domain", "domain", 1), ("domain", "storage", 1),
])]
fn test_self_edges_between_distinct_files(#[case] depth: Option<usize>, #[case] expected_edges: &[(&str, &str, usize)]) {
let fixture = file_graph_fixture();
let (files, mut dependencies) = assert_ok!(fixture, "Self-edge fixture paths must be valid");
let request_path = SourcePath::new(Path::new("src").join("domain").join("request.rs"));
let request_path = assert_ok!(request_path, "Self-dependent request module must have a valid source path");
let request_module = FileNode::new(request_path);
dependencies.insert(FileEdge::new(request_module.clone(), request_module, DependencyKind::Production));
let system_under_test = FileGraph::new(files, dependencies);
let system_under_test = assert_ok!(system_under_test, "Self-edge fixture must form a valid file graph");
let graph = system_under_test.folders(Path::new("src"), depth, true);
let graph = assert_ok!(graph, "Folder aggregation with self-edges must succeed at depth {depth:?}");
assert_eq!(
&folder_edges(expected_edges, DependencyKind::Production),
graph.edges(),
"Self-edge handling at depth {depth:?} differs"
);
}
#[test]
fn test_scope_boundaries_use_path_components() {
let fixture = file_graph_fixture();
let (mut files, mut dependencies) = assert_ok!(fixture, "Scope-boundary fixture paths must be valid");
let outside_path = SourcePath::new(Path::new("src2").join("outside.rs"));
let outside_path = assert_ok!(outside_path, "Outside module must have a valid project-relative source path");
let outside_module = FileNode::new(outside_path);
files.insert(outside_module.clone());
let service_path = SourcePath::new(Path::new("src").join("api").join("service.rs"));
let service_path = assert_ok!(service_path, "Service module must have a valid source path");
dependencies.insert(FileEdge::new(outside_module, FileNode::new(service_path), DependencyKind::Production));
let system_under_test = FileGraph::new(files, dependencies);
let system_under_test = assert_ok!(system_under_test, "Cross-scope dependencies must form a valid file graph");
let api_graph = system_under_test.folders(&Path::new("src").join("api"), None, false);
let api_graph = assert_ok!(api_graph, "API folder scope must aggregate successfully");
let source_graph = system_under_test.folders(Path::new("src"), None, false);
let source_graph = assert_ok!(source_graph, "Source folder scope must aggregate successfully");
assert_eq!(&folder_nodes(&[".", "v1"]), api_graph.nodes(), "API scope contains unexpected folders");
assert_eq!(&folder_edges(&[(".", "v1", 1)], DependencyKind::Production), api_graph.edges(), "API scope edges differ");
assert!(!source_graph.nodes().contains(&FolderNode::new("src2".into())), "Scope included a shared-prefix sibling");
assert_eq!(7, source_graph.edges().len(), "Scope changed the seven dependencies internal to the source tree");
}
#[rstest]
#[case(1, &["src"], &[])]
#[case(2, &["src", "src/api", "src/body_only", "src/domain", "src/isolated", "src/storage"], &[
("src/api", "src/domain", 2), ("src/api", "src/storage", 2),
("src/body_only", "src/storage", 1), ("src/domain", "src/storage", 1),
])]
fn test_default_depth_origin(
#[case] depth: usize,
#[case] expected_nodes: &[&str],
#[case] expected_edges: &[(&str, &str, usize)],
) {
let fixture = file_graph_fixture();
let (files, dependencies) = assert_ok!(fixture, "Default-root fixture paths must be valid");
let system_under_test = FileGraph::new(files, dependencies);
let system_under_test = assert_ok!(system_under_test, "Default-root fixture must form a valid file graph");
let graph = system_under_test.folders(Path::new(""), Some(depth), false);
let graph = assert_ok!(graph, "Default-root aggregation must succeed at depth {depth}");
assert_eq!(&folder_nodes(expected_nodes), graph.nodes(), "Default root produced incorrect nodes at depth {depth}");
assert_eq!(
&folder_edges(expected_edges, DependencyKind::Production),
graph.edges(),
"Default root produced incorrect dependencies at depth {depth}"
);
}
#[test]
fn test_isolated_folder_scope() {
let fixture = file_graph_fixture();
let (files, dependencies) = assert_ok!(fixture, "Isolated-folder fixture paths must be valid");
let system_under_test = FileGraph::new(files, dependencies);
let system_under_test = assert_ok!(system_under_test, "Isolated-folder fixture must form a valid file graph");
let graph = system_under_test.folders(&Path::new("src").join("isolated"), None, true);
let graph = assert_ok!(graph, "An isolated folder must be a valid aggregation scope");
assert_eq!(&folder_nodes(&["."]), graph.nodes(), "Isolated scope contains unexpected folders");
assert!(graph.edges().is_empty(), "An isolated folder acquired dependencies");
}
#[rstest]
#[case(None, &[("api", "domain", 1), ("api/v1", "domain", 1)], &[
("api", "domain", 1), ("api/v1", "domain", 1), ("domain", "api", 1), ("tests", "domain", 1),
])]
#[case(Some(1), &[("api", "domain", 2)], &[("api", "domain", 2), ("domain", "api", 1), ("tests", "domain", 1)])]
#[case(Some(0), &[(".", ".", 2)], &[(".", ".", 4)])]
fn test_dependency_kinds_deduplication_and_depth_aggregation(
#[case] depth: Option<usize>,
#[case] expected_production: &[(&str, &str, usize)],
#[case] expected_tests: &[(&str, &str, usize)],
) {
let fixture = mixed_dependency_fixture();
let (files, dependencies) = assert_ok!(fixture, "Mixed-dependency fixture paths must be valid");
let system_under_test = FileGraph::new(files, dependencies);
let system_under_test = assert_ok!(system_under_test, "Mixed dependency kinds must form a valid file graph");
let mut expected_edges = folder_edges(expected_production, DependencyKind::Production);
expected_edges.extend(folder_edges(expected_tests, DependencyKind::Test));
let graph = system_under_test.folders(Path::new("src"), depth, true);
let graph = assert_ok!(graph, "Mixed dependency kinds must aggregate at depth {depth:?}");
assert_eq!(6, system_under_test.edges().len(), "Duplicate occurrences retained or dependency kinds merged");
assert_eq!(&expected_edges, graph.edges(), "Depth {depth:?} changed dependency kinds or distinct file-pair counts");
}
#[test]
fn test_dependency_kind_filtering() {
let fixture = mixed_dependency_fixture();
let (files, dependencies) = assert_ok!(fixture, "Dependency-filtering fixture paths must be valid");
let expected_files = files.clone();
let system_under_test = FileGraph::new(files, dependencies);
let system_under_test = assert_ok!(system_under_test, "Dependency-filtering fixture must form a valid file graph");
let expected_edges = folder_edges(&[("api", "domain", 1), ("api/v1", "domain", 1)], DependencyKind::Production);
let graph = system_under_test.without_test_dependencies();
let folders = graph.folders(Path::new("src"), None, false);
let folders = assert_ok!(folders, "Production-only dependencies must support folder aggregation");
assert_eq!(&expected_files, graph.files(), "Excluding test dependencies removed source files");
assert_eq!(2, graph.edges().len(), "Excluding test dependencies lost production edges or retained test edges");
assert_eq!(&expected_edges, folders.edges(), "Excluding test dependencies changed production dependencies or counts");
assert_eq!(
&folder_nodes(&["api", "api/v1", "domain", "isolated", "tests"]),
folders.nodes(),
"Excluding test dependencies removed isolated or test-only source folders"
);
}
#[rstest]
#[case(PathBuf::from("source.rs"), PathBuf::new())]
#[case(Path::new("src").join("source.rs"), PathBuf::from("src"))]
#[case(PathBuf::from("src//source.rs/"), PathBuf::from("src"))]
#[case(PathBuf::from("src/./source.rs"), PathBuf::from("src"))]
fn test_file_node_source_path(#[case] path: PathBuf, #[case] directory: PathBuf) {
let source_path = SourcePath::new(path.clone());
let source_path = assert_ok!(source_path, "File-node fixture path must be lexically valid: {path:?}");
let system_under_test = FileNode::new(source_path);
assert_eq!(path.as_os_str(), system_under_test.path().as_os_str(), "File node changed its source path");
assert_eq!(directory, system_under_test.directory(), "File node has the wrong parent directory");
}
#[rstest]
#[case("", true)]
#[case(".", true)]
#[case("source.rs", false)]
#[case("src", false)]
fn test_project_root_file_scope(#[case] root: &str, #[case] included: bool) {
let source_path = SourcePath::new(PathBuf::from("source.rs"));
let source_path = assert_ok!(source_path, "Root-level file must have a valid source path");
let file = FileNode::new(source_path);
let system_under_test = FileGraph::new(BTreeSet::from([file.clone()]), BTreeSet::new());
let system_under_test = assert_ok!(system_under_test, "A root-level file must form a valid graph");
let expected_folders = if included { folder_nodes(&["."]) } else { BTreeSet::new() };
let folders = system_under_test.folders(Path::new(root), None, false);
let folders = assert_ok!(folders, "Root-level folder aggregation must accept scope {root:?}");
let scoped_files = system_under_test.within_root(Path::new(root));
let scoped_files = assert_ok!(scoped_files, "File scoping must accept root {root:?}");
assert_eq!(included, scoped_files.files().contains(&file), "Root filtering changed root-level file membership");
assert_eq!(&expected_folders, folders.nodes(), "Folder aggregation changed root-level file membership");
}
#[rstest]
#[case("..")]
#[case("../src")]
#[case("/src")]
fn test_folder_scope_preconditions(#[case] root: &str) {
let fixture = file_graph_fixture();
let (files, dependencies) = assert_ok!(fixture, "Scope-precondition fixture paths must be valid");
let system_under_test = FileGraph::new(files, dependencies);
let system_under_test = assert_ok!(system_under_test, "Scope-precondition fixture must form a valid file graph");
let graph = system_under_test.folders(Path::new(root), None, false);
assert!(graph.is_err(), "Invalid folder scope was accepted: {root}");
}
#[rstest]
#[case("known.rs", "missing.rs")]
#[case("missing.rs", "known.rs")]
fn test_file_graph_endpoint_membership(#[case] source: &str, #[case] destination: &str) {
let known_path = SourcePath::new(PathBuf::from("known.rs"));
let known_path = assert_ok!(known_path, "Known graph file must have a valid source path");
let files = BTreeSet::from([FileNode::new(known_path)]);
let source_path = SourcePath::new(PathBuf::from(source));
let source_path = assert_ok!(source_path, "Dependency source path must be valid: {source}");
let destination_path = SourcePath::new(PathBuf::from(destination));
let destination_path = assert_ok!(destination_path, "Dependency destination path must be valid: {destination}");
let dependencies = BTreeSet::from([FileEdge::new(
FileNode::new(source_path), FileNode::new(destination_path), DependencyKind::Production,
)]);
let system_under_test = FileGraph::new(files, dependencies);
assert!(system_under_test.is_err(), "File graph accepted an unknown dependency endpoint");
}
#[rstest]
#[case("known.rs", "missing.rs")]
#[case("missing.rs", "known.rs")]
fn test_file_dependency_insertion_membership(#[case] source: &str, #[case] target: &str) {
let known_path = SourcePath::new(PathBuf::from("known.rs"));
let known_path = assert_ok!(known_path, "Known insertion-fixture file must have a valid source path");
let files = BTreeSet::from([FileNode::new(known_path)]);
let source_path = SourcePath::new(PathBuf::from(source));
let source_path = assert_ok!(source_path, "Inserted dependency source path must be valid: {source}");
let target_path = SourcePath::new(PathBuf::from(target));
let target_path = assert_ok!(target_path, "Inserted dependency target path must be valid: {target}");
let dependency = FileEdge::new(FileNode::new(source_path), FileNode::new(target_path), DependencyKind::Production);
let mut system_under_test = FileGraph::from_files(files.clone());
let result = catch_unwind(AssertUnwindSafe(|| system_under_test.insert_dependency(dependency)));
assert!(result.is_err(), "Inserting an unknown dependency endpoint must violate the graph invariant");
assert_eq!(&files, system_under_test.files(), "Invalid dependency insertion changed graph files");
assert!(system_under_test.edges().is_empty(), "Invalid dependency insertion changed graph edges");
}
#[rstest]
#[case("known", "missing")]
#[case("missing", "known")]
fn test_folder_graph_endpoint_membership(#[case] source: &str, #[case] destination: &str) {
let nodes = folder_nodes(&["known"]);
let dependencies = folder_edges(&[(source, destination, 1)], DependencyKind::Production);
let system_under_test = FolderGraph::new(nodes, dependencies);
assert!(system_under_test.is_err(), "Folder graph accepted an unknown dependency endpoint");
}
}