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