Skip to main content

source_mesh_core/graph/
outgoing_dependencies.rs

1use std::collections::BTreeMap;
2use std::collections::BTreeSet;
3
4use anyhow::Context as _;
5use anyhow::Result;
6
7use super::markdown::inline_code;
8use super::model::Edge;
9use super::model::FileGraph;
10use super::model::FolderGraph;
11
12const NO_VIOLATIONS_FOUND: &str = "No outgoing dependency violations found.";
13
14#[derive(Clone, Copy)]
15pub enum Mode {
16    Files,
17    Folders,
18}
19
20impl Mode {
21    #[must_use]
22    const fn label(self) -> &'static str {
23        match self {
24            Self::Files => "files",
25            Self::Folders => "folders",
26        }
27    }
28}
29
30pub struct Analysis {
31    mode: Mode,
32    maximum: usize,
33    violations: BTreeMap<String, usize>,
34}
35
36impl Analysis {
37    pub fn files(graph: &FileGraph, maximum: usize) -> Result<Self> {
38        let violations = violating_sources(graph.edges().iter(), maximum).map(|(source, count)| {
39            let label = source.path().to_str().context("Outgoing dependency file path is not UTF-8")?;
40            Ok((label.to_owned(), count))
41        }).collect::<Result<_>>()?;
42        Ok(Self { mode: Mode::Files, maximum, violations })
43    }
44
45    #[must_use]
46    pub fn folders(graph: &FolderGraph, maximum: usize) -> Self {
47        let violations = violating_sources(graph.edges().keys(), maximum);
48        let violations = violations.map(|(source, count)| (source.label().clone(), count)).collect();
49        Self { mode: Mode::Folders, maximum, violations }
50    }
51
52    #[must_use]
53    pub fn has_violations(&self) -> bool {
54        !self.violations.is_empty()
55    }
56
57    #[must_use]
58    pub fn diagnostic(&self) -> String {
59        let mode = self.mode.label();
60        let mut output = if self.has_violations() {
61            format!(
62                "Outgoing dependency threshold exceeded (mode: {mode}, maximum: {}, violating sources: {}).\n",
63                self.maximum,
64                self.violations.len(),
65            )
66        } else {
67            format!("{NO_VIOLATIONS_FOUND} Mode: {mode}; maximum: {}.\n", self.maximum)
68        };
69        output.push_str(&self.violation_list(|label| format!("{label:?}")));
70        output
71    }
72
73    #[must_use]
74    pub fn markdown(&self) -> String {
75        let mode = self.mode.label();
76        let mut output = format!("# Outgoing dependency threshold\n\nMode: {mode}\n\nMaximum: {}\n\n", self.maximum);
77        if self.has_violations() {
78            output.push_str(&self.violation_list(inline_code));
79        } else {
80            output.push_str(NO_VIOLATIONS_FOUND);
81            output.push('\n');
82        }
83        output
84    }
85
86    #[must_use]
87    fn violation_list(&self, label: impl Fn(&str) -> String) -> String {
88        let mut output = String::new();
89        let maximum = self.maximum.to_string();
90        for (source, count) in &self.violations {
91            output.push_str("- ");
92            output.push_str(&label(source));
93            output.push_str(": ");
94            output.push_str(&count.to_string());
95            output.push_str(" outgoing dependencies (maximum: ");
96            output.push_str(&maximum);
97            output.push_str(")\n");
98        }
99        output
100    }
101}
102
103fn violating_sources<'a, Node: Ord + 'a>(
104    edges: impl Iterator<Item = &'a Edge<Node>>,
105    maximum: usize,
106) -> impl Iterator<Item = (&'a Node, usize)> {
107    let mut targets_by_source: BTreeMap<_, BTreeSet<_>> = BTreeMap::new();
108    for edge in edges {
109        targets_by_source.entry(edge.source()).or_default().insert(edge.target());
110    }
111    let counts = targets_by_source.into_iter().map(|(source, targets)| (source, targets.len()));
112    counts.filter(move |&(_, count)| count > maximum)
113}
114
115#[cfg(test)]
116mod tests {
117    use std::collections::BTreeMap;
118    use std::collections::BTreeSet;
119    use std::path::Path;
120    use std::path::PathBuf;
121
122    use anyhow::Error;
123    use anyhow::Result;
124    use claims::assert_ok;
125    use claims::assert_some;
126    use pretty_assertions::assert_eq;
127    use rstest::rstest;
128
129    use super::Analysis;
130    use super::Mode;
131    use super::NO_VIOLATIONS_FOUND;
132    use crate::SourcePath;
133    use crate::model::DependencyCount;
134    use crate::model::DependencyKind;
135    use crate::model::DependencyKind::Production;
136    use crate::model::DependencyKind::Test;
137    use crate::model::FileEdge;
138    use crate::model::FileGraph;
139    use crate::model::FileNode;
140    use crate::model::FolderEdge;
141    use crate::model::FolderGraph;
142    use crate::model::FolderNode;
143
144    fn file_node_fixture(path: PathBuf) -> Result<FileNode> {
145        SourcePath::new(path).map(FileNode::new)
146    }
147
148    fn graph_fixture(
149        dependencies: &[(&str, &str, DependencyKind, usize)],
150        isolated: &[&str],
151    ) -> Result<(FileGraph, FolderGraph)> {
152        let labels = dependencies.iter().flat_map(|&(source, target, _, _)| [source, target]);
153        let labels: BTreeSet<_> = labels.chain(isolated.iter().copied()).collect();
154        let files = labels.iter().map(|&label| file_node_fixture(label.into())).collect::<Result<_>>()?;
155        let file_edges = dependencies.iter().map(|&(source, target, kind, _)| {
156            Ok(FileEdge::new(file_node_fixture(source.into())?, file_node_fixture(target.into())?, kind))
157        }).collect::<Result<_>>()?;
158        let folders = labels.iter().map(|&label| FolderNode::new(label.into())).collect();
159        let folder_edges = dependencies.iter().map(|&(source, target, kind, weight)| {
160            let edge = FolderEdge::new(FolderNode::new(source.into()), FolderNode::new(target.into()), kind);
161            (edge, DependencyCount::new(weight))
162        }).collect();
163        Ok((FileGraph::new(files, file_edges)?, FolderGraph::new(folders, folder_edges)?))
164    }
165
166    #[rstest]
167    fn test_outgoing_direction(#[values(Mode::Files, Mode::Folders)] mode: Mode) {
168        let fixture = graph_fixture(&[
169            ("alpha", "sink", Production, 1),
170            ("beta", "sink", Production, 1),
171            ("gamma", "sink", Production, 1),
172            ("source", "alpha", Production, 1),
173            ("source", "beta", Production, 1),
174        ], &[]);
175        let (files, folders) = assert_ok!(fixture, "Incoming and outgoing dependencies must form valid graphs");
176
177        let system_under_test = match mode {
178            Mode::Files => Analysis::files(&files, 1),
179            Mode::Folders => Ok(Analysis::folders(&folders, 1)),
180        };
181        let system_under_test = assert_ok!(system_under_test, "Directed dependencies must support threshold analysis");
182
183        let expected = BTreeMap::from([(String::from("source"), 2)]);
184        assert_eq!(expected, system_under_test.violations, "Incoming dependencies must not contribute to the source count");
185        assert!(system_under_test.has_violations(), "Two outgoing targets must exceed a maximum of one");
186    }
187
188    #[rstest]
189    #[case::zero(0, true)]
190    #[case::above(1, true)]
191    #[case::equal(2, false)]
192    #[case::below(3, false)]
193    #[case::maximum(usize::MAX, false)]
194    fn test_distinct_targets_and_thresholds(
195        #[values(Mode::Files, Mode::Folders)] mode: Mode,
196        #[case] maximum: usize,
197        #[case] expected_violation: bool,
198    ) {
199        let fixture = graph_fixture(&[
200            ("source", "first", Production, usize::MAX),
201            ("source", "first", Test, usize::MAX),
202            ("source", "second", Test, 7),
203        ], &[]);
204        let (files, folders) = assert_ok!(fixture, "Mixed dependency kinds and large weights must form valid graphs");
205
206        let system_under_test = match mode {
207            Mode::Files => Analysis::files(&files, maximum),
208            Mode::Folders => Ok(Analysis::folders(&folders, maximum)),
209        };
210        let system_under_test = assert_ok!(system_under_test, "Threshold analysis must accept every usize maximum");
211
212        let expected = if expected_violation { BTreeMap::from([(String::from("source"), 2)]) } else { BTreeMap::new() };
213        assert_eq!(expected, system_under_test.violations, "Count distinct targets, not edge kinds or folder weights");
214        assert_eq!(expected_violation, system_under_test.has_violations(), "Only counts strictly above the maximum violate");
215    }
216
217    #[rstest]
218    #[case::empty(&[])]
219    #[case::isolated(&["isolated"])]
220    fn test_empty_and_isolated_reports(#[values(Mode::Files, Mode::Folders)] mode: Mode, #[case] isolated: &[&str]) {
221        let fixture = graph_fixture(&[], isolated);
222        let (files, folders) = assert_ok!(fixture, "Empty and isolated-node graphs must be valid");
223
224        let system_under_test = match mode {
225            Mode::Files => Analysis::files(&files, 0),
226            Mode::Folders => Ok(Analysis::folders(&folders, 0)),
227        };
228        let system_under_test = assert_ok!(system_under_test, "Graphs without edges must support threshold analysis");
229        let diagnostic = system_under_test.diagnostic();
230        let markdown = system_under_test.markdown();
231
232        assert!(!system_under_test.has_violations(), "An empty outgoing target set must satisfy a zero maximum");
233        assert!(diagnostic.contains(NO_VIOLATIONS_FOUND), "Diagnostic must explicitly state that no sources violate");
234        assert!(diagnostic.contains(&format!("Mode: {}; maximum: 0", mode.label())), "Diagnostic must identify its scope");
235        assert_eq!(Some(NO_VIOLATIONS_FOUND), markdown.lines().last(), "Markdown must explicitly state that no sources violate");
236        assert!(markdown.contains(&format!("Mode: {}", mode.label())), "Markdown must identify the analysis mode");
237        assert!(markdown.contains("Maximum: 0"), "Markdown must include the configured zero maximum");
238        assert!(!diagnostic.lines().any(|line| line.starts_with("- ")), "Diagnostic must not list isolated nodes");
239        assert!(!markdown.lines().any(|line| line.starts_with("- ")), "Markdown must not list isolated nodes");
240    }
241
242    #[rstest]
243    #[case::above(0, true)]
244    #[case::equal(1, false)]
245    fn test_self_edges(
246        #[values(Mode::Files, Mode::Folders)] mode: Mode,
247        #[case] maximum: usize,
248        #[case] expected_violation: bool,
249    ) {
250        let fixture = graph_fixture(&[("self", "self", Production, usize::MAX), ("self", "self", Test, 3)], &[]);
251        let (files, folders) = assert_ok!(fixture, "Self edges of both dependency kinds must form valid graphs");
252
253        let system_under_test = match mode {
254            Mode::Files => Analysis::files(&files, maximum),
255            Mode::Folders => Ok(Analysis::folders(&folders, maximum)),
256        };
257        let system_under_test = assert_ok!(system_under_test, "Self edges must support threshold analysis");
258
259        let expected = if expected_violation { BTreeMap::from([(String::from("self"), 1)]) } else { BTreeMap::new() };
260        assert_eq!(expected, system_under_test.violations, "A retained self edge must count as one distinct target");
261        assert_eq!(expected_violation, system_under_test.has_violations(), "Self-edge thresholds must use strict comparison");
262    }
263
264    #[rstest]
265    fn test_all_violations_in_sorted_order(#[values(Mode::Files, Mode::Folders)] mode: Mode) {
266        let fixture = graph_fixture(&[
267            ("zebra", "first", Production, 1),
268            ("zebra", "second", Test, 1),
269            ("middle", "first", Production, 1),
270            ("middle", "second", Production, 1),
271            ("alpha", "first", Production, 1),
272            ("alpha", "second", Production, 1),
273            ("alpha", "third", Production, 1),
274        ], &[]);
275        let (files, folders) = assert_ok!(fixture, "Several violating sources must form valid graphs");
276
277        let system_under_test = match mode {
278            Mode::Files => Analysis::files(&files, 1),
279            Mode::Folders => Ok(Analysis::folders(&folders, 1)),
280        };
281        let system_under_test = assert_ok!(system_under_test, "Every violating source must be analyzed");
282        let diagnostic = Error::msg(system_under_test.diagnostic()).to_string();
283        let markdown = system_under_test.markdown();
284        let diagnostic_lines: Vec<_> = diagnostic.lines().filter(|line| line.starts_with("- ")).collect();
285        let markdown_lines: Vec<_> = markdown.lines().filter(|line| line.starts_with("- ")).collect();
286
287        assert_eq!(vec![
288            "- \"alpha\": 3 outgoing dependencies (maximum: 1)",
289            "- \"middle\": 2 outgoing dependencies (maximum: 1)",
290            "- \"zebra\": 2 outgoing dependencies (maximum: 1)",
291        ], diagnostic_lines, "The complete error string must list all offending sources in label order");
292        assert_eq!(vec![
293            "- <code>alpha</code>: 3 outgoing dependencies (maximum: 1)",
294            "- <code>middle</code>: 2 outgoing dependencies (maximum: 1)",
295            "- <code>zebra</code>: 2 outgoing dependencies (maximum: 1)",
296        ], markdown_lines, "Markdown must list every source with its actual count and maximum");
297        let summary = format!("mode: {}, maximum: 1, violating sources: 3", mode.label());
298        assert!(diagnostic.contains(&summary), "The error summary must identify the mode, maximum, and violation total");
299        assert!(markdown.contains(&format!("Mode: {}", mode.label())), "Markdown must identify the analysis mode");
300        assert!(markdown.contains("Maximum: 1"), "Markdown must include the configured maximum");
301    }
302
303    #[test]
304    fn test_file_paths_and_folder_labels() {
305        let service = file_node_fixture(Path::new("src").join("api").join("deep").join("service.rs"));
306        let service = assert_ok!(service, "Nested source file must be a valid project-relative path");
307        let database = file_node_fixture(Path::new("src").join("storage").join("database.rs"));
308        let database = assert_ok!(database, "Target file must be a valid project-relative path");
309        let edge = FileEdge::new(service.clone(), database.clone(), Production);
310        let fixture = FileGraph::new(BTreeSet::from([service.clone(), database]), BTreeSet::from([edge]));
311        let fixture = assert_ok!(fixture, "Cross-folder dependency must form a valid file graph");
312        let folders = fixture.folders(Path::new("src"), Some(1), false);
313        let folders = assert_ok!(folders, "Folder aggregation must supply root-relative depth-folded labels");
314        let service_path = service.path().to_str();
315        let service_path = assert_some!(service_path, "Source fixture path must be UTF-8");
316
317        let system_under_test = Analysis::files(&fixture, 0);
318        let system_under_test = assert_ok!(system_under_test, "Nested source paths must support file threshold analysis");
319        let folder_analysis = Analysis::folders(&folders, 0);
320
321        let expected_files = BTreeMap::from([(service_path.to_owned(), 1)]);
322        assert_eq!(expected_files, system_under_test.violations, "File labels must retain the complete project-relative path");
323        let expected_folders = BTreeMap::from([(String::from("api"), 1)]);
324        assert_eq!(expected_folders, folder_analysis.violations, "Folder labels must come from the final aggregated graph");
325        let diagnostic_path = format!("{service_path:?}");
326        assert!(system_under_test.diagnostic().contains(&diagnostic_path), "Diagnostic must retain the complete file path");
327    }
328
329    #[rstest]
330    fn test_folder_self_edge_filtering(#[values(false, true)] include_self: bool) {
331        let service = file_node_fixture(Path::new("src").join("api").join("service.rs"));
332        let service = assert_ok!(service, "Service fixture path must be valid");
333        let request = file_node_fixture(Path::new("src").join("api").join("request.rs"));
334        let request = assert_ok!(request, "Request fixture path must be valid");
335        let edge = FileEdge::new(service.clone(), request.clone(), Production);
336        let fixture = FileGraph::new(BTreeSet::from([service, request]), BTreeSet::from([edge]));
337        let fixture = assert_ok!(fixture, "A dependency inside one folder must form a valid graph");
338        let folders = fixture.folders(Path::new("src"), None, include_self);
339        let folders = assert_ok!(folders, "Folder aggregation must apply the requested self-edge policy");
340
341        let system_under_test = Analysis::folders(&folders, 0);
342
343        let expected = if include_self { BTreeMap::from([(String::from("api"), 1)]) } else { BTreeMap::new() };
344        assert_eq!(expected, system_under_test.violations, "Analysis must count exactly the self edges retained by aggregation");
345        assert_eq!(include_self, system_under_test.has_violations(), "Analysis must not add or remove self edges");
346    }
347
348    #[rstest]
349    #[case(
350        "unsafe`<>&\n\r\t",
351        "unsafe&#96;&lt;&gt;&amp;&#92;n&#92;r&#92;t",
352        "\"unsafe`<>&\\n\\r\\t\"",
353    )]
354    #[case(
355        "unsafe*[link]_\\~|",
356        "unsafe&#42;&#91;link&#93;&#95;&#92;&#126;&#124;",
357        "\"unsafe*[link]_\\\\~|\"",
358    )]
359    #[case(
360        "unsafe\n## injected\n<script>alert(1)</script>",
361        "unsafe&#92;n## injected&#92;n&lt;script&gt;alert(1)&lt;/script&gt;",
362        "\"unsafe\\n## injected\\n<script>alert(1)</script>\"",
363    )]
364    fn test_report_label_escaping(
365        #[values(Mode::Files, Mode::Folders)] mode: Mode,
366        #[case] label: &str,
367        #[case] markdown_label: &str,
368        #[case] diagnostic_label: &str,
369    ) {
370        let fixture = graph_fixture(&[(label, "safe", Production, 1)], &[]);
371        let (files, folders) = assert_ok!(fixture, "Markup and control characters must be accepted as lexical graph labels");
372
373        let system_under_test = match mode {
374            Mode::Files => Analysis::files(&files, 0),
375            Mode::Folders => Ok(Analysis::folders(&folders, 0)),
376        };
377        let system_under_test = assert_ok!(system_under_test, "Special characters must not prevent threshold analysis");
378        let diagnostic = system_under_test.diagnostic();
379        let markdown = system_under_test.markdown();
380        let expected_diagnostic = format!("- {diagnostic_label}: 1 outgoing dependencies (maximum: 0)");
381        let expected_markdown = format!("- <code>{markdown_label}</code>: 1 outgoing dependencies (maximum: 0)");
382        let diagnostic_lines: Vec<_> = diagnostic.lines().filter(|line| line.starts_with("- ")).collect();
383        let markdown_lines: Vec<_> = markdown.lines().filter(|line| line.starts_with("- ")).collect();
384
385        assert_eq!(vec![expected_diagnostic.as_str()], diagnostic_lines, "Diagnostic labels must remain quoted on one line");
386        assert_eq!(vec![expected_markdown.as_str()], markdown_lines, "Markdown must preserve inline-code escaping");
387        assert!(!markdown.contains("<script>"), "A graph label must not inject HTML into the report");
388        assert!(!markdown.lines().any(|line| line.starts_with("## ")), "A graph label must not inject a report heading");
389    }
390
391    #[rstest]
392    #[case("unsafe\0\u{7}\u{1b}[31m\u{85}", "\"unsafe\\0\\u{7}\\u{1b}[31m\\u{85}\"")]
393    #[case("unsafe\u{2028}\u{202e}", "\"unsafe\\u{2028}\\u{202e}\"")]
394    #[case("quote\"and\\backslash", "\"quote\\\"and\\\\backslash\"")]
395    fn test_diagnostic_control_characters(
396        #[values(Mode::Files, Mode::Folders)] mode: Mode,
397        #[case] label: &str,
398        #[case] escaped: &str,
399    ) {
400        let fixture = graph_fixture(&[(label, "safe", Production, 1)], &[]);
401        let (files, folders) = assert_ok!(fixture, "Non-printing characters must be accepted as lexical graph labels");
402
403        let system_under_test = match mode {
404            Mode::Files => Analysis::files(&files, 0),
405            Mode::Folders => Ok(Analysis::folders(&folders, 0)),
406        };
407        let system_under_test = assert_ok!(system_under_test, "Control characters must not prevent threshold analysis");
408        let diagnostic = system_under_test.diagnostic();
409        let expected = format!("- {escaped}: 1 outgoing dependencies (maximum: 0)");
410
411        assert_eq!(Some(expected.as_str()), diagnostic.lines().last(), "Diagnostic labels must be quoted and control-safe");
412        assert!(diagnostic.chars().all(|character| character == '\n' || !character.is_control()), "Unsafe diagnostic control");
413        assert!(!diagnostic.contains('\u{202e}'), "A graph label must not change the diagnostic text direction");
414    }
415
416    #[cfg(any(unix, windows))]
417    #[rstest]
418    #[case::violating_path(0, true)]
419    #[case::nonviolating_path(1, false)]
420    fn test_file_path_encoding(#[case] maximum: usize, #[case] expected_error: bool) {
421        use std::ffi::OsString;
422
423        #[cfg(unix)]
424        let file_name = {
425            use std::os::unix::ffi::OsStringExt as _;
426            OsString::from_vec(vec![0xff])
427        };
428        #[cfg(windows)]
429        let file_name = {
430            use std::os::windows::ffi::OsStringExt as _;
431            OsString::from_wide(&[0xd800])
432        };
433        let file = file_node_fixture(file_name.into());
434        let file = assert_ok!(file, "A non-UTF-8 filename must remain a valid lexical source path");
435        let edge = FileEdge::new(file.clone(), file.clone(), Production);
436        let fixture = FileGraph::new(BTreeSet::from([file]), BTreeSet::from([edge]));
437        let fixture = assert_ok!(fixture, "A non-UTF-8 source must form a valid file graph");
438        let system_under_test = Analysis::files;
439
440        let result = system_under_test(&fixture, maximum);
441
442        assert_eq!(expected_error, result.is_err(), "Only reported source paths require lossless UTF-8 labels");
443    }
444}