Skip to main content

source_mesh_core/
application.rs

1use std::io::Write;
2use std::num::NonZeroUsize;
3use std::path::PathBuf;
4
5use anyhow::Context as _;
6use anyhow::Result;
7use anyhow::ensure;
8use bon::Builder;
9use derive_new::new;
10use protobuf::Message as _;
11use tempfile::NamedTempFile;
12
13use crate::analyzer::options::Options as AnalyzerOptions;
14use crate::backend::RustAnalyzer;
15use crate::cycle_report::file_report;
16use crate::cycle_report::folder_report;
17use crate::cycles::analyze_files;
18use crate::cycles::analyze_folders;
19use crate::export::Format;
20use crate::export::Options as ExportOptions;
21use crate::outgoing_dependencies::Analysis as OutgoingDependencyAnalysis;
22use crate::outgoing_dependencies::Mode as OutgoingDependencyMode;
23use crate::output_paths::FileOutput;
24use crate::output_paths::InputFile;
25use crate::output_paths::OutputFiles;
26use crate::scip::backend::file_graph;
27use crate::scip::index::ParsedIndex;
28
29/// Applies independently to the file-cycle and folder-cycle reports.
30pub const DEFAULT_CYCLE_LIMIT: NonZeroUsize = match NonZeroUsize::new(10_000) {
31    Some(limit) => limit,
32    None => unreachable!(),
33};
34
35#[derive(new)]
36pub struct Project {
37    path: PathBuf,
38    rust_analyzer_configuration: Option<PathBuf>,
39}
40
41pub enum Input {
42    Project(Project),
43    ScipFile(PathBuf),
44}
45
46#[derive(Builder)]
47pub struct CycleOptions {
48    #[builder(default)]
49    highlight_cycles: bool,
50    #[builder(default)]
51    fail_on_cycles: bool,
52    cycles_output: Option<PathBuf>,
53    file_cycles_output: Option<PathBuf>,
54    #[builder(default = DEFAULT_CYCLE_LIMIT)]
55    cycle_limit: NonZeroUsize,
56}
57
58#[derive(Builder)]
59pub struct OutgoingDependencyOptions {
60    maximum: usize,
61    #[builder(default = OutgoingDependencyMode::Folders)]
62    mode: OutgoingDependencyMode,
63    output: Option<PathBuf>,
64}
65
66#[derive(Builder)]
67pub struct Request {
68    input: Input,
69    #[builder(default = PathBuf::from("."))]
70    root: PathBuf,
71    #[builder(default = Format::Dot)]
72    format: Format,
73    output: Option<PathBuf>,
74    depth: Option<usize>,
75    #[builder(default)]
76    include_self: bool,
77    #[builder(default)]
78    group_folders: bool,
79    #[builder(default)]
80    exclude_tests: bool,
81    #[builder(default = CycleOptions::builder().build())]
82    cycles: CycleOptions,
83    outgoing_dependencies: Option<OutgoingDependencyOptions>,
84    save_scip: Option<PathBuf>,
85    #[builder(default = AnalyzerOptions::new(false))]
86    analyzer: AnalyzerOptions,
87}
88
89/**
90Analyze and export dependencies, writing the diagram to the supplied writer
91unless the request selects an output file.
92
93Analysis and serialization failures leave existing output files unchanged.
94Output files must be distinct and must not overwrite input files.
95Opening failures can leave new empty files; writing failures can leave partial outputs.
96Cycle and outgoing dependency checks fail only after outputs have been written.
97*/
98pub fn run(request: &Request, diagram_output: &mut dyn Write) -> Result<()> {
99    ensure!(
100        !matches!(request.input, Input::ScipFile(_)) || request.save_scip.is_none(),
101        "Cannot save analysis when replaying a SCIP file"
102    );
103    let mut protected_inputs = Vec::new();
104    let index = match request.input {
105        Input::ScipFile(ref path) => {
106            let mut input = InputFile::open(path)?;
107            let bytes = input.read()?;
108            protected_inputs.push(input);
109            ParsedIndex::parse(&bytes).context("Cannot load saved dependency analysis")?
110        }
111        Input::Project(ref project) => {
112            let configuration = project.rust_analyzer_configuration.as_deref().map(|path| -> Result<_> {
113                let mut input = InputFile::open(path)?;
114                let mut snapshot = NamedTempFile::new().context("Cannot create analysis configuration snapshot")?;
115                snapshot.write_all(&input.read()?).context("Cannot write analysis configuration snapshot")?;
116                protected_inputs.push(input);
117                Ok(snapshot)
118            });
119            let configuration = configuration.transpose()?;
120            let configuration_path = configuration.as_ref().map(NamedTempFile::path);
121            RustAnalyzer::new(&project.path, configuration_path, &request.analyzer).index_parsed()?
122        }
123    };
124    let file_graph = file_graph(&index)?;
125    let file_graph = if request.exclude_tests { file_graph.without_test_dependencies() } else { file_graph };
126    let file_graph = file_graph.within_root(&request.root)?;
127    let folder_graph = file_graph.folders(&request.root, request.depth, request.include_self)?;
128    ensure!(!folder_graph.nodes().is_empty(), "No indexed Rust files under root {}", request.root.display());
129    let cycles = &request.cycles;
130    let analyze_folder_cycles = cycles.highlight_cycles || cycles.cycles_output.is_some() || cycles.fail_on_cycles;
131    let (highlight_analysis, folder_report_output, folder_cycle_group_count) = if analyze_folder_cycles {
132        let analysis = analyze_folders(&folder_graph)?;
133        let report = cycles.cycles_output.as_ref().map(|path| {
134            folder_report(&analysis, cycles.cycle_limit).map(|report| (path, report))
135        });
136        let report = report.transpose()?;
137        let group_count = analysis.group_count();
138        (cycles.highlight_cycles.then_some(analysis), report, group_count)
139    } else {
140        (None, None, 0)
141    };
142    let analyze_file_cycles = cycles.file_cycles_output.is_some() || cycles.fail_on_cycles;
143    let (file_report_output, file_cycle_group_count) = if analyze_file_cycles {
144        let analysis = analyze_files(&file_graph)?;
145        let report = cycles.file_cycles_output.as_ref().map(|path| {
146            file_report(&analysis, cycles.cycle_limit).map(|report| (path, report))
147        });
148        let report = report.transpose()?;
149        (report, analysis.group_count())
150    } else {
151        (None, 0)
152    };
153    let (outgoing_analysis, outgoing_report_output) = if let Some(options) = request.outgoing_dependencies.as_ref() {
154        let analysis = match options.mode {
155            OutgoingDependencyMode::Files => OutgoingDependencyAnalysis::files(&file_graph, options.maximum)?,
156            OutgoingDependencyMode::Folders => OutgoingDependencyAnalysis::folders(&folder_graph, options.maximum),
157        };
158        let report = options.output.as_ref().map(|path| (path, analysis.markdown()));
159        (Some(analysis), report)
160    } else {
161        (None, None)
162    };
163    let mut diagram_bytes = Vec::new();
164    let exporter = request.format.exporter();
165    let options = ExportOptions::builder().group_folders(request.group_folders).maybe_cycles(highlight_analysis.as_ref()).build();
166    exporter.write_with_options(&folder_graph, &options, &mut diagram_bytes)?;
167    let saved_index = request.save_scip.as_ref().map(|path| {
168        let serialized = index.into_index().write_to_bytes().context("Cannot serialize dependency analysis");
169        serialized.map(|bytes| (path, bytes))
170    });
171    let saved_index = saved_index.transpose()?;
172    let mut outputs = Vec::new();
173    if let Some((path, ref bytes)) = saved_index {
174        outputs.push(FileOutput::new(path, bytes));
175    }
176    if let Some((path, ref report)) = folder_report_output {
177        outputs.push(FileOutput::new(path, report.as_bytes()));
178    }
179    if let Some((path, ref report)) = file_report_output {
180        outputs.push(FileOutput::new(path, report.as_bytes()));
181    }
182    if let Some((path, ref report)) = outgoing_report_output {
183        outputs.push(FileOutput::new(path, report.as_bytes()));
184    }
185    if let Some(path) = request.output.as_deref() {
186        outputs.push(FileOutput::new(path, &diagram_bytes));
187    }
188    OutputFiles::open(&outputs, &protected_inputs)?.write()?;
189    if request.output.is_none() {
190        diagram_output.write_all(&diagram_bytes)?;
191    }
192    let mut failures = Vec::new();
193    if cycles.fail_on_cycles && (folder_cycle_group_count != 0 || file_cycle_group_count != 0) {
194        failures.push(format!(
195            "Dependency cycles found: {folder_cycle_group_count} folder cycle group(s), \
196             {file_cycle_group_count} file cycle group(s)"
197        ));
198    }
199    if let Some(analysis) = outgoing_analysis && analysis.has_violations() {
200        failures.push(analysis.diagnostic());
201    }
202    ensure!(failures.is_empty(), "{}", failures.join("\n\n"));
203    Ok(())
204}
205
206#[cfg(test)]
207mod tests {
208    use std::fs;
209    use std::path::PathBuf;
210
211    use anyhow::Error;
212    use claims::assert_ok;
213    use claims::assert_some;
214    use pretty_assertions::assert_eq;
215    use protobuf::Message as _;
216    use rstest::rstest;
217    use scip::types::Document;
218    use scip::types::Index;
219    use scip::types::Occurrence;
220    use scip::types::SymbolRole;
221    use tempfile::tempdir;
222
223    use super::CycleOptions;
224    use super::Input;
225    use super::OutgoingDependencyOptions;
226    use super::Request;
227    use super::run;
228    use crate::cycle_report::NO_CYCLES_FOUND;
229    use crate::export::Format;
230    use crate::export::Options;
231    use crate::outgoing_dependencies::Mode;
232    use crate::output_paths::OutputPathConflict;
233    use crate::scip::backend::parse_scip;
234
235    #[test]
236    fn test_saved_analysis_replay() {
237        let fixture = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("src").join("fixtures").join("dependency-graph.scip");
238        let index = fs::read(&fixture);
239        let index = assert_ok!(index, "Saved SCIP fixture must be readable: {}", fixture.display());
240        let graph = parse_scip(&index);
241        let graph = assert_ok!(graph, "Saved SCIP fixture must contain a valid dependency graph");
242        let root = PathBuf::from("src");
243        let within_root = graph.within_root(&root);
244        let within_root = assert_ok!(within_root, "Fixture graph must support the selected source root");
245        let folders = within_root.folders(&root, Some(1), false);
246        let folders = assert_ok!(folders, "Fixture graph must support depth-limited folder aggregation");
247        let mut expected = Vec::new();
248        let export = Format::Mermaid.exporter()
249            .write_with_options(&folders, &Options::builder().group_folders(true).build(), &mut expected);
250        assert_ok!(export, "Expected grouped Mermaid diagram must render successfully");
251        let request = Request::builder().input(Input::ScipFile(fixture)).root(root).format(Format::Mermaid);
252        let system_under_test = request.depth(1).group_folders(true).build();
253        let mut diagram = Vec::new();
254
255        let result = run(&system_under_test, &mut diagram);
256
257        assert_ok!(result, "Replaying saved analysis must produce a dependency diagram");
258        assert_eq!(diagram, expected);
259        assert_ne!(diagram, [] as [u8; 0]);
260    }
261
262    #[must_use]
263    fn two_file_index_fixture(cyclic: bool) -> Index {
264        let first_symbol = "rust-analyzer cargo fixture 0.0.0 first().";
265        let second_symbol = "rust-analyzer cargo fixture 0.0.0 second().";
266        let mut second_occurrences = vec![Occurrence {
267            range: vec![0, 3, 9],
268            symbol: second_symbol.into(),
269            symbol_roles: SymbolRole::Definition as i32,
270            ..Occurrence::default()
271        }];
272        if cyclic {
273            second_occurrences.push(Occurrence { range: vec![1, 0, 5], symbol: first_symbol.into(), ..Occurrence::default() });
274        }
275        Index {
276            documents: vec![
277                Document {
278                    relative_path: "src/first.rs".into(),
279                    occurrences: vec![
280                        Occurrence {
281                            range: vec![0, 3, 8],
282                            symbol: first_symbol.into(),
283                            symbol_roles: SymbolRole::Definition as i32,
284                            ..Occurrence::default()
285                        },
286                        Occurrence { range: vec![1, 0, 6], symbol: second_symbol.into(), ..Occurrence::default() },
287                    ],
288                    ..Document::default()
289                },
290                Document {
291                    relative_path: "src/second.rs".into(),
292                    occurrences: second_occurrences,
293                    ..Document::default()
294                },
295            ],
296            ..Index::default()
297        }
298    }
299
300    #[must_use]
301    fn outgoing_dependency_index_fixture() -> Index {
302        let targets = [
303            ("src/target/first.rs", "first", 0),
304            ("src/target/second.rs", "second", 0),
305            ("src/target/deep/third.rs", "third", 0),
306            ("src/testonly/test.rs", "test_only", SymbolRole::Test as i32),
307            ("outside/external.rs", "external", 0),
308        ];
309        let mut documents = Vec::new();
310        let mut references = Vec::new();
311        for (relative_path, name, symbol_roles) in targets {
312            let symbol = format!("rust-analyzer cargo fixture 0.0.0 {name}().");
313            references.push(Occurrence { symbol: symbol.clone(), symbol_roles, ..Occurrence::default() });
314            documents.push(Document {
315                relative_path: relative_path.into(),
316                occurrences: vec![Occurrence { symbol, symbol_roles: SymbolRole::Definition as i32, ..Occurrence::default() }],
317                ..Document::default()
318            });
319        }
320        documents.push(Document {
321            relative_path: "outside/entry.rs".into(),
322            occurrences: references.clone(),
323            ..Document::default()
324        });
325        documents.push(Document { relative_path: "src/app/entry.rs".into(), occurrences: references, ..Document::default() });
326        Index { documents, ..Index::default() }
327    }
328
329    #[rstest]
330    #[case::files_all(Mode::Files, ".", false, None, &[("outside/entry.rs", 5), ("src/app/entry.rs", 5)])]
331    #[case::folders_all(Mode::Folders, ".", false, None, &[("outside", 3), ("src/app", 4)])]
332    #[case::files_root(Mode::Files, "src", false, None, &[("src/app/entry.rs", 4)])]
333    #[case::folders_root(Mode::Folders, "src", false, None, &[("app", 3)])]
334    #[case::files_production(Mode::Files, "src", true, None, &[("src/app/entry.rs", 3)])]
335    #[case::folders_production(Mode::Folders, "src", true, None, &[("app", 2)])]
336    #[case::files_folded(Mode::Files, "src", true, Some(1), &[("src/app/entry.rs", 3)])]
337    #[case::folders_folded(Mode::Folders, "src", true, Some(1), &[])]
338    #[case::folders_folded_with_tests(Mode::Folders, "src", false, Some(1), &[("app", 2)])]
339    fn test_outgoing_dependency_graph_selection(
340        #[case] mode: Mode,
341        #[case] root: &str,
342        #[case] exclude_tests: bool,
343        #[case] depth: Option<usize>,
344        #[case] expected: &[(&str, usize)],
345    ) {
346        let fixture = tempdir();
347        let fixture = assert_ok!(fixture, "Outgoing dependency fixture directory must be created");
348        let input = fixture.path().join("index.scip");
349        let report_path = fixture.path().join("outgoing.md");
350        let bytes = outgoing_dependency_index_fixture().write_to_bytes();
351        let bytes = assert_ok!(bytes, "Outgoing dependency fixture must serialize");
352        let written = fs::write(&input, bytes);
353        assert_ok!(written, "Outgoing dependency index must be written");
354        let options = OutgoingDependencyOptions::builder().maximum(1).mode(mode).output(report_path.clone()).build();
355        let request = Request::builder().input(Input::ScipFile(input)).root(PathBuf::from(root)).exclude_tests(exclude_tests);
356        let system_under_test = request.maybe_depth(depth).outgoing_dependencies(options).build();
357        let expected_lines: Vec<_> = expected.iter().map(|&(label, count)| {
358            let label = match mode {
359                Mode::Files => PathBuf::from_iter(label.split('/')).to_string_lossy().replace('\\', "&#92;"),
360                Mode::Folders => label.to_owned(),
361            };
362            format!("- <code>{label}</code>: {count} outgoing dependencies (maximum: 1)")
363        }).collect();
364        let mut diagram = Vec::new();
365
366        let result = run(&system_under_test, &mut diagram);
367        let report = fs::read_to_string(report_path);
368        let report = assert_ok!(report, "Outgoing report must be written before a threshold failure");
369        let actual_lines: Vec<_> = report.lines().filter(|line| line.starts_with("- ")).collect();
370
371        assert_eq!(actual_lines, expected_lines, "Report must reflect the selected graph after filtering and folding");
372        assert_eq!(result.is_err(), !expected.is_empty(), "Threshold result disagrees with expected sources: {result:?}");
373        if let Err(error) = result {
374            assert!(error.to_string().contains("Outgoing dependency threshold exceeded"), "Unexpected failure: {error}");
375        }
376        if expected.is_empty() {
377            assert!(report.contains("No outgoing dependency violations"), "Passing reports must state that no sources violate");
378        }
379        let mode_label = match mode { Mode::Files => "files", Mode::Folders => "folders" };
380        assert!(report.contains(&format!("Mode: {mode_label}")), "Report must identify the selected mode");
381        assert!(report.contains("Maximum: 1"), "Report must include the requested maximum");
382        assert!(!diagram.is_empty(), "Graph checks must run after diagram output is written");
383    }
384
385    #[rstest]
386    #[case::disabled(false, None, true, 0, false)]
387    #[case::default_folders(true, None, false, 0, false)]
388    #[case::default_folder_self(true, None, true, 0, true)]
389    #[case::files_without_self(true, Some(Mode::Files), false, 0, true)]
390    #[case::files_with_self(true, Some(Mode::Files), true, 0, true)]
391    #[case::folder_equality(true, Some(Mode::Folders), true, 1, false)]
392    #[case::file_equality(true, Some(Mode::Files), false, 1, false)]
393    fn test_outgoing_dependency_gate_and_outputs(
394        #[case] enabled: bool,
395        #[case] mode: Option<Mode>,
396        #[case] include_self: bool,
397        #[case] maximum: usize,
398        #[case] expected_failure: bool,
399        #[values(false, true)] report_requested: bool,
400    ) {
401        const CONTENTS_EXISTING: &str = "preserved";
402        let fixture = tempdir();
403        let fixture = assert_ok!(fixture, "Outgoing gate fixture directory must be created");
404        let input = fixture.path().join("index.scip");
405        let output = fixture.path().join("diagram.dot");
406        let report_path = fixture.path().join("outgoing.md");
407        let bytes = two_file_index_fixture(false).write_to_bytes();
408        let bytes = assert_ok!(bytes, "Same-folder dependency fixture must serialize");
409        let index_write = fs::write(&input, bytes);
410        assert_ok!(index_write, "Same-folder dependency index must be written");
411        let diagram_write = fs::write(&output, CONTENTS_EXISTING);
412        assert_ok!(diagram_write, "Existing diagram must be initialized before the outgoing gate");
413        let write_report = enabled && report_requested;
414        if write_report {
415            let report_write = fs::write(&report_path, CONTENTS_EXISTING);
416            assert_ok!(report_write, "Existing outgoing report must be initialized before the gate");
417        }
418        let options = OutgoingDependencyOptions::builder().maximum(maximum);
419        let options = options.maybe_output(report_requested.then(|| report_path.clone()));
420        let options = match mode { Some(mode) => options.mode(mode).build(), None => options.build() };
421        let request = Request::builder().input(Input::ScipFile(input)).root(PathBuf::from("src")).include_self(include_self);
422        let system_under_test = request.output(output.clone()).maybe_outgoing_dependencies(enabled.then_some(options)).build();
423        let mut diagram = Vec::new();
424
425        let result = run(&system_under_test, &mut diagram);
426        let exported = fs::read_to_string(output);
427        let exported = assert_ok!(exported, "Diagram must be readable after the outgoing gate");
428        let report_exists = report_path.try_exists();
429        let report_exists = assert_ok!(report_exists, "Outgoing report path must be inspectable");
430
431        assert_eq!(result.is_err(), expected_failure, "Unexpected outgoing threshold result: {result:?}");
432        if let Err(error) = result {
433            assert!(error.to_string().contains("Outgoing dependency threshold exceeded"), "Unexpected gate failure: {error}");
434        }
435        assert!(exported.contains("digraph"), "The requested diagram must replace existing output before gating");
436        assert_eq!(diagram, [] as [u8; 0], "An output-file request must not also write the diagram to the supplied writer");
437        assert_eq!(report_exists, write_report, "Only an enabled check with an output path should write a report");
438        if write_report {
439            let report = fs::read_to_string(report_path);
440            let report = assert_ok!(report, "Requested outgoing report must remain readable after gating");
441            let actual_lines: Vec<_> = report.lines().filter(|line| line.starts_with("- ")).collect();
442            let expected_lines = if expected_failure {
443                let label = if matches!(mode, Some(Mode::Files)) {
444                    PathBuf::from("src").join("first.rs").to_string_lossy().replace('\\', "&#92;")
445                } else {
446                    String::from(".")
447                };
448                vec![format!("- <code>{label}</code>: 1 outgoing dependencies (maximum: {maximum})")]
449            } else {
450                Vec::new()
451            };
452            assert_eq!(actual_lines, expected_lines, "File targets must not inherit folder self-edge filtering");
453            if !expected_failure {
454                assert!(report.contains("No outgoing dependency violations"), "Equality and zero targets must pass the check");
455            }
456        }
457    }
458
459    #[rstest]
460    #[case::cyclic_neither(true, false, false, None)]
461    #[case::cyclic_report_only(true, true, false, None)]
462    #[case::cyclic_gate_only(true, false, true, Some(1))]
463    #[case::cyclic_report_and_gate(true, true, true, Some(1))]
464    #[case::acyclic_neither(false, false, false, None)]
465    #[case::acyclic_report_only(false, true, false, None)]
466    #[case::acyclic_gate_only(false, false, true, None)]
467    #[case::acyclic_report_and_gate(false, true, true, None)]
468    fn test_file_cycle_report_and_gate_flags(
469        #[case] cyclic: bool,
470        #[case] report_requested: bool,
471        #[case] fail_on_cycles: bool,
472        #[case] expected_file_cycle_groups: Option<usize>,
473        #[values(false, true)] outgoing_requested: bool,
474    ) {
475        let fixture = tempdir();
476        let fixture = assert_ok!(fixture, "Cycle report fixture directory must be created");
477        let input = fixture.path().join("index.scip");
478        let file_report = fixture.path().join("files.md");
479        let outgoing_report = fixture.path().join("outgoing.md");
480        let bytes = two_file_index_fixture(cyclic).write_to_bytes();
481        let bytes = assert_ok!(bytes, "Two-file cycle fixture must serialize");
482        let written = fs::write(&input, bytes);
483        assert_ok!(written, "Cycle fixture index must be written: {}", input.display());
484        let cycles = CycleOptions::builder().fail_on_cycles(fail_on_cycles);
485        let cycles = cycles.maybe_file_cycles_output(report_requested.then(|| file_report.clone())).build();
486        let outgoing = outgoing_requested.then(|| {
487            OutgoingDependencyOptions::builder().maximum(0).mode(Mode::Files).output(outgoing_report.clone()).build()
488        });
489        /* Same-folder files and disabled self-edges keep the folder gate from masking skipped file analysis. */
490        let request = Request::builder().input(Input::ScipFile(input)).root(PathBuf::from("src")).include_self(false);
491        let system_under_test = request.cycles(cycles).maybe_outgoing_dependencies(outgoing).build();
492        let expected_error = expected_file_cycle_groups.map(|groups| {
493            format!("Dependency cycles found: 0 folder cycle group(s), {groups} file cycle group(s)")
494        });
495        let mut diagram = Vec::new();
496
497        let result = run(&system_under_test, &mut diagram);
498
499        let actual_error = result.err().map(|error| error.to_string());
500        if outgoing_requested {
501            let error = assert_some!(actual_error, "The zero outgoing maximum must reject the fixture's file dependencies");
502            assert!(error.contains("Outgoing dependency threshold exceeded"), "Combined gate omitted the outgoing reason");
503            assert_eq!(error.contains("Dependency cycles found:"), expected_error.is_some(), "Cycle checks are independent");
504            if let Some(expected_error) = expected_error {
505                assert!(error.contains(&expected_error), "Combined gate omitted the cycle reason: {error}");
506            }
507            let report = fs::read_to_string(outgoing_report);
508            let report = assert_ok!(report, "Outgoing report must be written even when both dependency checks fail");
509            let violations = report.lines().filter(|line| line.starts_with("- ")).count();
510            assert_eq!(violations, if cyclic { 2 } else { 1 }, "Outgoing report must include every violating source");
511            assert!(report.contains("first.rs</code>: 1 outgoing dependencies (maximum: 0)"), "First source count is missing");
512            let second_source = report.contains("second.rs</code>: 1 outgoing dependencies (maximum: 0)");
513            assert_eq!(second_source, cyclic, "Only a cyclic fixture has an outgoing dependency from the second source");
514        } else {
515            assert_eq!(actual_error, expected_error);
516        }
517        assert!(!diagram.is_empty(), "Cycle gating must happen after diagram output is written");
518        let report_exists = file_report.try_exists();
519        let report_exists = assert_ok!(report_exists, "File-cycle report path must be inspectable");
520        assert_eq!(report_exists, report_requested, "Only a requested file-cycle report should be written");
521        if report_requested {
522            let report = fs::read_to_string(file_report);
523            let report = assert_ok!(report, "Requested file-cycle report must be readable");
524            assert_eq!(report.lines().next(), Some("# File dependency cycles"));
525            let cycle_groups = report.lines().filter(|line| line.starts_with("## ")).count();
526            assert_eq!(cycle_groups, usize::from(cyclic));
527            if cyclic {
528                assert!(report.contains("first.rs</code>"), "File-cycle report omitted the first file");
529                assert!(report.contains("second.rs</code>"), "File-cycle report omitted the second file");
530                assert!(!report.contains(NO_CYCLES_FOUND), "File-cycle report incorrectly claims there are no cycles");
531            } else {
532                assert_eq!(report.lines().last(), Some(NO_CYCLES_FOUND));
533            }
534        }
535    }
536
537    #[test]
538    fn test_replay_cannot_save_analysis() {
539        const CONTENTS_EXISTING: &str = "preserved";
540        let fixture = tempdir();
541        let fixture = assert_ok!(fixture, "Replay output fixture directory must be created");
542        let output = fixture.path().join("index.scip");
543        let written = fs::write(&output, CONTENTS_EXISTING);
544        assert_ok!(written, "Existing analysis output must be initialized");
545        let input = Input::ScipFile(fixture.path().join("missing.scip"));
546        let system_under_test = Request::builder().input(input).save_scip(output.clone()).build();
547        let mut diagram = Vec::new();
548
549        let result = run(&system_under_test, &mut diagram);
550        let preserved = fs::read_to_string(output);
551        let preserved = assert_ok!(preserved, "Rejected replay must leave the existing analysis output readable");
552
553        assert!(
554            result.as_ref().is_err_and(|error| error.to_string().contains("Cannot save analysis")),
555            "Replay must reject saving a new analysis: {result:?}"
556        );
557        assert_eq!(preserved, CONTENTS_EXISTING);
558        assert_eq!(diagram, [] as [u8; 0]);
559    }
560
561    #[rstest]
562    #[case::same_path(false)]
563    #[case::hard_link(true)]
564    fn test_replay_cannot_overwrite_input(#[case] alias: bool, #[values(false, true)] outgoing_report: bool) {
565        let fixture = tempdir();
566        let fixture = assert_ok!(fixture, "Protected input fixture directory must be created");
567        let input = fixture.path().join("index.scip");
568        let bytes = two_file_index_fixture(false).write_to_bytes();
569        let bytes = assert_ok!(bytes, "Protected input fixture must serialize");
570        let written = fs::write(&input, &bytes);
571        assert_ok!(written, "Protected SCIP input must be initialized");
572        let output = if alias {
573            let output = fixture.path().join("alias.scip");
574            let linked = fs::hard_link(&input, &output);
575            assert_ok!(linked, "Output alias must refer to the protected input file");
576            output
577        } else {
578            input.clone()
579        };
580        let request = Request::builder().input(Input::ScipFile(input.clone()));
581        let system_under_test = if outgoing_report {
582            let options = OutgoingDependencyOptions::builder().maximum(usize::MAX).output(output).build();
583            request.outgoing_dependencies(options).build()
584        } else {
585            request.output(output).build()
586        };
587        let mut diagram = Vec::new();
588
589        let result = run(&system_under_test, &mut diagram);
590        let preserved = fs::read(input);
591        let preserved = assert_ok!(preserved, "Protected SCIP input must remain readable after replay rejection");
592
593        assert!(result.as_ref().is_err_and(Error::is::<OutputPathConflict>), "Replay must protect input aliases: {result:?}");
594        assert_eq!(preserved, bytes);
595        assert_eq!(diagram, [] as [u8; 0]);
596    }
597
598    #[rstest]
599    #[case::empty(b"")]
600    #[case::malformed(b"\xff")]
601    fn test_invalid_index_preserves_outputs(#[case] bytes: &[u8], #[values(false, true)] existing_report: bool) {
602        const CONTENTS_EXISTING: &str = "preserved";
603        let fixture = tempdir();
604        let fixture = assert_ok!(fixture, "Invalid-index fixture directory must be created");
605        let input = fixture.path().join("index.scip");
606        let output = fixture.path().join("diagram.dot");
607        let folder_report = fixture.path().join("folders.json");
608        let file_report = fixture.path().join("files.json");
609        let outgoing_report = fixture.path().join("outgoing.md");
610        let input_write = fs::write(&input, bytes);
611        assert_ok!(input_write, "Invalid SCIP bytes must be written for the rejection check");
612        let diagram_write = fs::write(&output, CONTENTS_EXISTING);
613        assert_ok!(diagram_write, "Existing diagram must be initialized before invalid-index replay");
614        if existing_report {
615            let report_write = fs::write(&outgoing_report, CONTENTS_EXISTING);
616            assert_ok!(report_write, "Existing outgoing report must be initialized before invalid-index replay");
617        }
618        let outgoing = OutgoingDependencyOptions::builder().maximum(0).output(outgoing_report.clone()).build();
619        let cycles = CycleOptions::builder().cycles_output(folder_report.clone());
620        let cycles = cycles.file_cycles_output(file_report.clone()).build();
621        let request = Request::builder().input(Input::ScipFile(input)).output(output.clone()).cycles(cycles);
622        let system_under_test = request.outgoing_dependencies(outgoing).build();
623        let mut diagram = Vec::new();
624
625        let result = run(&system_under_test, &mut diagram);
626        let preserved = fs::read_to_string(output);
627        let preserved = assert_ok!(preserved, "Existing diagram must remain readable after invalid-index rejection");
628
629        assert!(result.is_err(), "Malformed external analysis must return an error");
630        assert_eq!(preserved, CONTENTS_EXISTING);
631        let folder_report_exists = folder_report.try_exists();
632        let folder_report_exists = assert_ok!(folder_report_exists, "Folder report path must be inspectable");
633        assert!(!folder_report_exists, "Invalid input created a folder report");
634        let file_report_exists = file_report.try_exists();
635        let file_report_exists = assert_ok!(file_report_exists, "File report path must be inspectable");
636        assert!(!file_report_exists, "Invalid input created a file report");
637        let outgoing_report_exists = outgoing_report.try_exists();
638        let outgoing_report_exists = assert_ok!(outgoing_report_exists, "Outgoing report path must be inspectable");
639        assert_eq!(outgoing_report_exists, existing_report, "Invalid input must not create an outgoing report");
640        if existing_report {
641            let preserved_report = fs::read_to_string(outgoing_report);
642            let preserved_report = assert_ok!(preserved_report, "Invalid input must leave the existing outgoing report readable");
643            assert_eq!(preserved_report, CONTENTS_EXISTING, "Invalid input must not replace an outgoing report");
644        }
645        assert_eq!(diagram, [] as [u8; 0]);
646    }
647
648    #[rstest]
649    #[case::empty("")]
650    #[case::parent("../outside.rs")]
651    #[case::absolute("/absolute.rs")]
652    fn test_invalid_source_path_preserves_outputs(#[case] path: &str) {
653        let fixture = tempdir();
654        let fixture = assert_ok!(fixture, "Invalid-source-path fixture directory must be created");
655        let input = fixture.path().join("index.scip");
656        let output = fixture.path().join("diagram.dot");
657        let index = Index { documents: vec![Document { relative_path: path.into(), ..Document::default() }], ..Index::default() };
658        let bytes = index.write_to_bytes();
659        let bytes = assert_ok!(bytes, "Index with an invalid source path must serialize before validation");
660        let written = fs::write(&input, bytes);
661        assert_ok!(written, "Invalid-source-path index must be written");
662        let system_under_test = Request::builder().input(Input::ScipFile(input)).output(output.clone()).build();
663        let mut diagram = Vec::new();
664
665        let result = run(&system_under_test, &mut diagram);
666
667        assert!(result.is_err(), "Malformed external source paths must return an error");
668        let output_exists = output.try_exists();
669        let output_exists = assert_ok!(output_exists, "Diagram output path must be inspectable");
670        assert!(!output_exists, "Invalid input created a diagram");
671        assert_eq!(diagram, [] as [u8; 0]);
672    }
673
674    #[rstest]
675    #[case::same_path(false)]
676    #[case::hard_link(true)]
677    fn test_conflicting_outputs_preserve_files(#[case] alias: bool, #[values(false, true)] outgoing_report: bool) {
678        const CONTENTS_EXISTING: &str = "preserved";
679        let fixture = tempdir();
680        let fixture = assert_ok!(fixture, "Conflicting-output fixture directory must be created");
681        let input = fixture.path().join("index.scip");
682        let output = fixture.path().join("diagram.dot");
683        let file_report = fixture.path().join("files.json");
684        let bytes = two_file_index_fixture(false).write_to_bytes();
685        let bytes = assert_ok!(bytes, "Conflicting-output fixture must serialize");
686        let input_write = fs::write(&input, bytes);
687        assert_ok!(input_write, "Valid SCIP input must be initialized before output conflict validation");
688        let diagram_write = fs::write(&output, CONTENTS_EXISTING);
689        assert_ok!(diagram_write, "Existing diagram must be initialized before output conflict validation");
690        let report_write = fs::write(&file_report, CONTENTS_EXISTING);
691        assert_ok!(report_write, "File-cycle report must be written before testing output conflicts");
692        let conflicting_report = if alias {
693            let report = fixture.path().join("conflict.md");
694            let linked = fs::hard_link(&output, &report);
695            assert_ok!(linked, "Conflicting report alias must refer to the existing diagram");
696            report
697        } else {
698            output.clone()
699        };
700        let cycles = CycleOptions::builder().file_cycles_output(file_report.clone());
701        let request = Request::builder().input(Input::ScipFile(input)).output(output.clone());
702        let system_under_test = if outgoing_report {
703            let outgoing = OutgoingDependencyOptions::builder().maximum(usize::MAX).output(conflicting_report).build();
704            request.cycles(cycles.build()).outgoing_dependencies(outgoing).build()
705        } else {
706            request.cycles(cycles.cycles_output(conflicting_report).build()).build()
707        };
708        let mut diagram = Vec::new();
709
710        let result = run(&system_under_test, &mut diagram);
711        let preserved_diagram = fs::read_to_string(output);
712        let preserved_diagram = assert_ok!(preserved_diagram, "Diagram must remain readable after output conflicts");
713        let preserved_report = fs::read_to_string(file_report);
714        let preserved_report = assert_ok!(preserved_report, "File report must remain readable after output conflicts");
715
716        assert!(result.as_ref().is_err_and(Error::is::<OutputPathConflict>), "Replay must reject output aliases: {result:?}");
717        assert_eq!(preserved_diagram, CONTENTS_EXISTING);
718        assert_eq!(preserved_report, CONTENTS_EXISTING);
719        assert_eq!(diagram, [] as [u8; 0]);
720    }
721}