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::Exclusions;
14use crate::analyzer::options::Options as AnalyzerOptions;
15use crate::backend::RustAnalyzer;
16use crate::cycle_report::file_report;
17use crate::cycle_report::folder_report;
18use crate::cycles::analyze_files;
19use crate::cycles::analyze_folders;
20use crate::export::Format;
21use crate::export::Options as ExportOptions;
22use crate::outgoing_dependencies::Analysis as OutgoingDependencyAnalysis;
23use crate::outgoing_dependencies::Mode as OutgoingDependencyMode;
24use crate::output_paths::FileOutput;
25use crate::output_paths::InputFile;
26use crate::output_paths::OutputFiles;
27use crate::scip::backend::file_graph;
28use crate::scip::index::ParsedIndex;
29
30const NO_FILES_AFTER_FILTERING: &str = "No indexed Rust files remain after applying root and file filters";
31
32pub const DEFAULT_CYCLE_LIMIT: NonZeroUsize = match NonZeroUsize::new(10_000) {
33    Some(limit) => limit,
34    None => unreachable!(),
35};
36
37#[derive(new)]
38pub struct Project {
39    path: PathBuf,
40    rust_analyzer_configuration: Option<PathBuf>,
41}
42
43pub enum Input {
44    Project(Project),
45    ScipFile(PathBuf),
46}
47
48enum PreparedInput {
49    Project(Project),
50    ScipFile { index: ParsedIndex, protected_input: InputFile },
51}
52
53impl TryFrom<Input> for PreparedInput {
54    type Error = anyhow::Error;
55
56    fn try_from(input: Input) -> Result<Self> {
57        match input {
58            Input::Project(project) => Ok(Self::Project(project)),
59            Input::ScipFile(path) => {
60                let mut protected_input = InputFile::open(&path)?;
61                let bytes = protected_input.read()?;
62                let index = ParsedIndex::parse(&bytes).context("Cannot load saved dependency analysis")?;
63                Ok(Self::ScipFile { index, protected_input })
64            }
65        }
66    }
67}
68
69#[derive(Builder)]
70pub struct CycleOptions {
71    #[builder(default)]
72    highlight_cycles: bool,
73    #[builder(default)]
74    fail_on_cycles: bool,
75    cycles_output: Option<PathBuf>,
76    file_cycles_output: Option<PathBuf>,
77    #[builder(default = DEFAULT_CYCLE_LIMIT)]
78    cycle_limit: NonZeroUsize,
79}
80
81#[derive(Builder)]
82pub struct OutgoingDependencyOptions {
83    maximum: usize,
84    #[builder(default = OutgoingDependencyMode::Folders)]
85    mode: OutgoingDependencyMode,
86    output: Option<PathBuf>,
87}
88
89pub struct Request {
90    input: PreparedInput,
91    root: PathBuf,
92    format: Format,
93    output: Option<PathBuf>,
94    depth: Option<usize>,
95    include_self: bool,
96    group_folders: bool,
97    exclude_tests: bool,
98    exclusions: Exclusions,
99    cycles: CycleOptions,
100    outgoing_dependencies: Option<OutgoingDependencyOptions>,
101    save_scip: Option<PathBuf>,
102    protected_inputs: Vec<InputFile>,
103    analyzer: AnalyzerOptions,
104}
105
106#[bon::bon]
107impl Request {
108    #[builder]
109    pub fn new(
110        input: Input,
111        #[builder(default = PathBuf::from("."))] root: PathBuf,
112        #[builder(default = Format::Dot)] format: Format,
113        output: Option<PathBuf>,
114        depth: Option<usize>,
115        #[builder(default)] include_self: bool,
116        #[builder(default)] group_folders: bool,
117        #[builder(default)] exclude_tests: bool,
118        #[builder(default)] exclusions: Exclusions,
119        #[builder(default = CycleOptions::builder().build())] cycles: CycleOptions,
120        outgoing_dependencies: Option<OutgoingDependencyOptions>,
121        save_scip: Option<PathBuf>,
122        #[builder(default)] protected_inputs: Vec<InputFile>,
123        #[builder(default = AnalyzerOptions::new(false))] analyzer: AnalyzerOptions,
124    ) -> Result<Self> {
125        ensure!(!matches!(input, Input::ScipFile(_)) || save_scip.is_none(), "Cannot save analysis when replaying a SCIP file");
126        let input = PreparedInput::try_from(input)?;
127        Ok(Self {
128            input, root, format, output, depth, include_self, group_folders, exclude_tests, exclusions,
129            cycles, outgoing_dependencies, save_scip, protected_inputs, analyzer,
130        })
131    }
132}
133
134pub fn run(request: &Request, diagram_output: &mut dyn Write) -> Result<()> {
135    let mut retained_inputs = Vec::new();
136    let (file_graph, saved_index, replay_input) = match request.input {
137        PreparedInput::ScipFile { ref index, ref protected_input } => (file_graph(index)?, None, Some(protected_input)),
138        PreparedInput::Project(ref project) => {
139            let configuration = project.rust_analyzer_configuration.as_deref().map(|path| -> Result<_> {
140                let mut input = InputFile::open(path)?;
141                let mut snapshot = NamedTempFile::new().context("Cannot create analysis configuration snapshot")?;
142                snapshot.write_all(&input.read()?).context("Cannot write analysis configuration snapshot")?;
143                retained_inputs.push(input);
144                Ok(snapshot)
145            });
146            let configuration = configuration.transpose()?;
147            let configuration_path = configuration.as_ref().map(NamedTempFile::path);
148            let index = RustAnalyzer::new(&project.path, configuration_path, &request.analyzer).index_parsed()?;
149            let graph = file_graph(&index)?;
150            let saved_index = request.save_scip.as_ref().map(|path| {
151                let serialized = index.into_index().write_to_bytes().context("Cannot serialize dependency analysis");
152                serialized.map(|bytes| (path, bytes))
153            }).transpose()?;
154            (graph, saved_index, None)
155        }
156    };
157    let file_graph = if request.exclude_tests { file_graph.without_test_dependencies() } else { file_graph };
158    let file_graph = file_graph.within_root(&request.root)?.excluding(&request.exclusions);
159    let folder_graph = file_graph.folders(&request.root, request.depth, request.include_self)?;
160    ensure!(!folder_graph.nodes().is_empty(), "{NO_FILES_AFTER_FILTERING}: root {}", request.root.display());
161    let cycles = &request.cycles;
162    let analyze_folder_cycles = cycles.highlight_cycles || cycles.cycles_output.is_some() || cycles.fail_on_cycles;
163    let (highlight_analysis, folder_report_output, folder_cycle_group_count) = if analyze_folder_cycles {
164        let analysis = analyze_folders(&folder_graph)?;
165        let report = cycles.cycles_output.as_ref().map(|path| {
166            folder_report(&analysis, cycles.cycle_limit).map(|report| (path, report))
167        });
168        let report = report.transpose()?;
169        let group_count = analysis.group_count();
170        (cycles.highlight_cycles.then_some(analysis), report, group_count)
171    } else {
172        (None, None, 0)
173    };
174    let analyze_file_cycles = cycles.file_cycles_output.is_some() || cycles.fail_on_cycles;
175    let (file_report_output, file_cycle_group_count) = if analyze_file_cycles {
176        let analysis = analyze_files(&file_graph)?;
177        let report = cycles.file_cycles_output.as_ref().map(|path| {
178            file_report(&analysis, cycles.cycle_limit).map(|report| (path, report))
179        });
180        let report = report.transpose()?;
181        (report, analysis.group_count())
182    } else {
183        (None, 0)
184    };
185    let (outgoing_analysis, outgoing_report_output) = if let Some(options) = request.outgoing_dependencies.as_ref() {
186        let analysis = match options.mode {
187            OutgoingDependencyMode::Files => OutgoingDependencyAnalysis::files(&file_graph, options.maximum)?,
188            OutgoingDependencyMode::Folders => OutgoingDependencyAnalysis::folders(&folder_graph, options.maximum),
189        };
190        let report = options.output.as_ref().map(|path| (path, analysis.markdown()));
191        (Some(analysis), report)
192    } else {
193        (None, None)
194    };
195    let mut diagram_bytes = Vec::new();
196    let exporter = request.format.exporter();
197    let options = ExportOptions::builder().group_folders(request.group_folders).maybe_cycles(highlight_analysis.as_ref()).build();
198    exporter.write_with_options(&folder_graph, &options, &mut diagram_bytes)?;
199
200    let mut outputs = Vec::new();
201    if let Some((path, ref bytes)) = saved_index {
202        outputs.push(FileOutput::new(path, bytes));
203    }
204    if let Some((path, ref report)) = folder_report_output {
205        outputs.push(FileOutput::new(path, report.as_bytes()));
206    }
207    if let Some((path, ref report)) = file_report_output {
208        outputs.push(FileOutput::new(path, report.as_bytes()));
209    }
210    if let Some((path, ref report)) = outgoing_report_output {
211        outputs.push(FileOutput::new(path, report.as_bytes()));
212    }
213    if let Some(path) = request.output.as_deref() {
214        outputs.push(FileOutput::new(path, &diagram_bytes));
215    }
216    let protected_inputs: Vec<_> = retained_inputs.iter().chain(&request.protected_inputs).chain(replay_input).collect();
217    OutputFiles::open(&outputs, &protected_inputs)?.write()?;
218    if request.output.is_none() {
219        diagram_output.write_all(&diagram_bytes)?;
220    }
221    let mut failures = Vec::new();
222    if cycles.fail_on_cycles && (folder_cycle_group_count != 0 || file_cycle_group_count != 0) {
223        failures.push(format!(
224            "Dependency cycles found: {folder_cycle_group_count} folder cycle group(s), \
225             {file_cycle_group_count} file cycle group(s)"
226        ));
227    }
228    if let Some(analysis) = outgoing_analysis && analysis.has_violations() {
229        failures.push(analysis.diagnostic());
230    }
231    ensure!(failures.is_empty(), "{}", failures.join("\n\n"));
232    Ok(())
233}
234
235#[cfg(test)]
236mod tests {
237    use std::fs;
238    use std::path::Path;
239    use std::path::PathBuf;
240
241    use anyhow::Context as _;
242    use anyhow::Error;
243    use anyhow::Result;
244    use claims::assert_ok;
245    use claims::assert_some;
246    use pretty_assertions::assert_eq;
247    use protobuf::Message as _;
248    use rstest::rstest;
249    use scip::types::Document;
250    use scip::types::Index;
251    use scip::types::Occurrence;
252    use scip::types::SymbolRole;
253    use tempfile::TempDir;
254    use tempfile::tempdir;
255
256    use super::CycleOptions;
257    use super::Input;
258    use super::NO_FILES_AFTER_FILTERING;
259    use super::OutgoingDependencyOptions;
260    use super::Request;
261    use super::run;
262    use crate::Exclusions;
263    use crate::InputFile;
264    use crate::export::Format;
265    use crate::export::Options;
266    use crate::outgoing_dependencies::Mode;
267    use crate::output_paths::OutputPathConflict;
268    use crate::scip::backend::parse_scip;
269
270    struct ReplayTestFixture {
271        directory: TempDir,
272        index: PathBuf,
273        index_bytes: Vec<u8>,
274        diagram: PathBuf,
275        file_report: PathBuf,
276        folder_report: PathBuf,
277        outgoing_report: PathBuf,
278    }
279
280    fn replay_bytes_test_fixture(index_bytes: Vec<u8>) -> Result<ReplayTestFixture> {
281        let directory = tempdir()?;
282        let fixture = ReplayTestFixture {
283            index: directory.path().join("index.scip"),
284            diagram: directory.path().join("diagram.dot"),
285            file_report: directory.path().join("files.md"),
286            folder_report: directory.path().join("folders.md"),
287            outgoing_report: directory.path().join("outgoing.md"),
288            directory, index_bytes,
289        };
290        fs::write(&fixture.index, &fixture.index_bytes)?;
291        Ok(fixture)
292    }
293
294    fn replay_test_fixture(index: &Index) -> Result<(ReplayTestFixture, Request)> {
295        let fixture = replay_bytes_test_fixture(index.write_to_bytes()?)?;
296        let request = Request::builder().input(Input::ScipFile(fixture.index.clone())).root(PathBuf::from("src")).build()?;
297        Ok((fixture, request))
298    }
299
300    #[must_use]
301    fn cycle_reports_test_fixture(file_report: &Path, folder_report: &Path) -> CycleOptions {
302        let options = CycleOptions::builder().file_cycles_output(file_report.to_path_buf());
303        options.cycles_output(folder_report.to_path_buf()).build()
304    }
305
306    #[must_use]
307    fn outgoing_options_test_fixture(output: Option<&Path>, maximum: usize, mode: Option<Mode>) -> OutgoingDependencyOptions {
308        let options = OutgoingDependencyOptions::builder().maximum(maximum).maybe_mode(mode);
309        options.maybe_output(output.map(Path::to_path_buf)).build()
310    }
311
312    fn write_outputs_test_fixture(paths: &[&Path], contents: &str) -> Result<()> {
313        for path in paths {
314            fs::write(path, contents).with_context(|| format!("Cannot initialize fixture output {}", path.display()))?;
315        }
316        Ok(())
317    }
318
319    fn read_outputs_test_fixture(paths: &[&Path]) -> Result<Vec<String>> {
320        paths.iter().map(|path| {
321            fs::read_to_string(path).with_context(|| format!("Cannot read fixture output {}", path.display()))
322        }).collect()
323    }
324
325    fn output_alias_test_fixture(path: &Path, alias: bool) -> Result<PathBuf> {
326        if alias {
327            let output = path.with_extension("alias");
328            fs::hard_link(path, &output)?;
329            Ok(output)
330        } else {
331            Ok(path.to_path_buf())
332        }
333    }
334
335    #[must_use]
336    fn request_output_test_fixture(mut request: Request, output: PathBuf, outgoing_report: bool) -> Request {
337        if outgoing_report {
338            request.outgoing_dependencies = Some(outgoing_options_test_fixture(Some(&output), usize::MAX, None));
339        } else {
340            request.output = Some(output);
341        }
342        request
343    }
344
345    #[test]
346    fn test_saved_analysis_replay() {
347        let fixture = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("src").join("fixtures").join("dependency-graph.scip");
348        let index = fs::read(&fixture);
349        let index = assert_ok!(index, "Saved SCIP fixture must be readable: {}", fixture.display());
350        let graph = parse_scip(&index);
351        let graph = assert_ok!(graph, "Saved SCIP fixture must contain a valid dependency graph");
352        let root = PathBuf::from("src");
353        let within_root = graph.within_root(&root);
354        let within_root = assert_ok!(within_root, "Fixture graph must support the selected source root");
355        let folders = within_root.folders(&root, Some(1), false);
356        let folders = assert_ok!(folders, "Fixture graph must support depth-limited folder aggregation");
357        let mut expected = Vec::new();
358        let export = Format::Mermaid.exporter()
359            .write_with_options(&folders, &Options::builder().group_folders(true).build(), &mut expected);
360        assert_ok!(export, "Expected grouped Mermaid diagram must render successfully");
361        let request = Request::builder().input(Input::ScipFile(fixture)).root(root).format(Format::Mermaid);
362        let system_under_test = request.depth(1).group_folders(true).build();
363        let system_under_test = assert_ok!(system_under_test, "Saved analysis must load during request construction");
364        let mut diagram = Vec::new();
365
366        let result = run(&system_under_test, &mut diagram);
367
368        assert_ok!(result, "Replaying saved analysis must produce a dependency diagram");
369        assert_eq!(diagram, expected);
370        assert_ne!(diagram, [] as [u8; 0]);
371    }
372
373    #[must_use]
374    fn two_file_index_fixture(cyclic: bool) -> Index {
375        let first_symbol = "rust-analyzer cargo fixture 0.0.0 first().";
376        let second_symbol = "rust-analyzer cargo fixture 0.0.0 second().";
377        let mut second_occurrences = vec![Occurrence {
378            range: vec![0, 3, 9],
379            symbol: second_symbol.into(),
380            symbol_roles: SymbolRole::Definition as i32,
381            ..Occurrence::default()
382        }];
383        if cyclic {
384            second_occurrences.push(Occurrence { range: vec![1, 0, 5], symbol: first_symbol.into(), ..Occurrence::default() });
385        }
386        Index {
387            documents: vec![
388                Document {
389                    relative_path: "src/first.rs".into(),
390                    occurrences: vec![
391                        Occurrence {
392                            range: vec![0, 3, 8],
393                            symbol: first_symbol.into(),
394                            symbol_roles: SymbolRole::Definition as i32,
395                            ..Occurrence::default()
396                        },
397                        Occurrence { range: vec![1, 0, 6], symbol: second_symbol.into(), ..Occurrence::default() },
398                    ],
399                    ..Document::default()
400                },
401                Document {
402                    relative_path: "src/second.rs".into(),
403                    occurrences: second_occurrences,
404                    ..Document::default()
405                },
406            ],
407            ..Index::default()
408        }
409    }
410
411    #[must_use]
412    fn outgoing_dependency_index_fixture() -> Index {
413        let targets = [
414            ("src/target/first.rs", "first", 0),
415            ("src/target/second.rs", "second", 0),
416            ("src/target/deep/third.rs", "third", 0),
417            ("src/testonly/test.rs", "test_only", SymbolRole::Test as i32),
418            ("outside/external.rs", "external", 0),
419        ];
420        let mut documents = Vec::new();
421        let mut references = Vec::new();
422        for (relative_path, name, symbol_roles) in targets {
423            let symbol = format!("rust-analyzer cargo fixture 0.0.0 {name}().");
424            references.push(Occurrence { symbol: symbol.clone(), symbol_roles, ..Occurrence::default() });
425            documents.push(Document {
426                relative_path: relative_path.into(),
427                occurrences: vec![Occurrence { symbol, symbol_roles: SymbolRole::Definition as i32, ..Occurrence::default() }],
428                ..Document::default()
429            });
430        }
431        documents.push(Document {
432            relative_path: "outside/entry.rs".into(),
433            occurrences: references.clone(),
434            ..Document::default()
435        });
436        documents.push(Document { relative_path: "src/app/entry.rs".into(), occurrences: references, ..Document::default() });
437        Index { documents, ..Index::default() }
438    }
439
440    #[rstest]
441    #[case::files_all(Mode::Files, ".", false, None, &[("outside/entry.rs", 5), ("src/app/entry.rs", 5)])]
442    #[case::folders_all(Mode::Folders, ".", false, None, &[("outside", 3), ("src/app", 4)])]
443    #[case::files_root(Mode::Files, "src", false, None, &[("src/app/entry.rs", 4)])]
444    #[case::folders_root(Mode::Folders, "src", false, None, &[("app", 3)])]
445    #[case::files_production(Mode::Files, "src", true, None, &[("src/app/entry.rs", 3)])]
446    #[case::folders_production(Mode::Folders, "src", true, None, &[("app", 2)])]
447    #[case::files_folded(Mode::Files, "src", true, Some(1), &[("src/app/entry.rs", 3)])]
448    #[case::folders_folded(Mode::Folders, "src", true, Some(1), &[])]
449    #[case::folders_folded_with_tests(Mode::Folders, "src", false, Some(1), &[("app", 2)])]
450    fn test_outgoing_dependency_graph_selection(
451        #[case] mode: Mode,
452        #[case] root: &str,
453        #[case] exclude_tests: bool,
454        #[case] depth: Option<usize>,
455        #[case] expected: &[(&str, usize)],
456    ) {
457        let fixture = replay_test_fixture(&outgoing_dependency_index_fixture());
458        let (_fixture, mut system_under_test) = assert_ok!(fixture, "Outgoing dependency replay fixture must be created");
459        system_under_test.root = PathBuf::from(root);
460        system_under_test.exclude_tests = exclude_tests;
461        system_under_test.depth = depth;
462        system_under_test.outgoing_dependencies = Some(outgoing_options_test_fixture(None, 1, Some(mode)));
463        let expected_failure = !expected.is_empty();
464        let expected_lines: Vec<_> = expected.iter().map(|&(label, count)| {
465            let label = match mode {
466                Mode::Files => PathBuf::from_iter(label.split('/')).to_string_lossy().into_owned(),
467                Mode::Folders => label.to_owned(),
468            };
469            format!("- {label:?}: {count} outgoing dependencies (maximum: 1)")
470        }).collect();
471        let mut diagram = Vec::new();
472
473        let result = run(&system_under_test, &mut diagram);
474        let failed = result.is_err();
475        let diagnostic = result.err().map_or_else(String::new, |error| error.to_string());
476        let actual_lines: Vec<_> = diagnostic.lines().filter(|line| line.starts_with("- ")).collect();
477
478        assert_eq!(failed, expected_failure, "Unexpected graph-selection result: {diagnostic}");
479        assert_eq!(actual_lines, expected_lines, "Violations must reflect the selected graph after filtering and folding");
480    }
481
482    #[rstest]
483    #[case::disabled(false, None, true, 0, false)]
484    #[case::default_folders(true, None, false, 0, false)]
485    #[case::default_folder_self(true, None, true, 0, true)]
486    #[case::files_without_self(true, Some(Mode::Files), false, 0, true)]
487    #[case::files_with_self(true, Some(Mode::Files), true, 0, true)]
488    #[case::folder_equality(true, Some(Mode::Folders), true, 1, false)]
489    #[case::file_equality(true, Some(Mode::Files), false, 1, false)]
490    fn test_outgoing_dependency_gate(
491        #[case] enabled: bool,
492        #[case] mode: Option<Mode>,
493        #[case] include_self: bool,
494        #[case] maximum: usize,
495        #[case] expected_failure: bool,
496    ) {
497        let fixture = replay_test_fixture(&two_file_index_fixture(false));
498        let (_fixture, mut system_under_test) = assert_ok!(fixture, "Outgoing gate replay fixture must be created");
499        system_under_test.include_self = include_self;
500        system_under_test.outgoing_dependencies = enabled.then(|| outgoing_options_test_fixture(None, maximum, mode));
501        let mut diagram = Vec::new();
502
503        let result = run(&system_under_test, &mut diagram);
504        let failed = result.is_err();
505
506        assert_eq!(failed, expected_failure, "Unexpected outgoing threshold result: {result:?}");
507        if let Err(error) = result {
508            let diagnostic = error.to_string();
509            assert!(diagnostic.contains("Outgoing dependency threshold exceeded"), "Unexpected gate failure: {diagnostic}");
510        }
511    }
512
513    #[rstest]
514    #[case::at_limit(1, false)]
515    #[case::above_limit(0, true)]
516    fn test_outgoing_dependency_outputs(#[case] maximum: usize, #[case] expected_failure: bool) {
517        const CONTENTS_EXISTING: &str = "preserved";
518        let fixture = replay_test_fixture(&two_file_index_fixture(false));
519        let (fixture, mut system_under_test) = assert_ok!(fixture, "Outgoing output replay fixture must be created");
520        let outputs: [&Path; 2] = [&fixture.diagram, &fixture.outgoing_report];
521        let initialized = write_outputs_test_fixture(&outputs, CONTENTS_EXISTING);
522        assert_ok!(initialized, "Existing outputs must be initialized before the outgoing gate");
523        system_under_test.output = Some(fixture.diagram.clone());
524        let outgoing = outgoing_options_test_fixture(Some(&fixture.outgoing_report), maximum, Some(Mode::Files));
525        system_under_test.outgoing_dependencies = Some(outgoing);
526        let mut diagram = Vec::new();
527
528        let result = run(&system_under_test, &mut diagram);
529        let exported = read_outputs_test_fixture(&outputs);
530        let exported = assert_ok!(exported, "Diagram and report must remain readable after the outgoing gate");
531        let replaced: Vec<_> = exported.iter().map(|contents| !contents.is_empty() && contents != CONTENTS_EXISTING).collect();
532        let failed = result.is_err();
533
534        assert_eq!(failed, expected_failure, "Unexpected outgoing threshold result: {result:?}");
535        assert_eq!(replaced, [true; 2], "Both outputs must be replaced before gating: {exported:?}");
536        assert_eq!(diagram, [] as [u8; 0], "An output-file request must not also write to the supplied writer");
537    }
538
539    #[rstest]
540    #[case::cyclic_neither(true, false, false, None)]
541    #[case::cyclic_report_only(true, true, false, None)]
542    #[case::cyclic_gate_only(true, false, true, Some(1))]
543    #[case::cyclic_report_and_gate(true, true, true, Some(1))]
544    #[case::acyclic_neither(false, false, false, None)]
545    #[case::acyclic_report_only(false, true, false, None)]
546    #[case::acyclic_gate_only(false, false, true, None)]
547    #[case::acyclic_report_and_gate(false, true, true, None)]
548    fn test_file_cycle_report_and_gate_flags(
549        #[case] cyclic: bool,
550        #[case] report_requested: bool,
551        #[case] fail_on_cycles: bool,
552        #[case] expected_file_cycle_groups: Option<usize>,
553    ) {
554        let fixture = replay_test_fixture(&two_file_index_fixture(cyclic));
555        let (fixture, mut system_under_test) = assert_ok!(fixture, "Cycle report replay fixture must be created");
556        system_under_test.cycles.fail_on_cycles = fail_on_cycles;
557        system_under_test.cycles.file_cycles_output = report_requested.then(|| fixture.file_report.clone());
558        /* Same-folder files and disabled self-edges keep the folder gate from masking skipped file analysis. */
559        system_under_test.include_self = false;
560        let expected_error = expected_file_cycle_groups.map(|groups| {
561            format!("Dependency cycles found: 0 folder cycle group(s), {groups} file cycle group(s)")
562        });
563        let mut diagram = Vec::new();
564
565        let result = run(&system_under_test, &mut diagram);
566
567        let actual_error = result.err().map(|error| error.to_string());
568        assert_eq!(actual_error, expected_error);
569        assert!(!diagram.is_empty(), "Cycle gating must happen after diagram output is written");
570        let report_exists = fixture.file_report.try_exists();
571        let report_exists = assert_ok!(report_exists, "File-cycle report path must be inspectable");
572        assert_eq!(report_exists, report_requested, "Only a requested file-cycle report should be written");
573        if report_requested {
574            let report = fs::read_to_string(&fixture.file_report);
575            let report = assert_ok!(report, "Requested file-cycle report must be readable");
576            let cycle_groups = report.lines().filter(|line| line.starts_with("## ")).count();
577            let expected_groups = usize::from(cyclic);
578            assert_eq!(cycle_groups, expected_groups, "Report requests must trigger file-cycle analysis independently of gating");
579        }
580    }
581
582    #[rstest]
583    #[case::cycles_only(true, 1, [true, false])]
584    #[case::outgoing_only(false, 0, [false, true])]
585    #[case::both(true, 0, [true, true])]
586    fn test_combined_dependency_gates(
587        #[case] fail_on_cycles: bool, #[case] maximum: usize, #[case] expected_reasons: [bool; 2],
588    ) {
589        let fixture = replay_test_fixture(&two_file_index_fixture(true));
590        let (fixture, mut system_under_test) = assert_ok!(fixture, "Combined gate replay fixture must be created");
591        system_under_test.cycles.fail_on_cycles = fail_on_cycles;
592        system_under_test.cycles.file_cycles_output = Some(fixture.file_report.clone());
593        let outgoing = outgoing_options_test_fixture(Some(&fixture.outgoing_report), maximum, Some(Mode::Files));
594        system_under_test.outgoing_dependencies = Some(outgoing);
595        let mut diagram = Vec::new();
596
597        let error = run(&system_under_test, &mut diagram).err();
598        let error = assert_some!(error, "At least one dependency gate must reject the cyclic fixture");
599        let diagnostic = error.to_string();
600        let reasons = ["Dependency cycles found:", "Outgoing dependency threshold exceeded"];
601        let actual_reasons = reasons.map(|reason| diagnostic.contains(reason));
602        let reports = read_outputs_test_fixture(&[&fixture.file_report, &fixture.outgoing_report]);
603        let reports = assert_ok!(reports, "Both reports must be written before either dependency gate fails");
604        let reports_written = reports.iter().all(|report| !report.is_empty());
605
606        assert_eq!(actual_reasons, expected_reasons, "Dependency gates must contribute independent reasons: {diagnostic}");
607        assert!(reports_written, "Gate failures must not suppress reports");
608        assert!(!diagram.is_empty(), "Gate failures must not suppress the diagram");
609    }
610
611    #[rstest]
612    #[case::matching("src/second.rs", false)]
613    #[case::project_relative("second.rs", true)]
614    fn test_exclusions_and_checks(
615        #[case] pattern: &str,
616        #[case] expected_failure: bool,
617        #[values(Mode::Files, Mode::Folders)] mode: Mode,
618    ) {
619        let fixture = replay_test_fixture(&two_file_index_fixture(true));
620        let (fixture, mut system_under_test) = assert_ok!(fixture, "Exclusion replay fixture must be created");
621        let exclusions = Exclusions::new(&[pattern.to_owned()]);
622        system_under_test.exclusions = assert_ok!(exclusions, "Replay exclusion patterns must compile");
623        system_under_test.include_self = true;
624        system_under_test.cycles = cycle_reports_test_fixture(&fixture.file_report, &fixture.folder_report);
625        system_under_test.cycles.highlight_cycles = true;
626        system_under_test.cycles.fail_on_cycles = true;
627        let outgoing = outgoing_options_test_fixture(Some(&fixture.outgoing_report), 0, Some(mode));
628        system_under_test.outgoing_dependencies = Some(outgoing);
629        let expected_groups = usize::from(expected_failure);
630        let expected_sources = if expected_failure { match mode { Mode::Files => 2, Mode::Folders => 1 } } else { 0 };
631        let mut diagram = Vec::new();
632
633        let result = run(&system_under_test, &mut diagram);
634        let reports = read_outputs_test_fixture(&[&fixture.file_report, &fixture.folder_report]);
635        let reports = assert_ok!(reports, "Cycle reports must be written for the filtered replay graph");
636        let groups: Vec<_> = reports.iter().map(|report| report.lines().filter(|line| line.starts_with("## ")).count()).collect();
637        let outgoing_contents = fs::read_to_string(&fixture.outgoing_report);
638        let outgoing_contents = assert_ok!(outgoing_contents, "Outgoing counts must be written for the filtered replay graph");
639        let violating_sources = outgoing_contents.lines().filter(|line| line.starts_with("- ")).count();
640        let failed = result.is_err();
641
642        assert_eq!(failed, expected_failure, "Exclusions did not affect dependency checks as expected: {result:?}");
643        assert_eq!(groups, [expected_groups; 2], "File and folder cycles must use the filtered graph");
644        assert_eq!(violating_sources, expected_sources, "Outgoing counts must use the filtered graph");
645    }
646
647    #[test]
648    fn test_exclusions_saved_replay() {
649        let fixture = replay_test_fixture(&two_file_index_fixture(true));
650        let (fixture, mut system_under_test) = assert_ok!(fixture, "Exclusion replay fixture must be created");
651        let exclusions = Exclusions::new(&["src/second.rs".to_owned()]);
652        system_under_test.exclusions = assert_ok!(exclusions, "Replay exclusion patterns must compile");
653        system_under_test.include_self = true;
654        let mut diagram = Vec::new();
655
656        let result = run(&system_under_test, &mut diagram);
657        assert_ok!(result, "Filtered replay must export its remaining graph");
658        system_under_test.exclusions = Exclusions::default();
659        let mut replayed_diagram = Vec::new();
660        let replay = run(&system_under_test, &mut replayed_diagram);
661        assert_ok!(replay, "The same saved index must support replay with different filters");
662        let preserved = fs::read(&fixture.index);
663        let preserved = assert_ok!(preserved, "The saved index must remain readable after changing replay filters");
664
665        assert_ne!(diagram, replayed_diagram, "Clearing exclusions must restore the original graph");
666        assert_eq!(preserved, fixture.index_bytes, "Exclusions must not rewrite the saved index");
667    }
668
669    #[test]
670    fn test_exclusions_all_files() {
671        const CONTENTS_EXISTING: &str = "preserved";
672        let fixture = replay_test_fixture(&two_file_index_fixture(false));
673        let (fixture, mut system_under_test) = assert_ok!(fixture, "Whole-root exclusion replay fixture must be created");
674        let outputs: [&Path; 3] = [&fixture.diagram, &fixture.file_report, &fixture.outgoing_report];
675        let initialized = write_outputs_test_fixture(&outputs, CONTENTS_EXISTING);
676        assert_ok!(initialized, "Existing outputs must be initialized before exclusions remove every file");
677        let exclusions = Exclusions::new(&["src/**".to_owned()]);
678        system_under_test.exclusions = assert_ok!(exclusions, "A whole-root exclusion must compile");
679        system_under_test.output = Some(fixture.diagram.clone());
680        system_under_test.cycles = cycle_reports_test_fixture(&fixture.file_report, &fixture.folder_report);
681        system_under_test.outgoing_dependencies = Some(outgoing_options_test_fixture(Some(&fixture.outgoing_report), 0, None));
682        let mut diagram = Vec::new();
683
684        let error = run(&system_under_test, &mut diagram).err();
685        let error = assert_some!(error, "Excluding every indexed file must fail before opening outputs");
686        let diagnostic = error.to_string();
687        let preserved = read_outputs_test_fixture(&outputs);
688        let preserved = assert_ok!(preserved, "Existing outputs must remain readable after all files are excluded");
689        let report_exists = fixture.folder_report.try_exists();
690        let report_exists = assert_ok!(report_exists, "The unwritten folder-report path must be inspectable");
691
692        assert!(diagnostic.starts_with(NO_FILES_AFTER_FILTERING), "The error must explain filtering: {diagnostic}");
693        assert_eq!(preserved, [CONTENTS_EXISTING; 3], "An empty filtered graph replaced an existing output");
694        assert!(!report_exists, "An empty filtered graph created a report");
695        assert!(diagram.is_empty(), "An empty filtered graph wrote diagram bytes");
696    }
697
698    #[rstest]
699    #[case::readable_input(false)]
700    #[case::missing_input(true)]
701    fn test_replay_cannot_save_analysis(#[case] missing_input: bool) {
702        let fixture = replay_test_fixture(&two_file_index_fixture(false));
703        let (fixture, _request) = assert_ok!(fixture, "Replay without saving must accept the valid input");
704        let output = fixture.directory.path().join("saved.scip");
705        let initialized = fs::write(&output, b"preserved");
706        assert_ok!(initialized, "Existing analysis output must be initialized separately from the replay input");
707        let input = if missing_input { fixture.directory.path().join("missing.scip") } else { fixture.index.clone() };
708        let system_under_test = Request::builder().input(Input::ScipFile(input)).save_scip(output.clone());
709
710        let request = system_under_test.build();
711        let preserved = fs::read(&output);
712        let input_bytes = fs::read(&fixture.index);
713
714        let error = assert_some!(request.err(), "Request construction must reject saving replayed analysis");
715        assert!(!error.is::<std::io::Error>(), "Conflicting options must be rejected before input I/O: {error:#}");
716        let preserved = assert_ok!(preserved, "Rejected replay must leave the existing analysis output readable");
717        let input_bytes = assert_ok!(input_bytes, "Rejected replay must leave the source index readable");
718        assert_eq!(preserved, b"preserved", "Rejected replay must preserve the existing output");
719        assert_eq!(input_bytes, fixture.index_bytes, "Rejected replay must preserve its source index");
720    }
721
722    #[rstest]
723    #[case::missing(false)]
724    #[case::directory(true)]
725    fn test_replay_input_io_at_construction(#[case] directory_input: bool) {
726        let fixture = tempdir();
727        let fixture = assert_ok!(fixture, "The request construction fixture must be created");
728        let path = if directory_input { fixture.path().to_path_buf() } else { fixture.path().join("missing.scip") };
729        let system_under_test = Request::builder().input(Input::ScipFile(path.clone()));
730
731        let error = system_under_test.build().err();
732        let error = assert_some!(error, "An unreadable saved index must fail before execution");
733        let diagnostic = format!("{error:#}");
734
735        assert!(error.is::<std::io::Error>(), "Input failure must preserve its I/O cause: {diagnostic}");
736        assert!(diagnostic.contains(&path.to_string_lossy().into_owned()), "Input failure must identify its path: {diagnostic}");
737    }
738
739    #[rstest]
740    #[case::overwrite_contents(false)]
741    #[case::replace_path(true)]
742    fn test_replay_snapshot_at_construction(#[case] replace_path: bool) {
743        let fixture = replay_test_fixture(&two_file_index_fixture(false));
744        let (fixture, system_under_test) = assert_ok!(fixture, "The snapshot request must load before modifying its input");
745        if replace_path {
746            let renamed = fs::rename(&fixture.index, fixture.directory.path().join("retained.scip"));
747            assert_ok!(renamed, "The loaded index must be renamed before replacing its path");
748        }
749        let changed = fs::write(&fixture.index, b"\xff");
750        assert_ok!(changed, "The index path must contain malformed data before the first run");
751        let mut diagram = Vec::new();
752        let mut repeated_diagram = Vec::new();
753
754        let result = run(&system_under_test, &mut diagram);
755        let repeated = run(&system_under_test, &mut repeated_diagram);
756        let reloaded = Request::builder().input(Input::ScipFile(fixture.index)).build();
757
758        assert_ok!(result, "Execution must use the snapshot captured by build, not the changed file");
759        assert_ok!(repeated, "The same request must support repeated execution without rereading the file");
760        assert!(!diagram.is_empty(), "The parsed snapshot must still produce a diagram");
761        assert_eq!(diagram, repeated_diagram, "Repeated execution must use the same saved analysis");
762        assert!(reloaded.is_err(), "A new request must load the changed file instead of reusing another request's snapshot");
763    }
764
765    #[test]
766    fn test_renamed_replay_input_protection() {
767        let fixture = replay_test_fixture(&two_file_index_fixture(false));
768        let (fixture, mut system_under_test) = assert_ok!(fixture, "The protected request must load before renaming its input");
769        let retained = fixture.directory.path().join("retained.scip");
770        let renamed = fs::rename(&fixture.index, &retained);
771        assert_ok!(renamed, "The loaded index must be renamed while its identity is retained");
772        let replaced = fs::write(&fixture.index, b"replacement");
773        assert_ok!(replaced, "The original input path must contain a different file before execution");
774        system_under_test.output = Some(retained.clone());
775        let mut diagram = Vec::new();
776
777        let result = run(&system_under_test, &mut diagram);
778        let preserved = fs::read(&retained);
779        let replacement = fs::read(&fixture.index);
780
781        assert!(result.as_ref().is_err_and(Error::is::<OutputPathConflict>), "The retained input must be protected: {result:?}");
782        let preserved = assert_ok!(preserved, "The renamed index must remain readable after rejecting output");
783        let replacement = assert_ok!(replacement, "The replacement file must remain readable after rejecting output");
784        assert_eq!(preserved, fixture.index_bytes, "Output protection must follow the original file's identity");
785        assert_eq!(replacement, b"replacement", "Output protection must not modify the replacement file");
786        assert!(diagram.is_empty(), "An input conflict must not write a diagram");
787    }
788
789    #[rstest]
790    #[case::same_path(false)]
791    #[case::hard_link(true)]
792    fn test_replay_cannot_overwrite_input(#[case] alias: bool, #[values(false, true)] outgoing_report: bool) {
793        let fixture = replay_test_fixture(&two_file_index_fixture(false));
794        let (fixture, request) = assert_ok!(fixture, "Protected input replay fixture must be created");
795        let output = output_alias_test_fixture(&fixture.index, alias);
796        let output = assert_ok!(output, "Output must identify the protected index");
797        let system_under_test = request_output_test_fixture(request, output, outgoing_report);
798        let mut diagram = Vec::new();
799
800        let result = run(&system_under_test, &mut diagram);
801        let preserved = fs::read(&fixture.index);
802        let preserved = assert_ok!(preserved, "Protected SCIP input must remain readable after replay rejection");
803        let conflict = result.as_ref().is_err_and(Error::is::<OutputPathConflict>);
804
805        assert!(conflict, "Replay must protect input aliases: {result:?}");
806        assert_eq!(preserved, fixture.index_bytes);
807        assert_eq!(diagram, [] as [u8; 0]);
808    }
809
810    #[rstest]
811    #[case::configuration_path(true, false, false)]
812    #[case::configuration_alias(true, true, false)]
813    #[case::configuration_renamed(true, false, true)]
814    #[case::index_path(false, false, false)]
815    #[case::index_alias(false, true, false)]
816    fn test_request_protected_inputs(
817        #[case] configuration_target: bool,
818        #[case] alias: bool,
819        #[case] renamed: bool,
820        #[values(false, true)] outgoing_report: bool,
821    ) {
822        const CONTENTS_CONFIGURATION: &[u8] = b"# protected configuration\n";
823        const CONTENTS_REPLACEMENT: &[u8] = b"# replacement configuration\n";
824        let fixture = replay_test_fixture(&two_file_index_fixture(false));
825        let (fixture, mut request) = assert_ok!(fixture, "Request input-protection replay fixture must be created");
826        let configuration = fixture.directory.path().join("source-mesh.toml");
827        let retained_configuration = fixture.directory.path().join("retained.toml");
828        let configuration_write = fs::write(&configuration, CONTENTS_CONFIGURATION);
829        assert_ok!(configuration_write, "Protected configuration must be written before loading");
830        let opened_configuration = InputFile::open(&configuration);
831        let mut opened_configuration = assert_ok!(opened_configuration, "Configuration must open before request construction");
832        let loaded = opened_configuration.read();
833        let loaded = assert_ok!(loaded, "Configuration contents must be read from its retained handle");
834        assert_eq!(CONTENTS_CONFIGURATION, loaded, "The retained handle must identify the loaded configuration");
835        let configuration_path = if renamed {
836            let moved = fs::rename(&configuration, &retained_configuration);
837            assert_ok!(moved, "Loaded configuration must be renamed while its identity is retained");
838            let replacement_write = fs::write(&configuration, CONTENTS_REPLACEMENT);
839            assert_ok!(replacement_write, "The original configuration path must be replaced before output validation");
840            &retained_configuration
841        } else {
842            &configuration
843        };
844        let protected_path = if configuration_target { configuration_path } else { &fixture.index };
845        let output = output_alias_test_fixture(protected_path, alias);
846        let output = assert_ok!(output, "Output must identify the protected input");
847        request.protected_inputs = vec![opened_configuration];
848        let system_under_test = request_output_test_fixture(request, output, outgoing_report);
849        let mut diagram = Vec::new();
850
851        let result = run(&system_under_test, &mut diagram);
852        let preserved_index = fs::read(&fixture.index);
853        let preserved_index = assert_ok!(preserved_index, "Replay index must remain readable after a protected-input conflict");
854        let preserved_configuration = fs::read(configuration_path);
855        let preserved_configuration = assert_ok!(preserved_configuration, "The loaded configuration must remain readable");
856
857        let conflict = result.as_ref().is_err_and(Error::is::<OutputPathConflict>);
858        assert!(conflict, "Output validation must protect both request-owned and locally opened inputs: {result:?}");
859        assert_eq!(fixture.index_bytes, preserved_index, "Output validation changed the replay index");
860        assert_eq!(CONTENTS_CONFIGURATION, preserved_configuration, "Output validation changed the loaded configuration");
861        if renamed {
862            let replacement = fs::read(configuration);
863            let replacement = assert_ok!(replacement, "The replacement configuration must remain readable");
864            assert_eq!(CONTENTS_REPLACEMENT, replacement, "Output validation changed the replacement configuration");
865        }
866        assert!(diagram.is_empty(), "An input conflict must be detected before writing diagram bytes");
867    }
868
869    #[rstest]
870    #[case::empty(b"")]
871    #[case::malformed(b"\xff")]
872    #[case::metadata_without_documents(b"\x0a\x00")]
873    fn test_invalid_index_preserves_outputs(#[case] bytes: &[u8], #[values(false, true)] existing_report: bool) {
874        const CONTENTS_EXISTING: &str = "preserved";
875        let fixture = replay_bytes_test_fixture(bytes.to_vec());
876        let fixture = assert_ok!(fixture, "Invalid-index replay fixture must be created");
877        let mut existing_outputs = vec![fixture.diagram.as_path()];
878        if existing_report { existing_outputs.push(&fixture.outgoing_report); }
879        let initialized = write_outputs_test_fixture(&existing_outputs, CONTENTS_EXISTING);
880        assert_ok!(initialized, "Existing outputs must be initialized before invalid-index replay");
881        let system_under_test = Request::builder().input(Input::ScipFile(fixture.index.clone()))
882            .output(fixture.diagram.clone()).cycles(cycle_reports_test_fixture(&fixture.file_report, &fixture.folder_report))
883            .outgoing_dependencies(outgoing_options_test_fixture(Some(&fixture.outgoing_report), 0, None));
884
885        let result = system_under_test.build();
886        let preserved = read_outputs_test_fixture(&existing_outputs);
887        let preserved = assert_ok!(preserved, "Existing outputs must remain readable after invalid-index rejection");
888        let expected = vec![CONTENTS_EXISTING; existing_outputs.len()];
889        let reports = [&fixture.folder_report, &fixture.file_report, &fixture.outgoing_report];
890        let reports_exist = reports.map(|path| {
891            let exists = path.try_exists();
892            assert_ok!(exists, "Report path must be inspectable: {}", path.display())
893        });
894
895        assert!(result.is_err(), "Malformed external analysis must fail during request construction");
896        assert_eq!(preserved, expected, "Invalid input must not replace an existing output");
897        assert_eq!(reports_exist, [false, false, existing_report], "Invalid input must not create any report");
898    }
899
900    #[rstest]
901    #[case::empty("")]
902    #[case::parent("../outside.rs")]
903    #[case::absolute("/absolute.rs")]
904    fn test_invalid_source_path_preserves_outputs(#[case] path: &str) {
905        let index = Index { documents: vec![Document { relative_path: path.into(), ..Document::default() }], ..Index::default() };
906        let bytes = index.write_to_bytes();
907        let bytes = assert_ok!(bytes, "The invalid-source-path index must serialize");
908        let fixture = replay_bytes_test_fixture(bytes);
909        let fixture = assert_ok!(fixture, "Invalid-source-path replay fixture must be created");
910        let system_under_test = Request::builder().input(Input::ScipFile(fixture.index.clone())).output(fixture.diagram.clone());
911
912        let result = system_under_test.build();
913
914        assert!(result.is_err(), "Malformed external source paths must fail during request construction");
915        let output_exists = fixture.diagram.try_exists();
916        let output_exists = assert_ok!(output_exists, "Diagram output path must be inspectable");
917        assert!(!output_exists, "Invalid input created a diagram");
918    }
919
920    #[rstest]
921    #[case::same_path(false)]
922    #[case::hard_link(true)]
923    fn test_conflicting_outputs_preserve_files(#[case] alias: bool, #[values(false, true)] outgoing_report: bool) {
924        const CONTENTS_EXISTING: &str = "preserved";
925        let fixture = replay_test_fixture(&two_file_index_fixture(false));
926        let (fixture, mut system_under_test) = assert_ok!(fixture, "Conflicting-output replay fixture must be created");
927        let outputs: [&Path; 2] = [&fixture.diagram, &fixture.file_report];
928        let initialized = write_outputs_test_fixture(&outputs, CONTENTS_EXISTING);
929        assert_ok!(initialized, "Existing outputs must be initialized before conflict validation");
930        let conflicting_report = output_alias_test_fixture(&fixture.diagram, alias);
931        let conflicting_report = assert_ok!(conflicting_report, "Conflicting report must identify the existing diagram");
932        system_under_test.output = Some(fixture.diagram.clone());
933        system_under_test.cycles.file_cycles_output = Some(fixture.file_report.clone());
934        if outgoing_report {
935            let outgoing = outgoing_options_test_fixture(Some(&conflicting_report), usize::MAX, None);
936            system_under_test.outgoing_dependencies = Some(outgoing);
937        } else {
938            system_under_test.cycles.cycles_output = Some(conflicting_report);
939        }
940        let mut diagram = Vec::new();
941
942        let result = run(&system_under_test, &mut diagram);
943        let preserved = read_outputs_test_fixture(&outputs);
944        let preserved = assert_ok!(preserved, "Existing outputs must remain readable after conflicts");
945        let conflict = result.as_ref().is_err_and(Error::is::<OutputPathConflict>);
946
947        assert!(conflict, "Replay must reject output aliases: {result:?}");
948        assert_eq!(preserved, [CONTENTS_EXISTING; 2]);
949        assert_eq!(diagram, [] as [u8; 0]);
950    }
951}