Skip to main content

source_mesh_core/
output_paths.rs

1use std::error::Error;
2use std::fmt;
3use std::fs::File;
4use std::fs::OpenOptions;
5use std::io::Read as _;
6use std::io::Seek as _;
7use std::io::Write as _;
8use std::path::Path;
9use std::path::PathBuf;
10use std::path::absolute;
11
12use anyhow::Context as _;
13use anyhow::Result;
14use anyhow::ensure;
15use derive_new::new;
16use getset::CopyGetters;
17use same_file::Handle;
18
19const OUTPUT_PATH_CONFLICT: &str = "Output files must use distinct paths and must not overwrite input files";
20
21#[derive(Debug, new)]
22pub(crate) struct OutputPathConflict {
23    path: PathBuf,
24    other_path: PathBuf,
25}
26
27impl fmt::Display for OutputPathConflict {
28    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
29        write!(formatter, "{OUTPUT_PATH_CONFLICT}: {} and {}", self.path.display(), self.other_path.display())
30    }
31}
32
33impl Error for OutputPathConflict {}
34
35#[derive(Debug)]
36enum OutputIoError {
37    Resolve(PathBuf),
38    Open(PathBuf),
39    Identify(PathBuf),
40    Truncate(PathBuf),
41    Seek(PathBuf),
42    Write(PathBuf),
43}
44
45impl fmt::Display for OutputIoError {
46    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
47        match *self {
48            Self::Resolve(ref path) => write!(formatter, "Cannot resolve output path {}", path.display()),
49            Self::Open(ref path) => write!(formatter, "Cannot open output file {}", path.display()),
50            Self::Identify(ref path) => write!(formatter, "Cannot identify output file {}", path.display()),
51            Self::Truncate(ref path) => write!(formatter, "Cannot truncate output file {}", path.display()),
52            Self::Seek(ref path) => write!(formatter, "Cannot seek output file {}", path.display()),
53            Self::Write(ref path) => write!(formatter, "Cannot write output file {}", path.display()),
54        }
55    }
56}
57
58impl Error for OutputIoError {}
59
60
61pub struct InputFile {
62    path: PathBuf,
63    handle: Handle,
64}
65
66impl InputFile {
67    pub fn open(path: &Path) -> Result<Self> {
68        let path = absolute(path).with_context(|| format!("Cannot resolve input path {}", path.display()))?;
69        let file = File::open(&path).with_context(|| format!("Cannot open input file {}", path.display()))?;
70        let handle = Handle::from_file(file).with_context(|| format!("Cannot identify input file {}", path.display()))?;
71        Ok(Self { path, handle })
72    }
73
74
75    pub fn read(&mut self) -> Result<Vec<u8>> {
76        let mut contents = Vec::new();
77        let read_result = self.handle.as_file_mut().read_to_end(&mut contents);
78        read_result.with_context(|| format!("Cannot read input file {}", self.path.display()))?;
79        Ok(contents)
80    }
81}
82
83#[derive(Clone, Copy, CopyGetters, new)]
84pub(crate) struct FileOutput<'a> {
85    #[getset(get_copy = "pub(crate)")]
86    path: &'a Path,
87    contents: &'a [u8],
88}
89
90struct OpenedOutput<'a> {
91    output: FileOutput<'a>,
92    handle: Handle,
93}
94
95impl OpenedOutput<'_> {
96    fn write(&mut self, contents: &[u8]) -> Result<()> {
97        let path = self.output.path;
98        let output = self.handle.as_file_mut();
99        output.set_len(0).with_context(|| OutputIoError::Truncate(path.to_path_buf()))?;
100        output.rewind().with_context(|| OutputIoError::Seek(path.to_path_buf()))?;
101        output.write_all(contents).with_context(|| OutputIoError::Write(path.to_path_buf()))
102    }
103}
104
105pub(crate) struct OutputFiles<'a> {
106    files: Vec<OpenedOutput<'a>>,
107}
108
109impl<'a> OutputFiles<'a> {
110    /**
111    Newly created empty files may remain on failure: removing their paths could delete replacement
112    files, so no path-based rollback is attempted.
113    */
114    pub(crate) fn open(outputs: &[FileOutput<'a>], inputs: &[&InputFile]) -> Result<Self> {
115        let paths = outputs.iter().map(|output| {
116            absolute(output.path).with_context(|| OutputIoError::Resolve(output.path.to_path_buf()))
117        }).collect::<Result<Vec<_>>>()?;
118        for (index, path) in paths.iter().enumerate() {
119            for other in paths.iter().take(index).chain(inputs.iter().map(|input| &input.path)) {
120                ensure!(path != other, OutputPathConflict::new(path.clone(), other.clone()));
121            }
122        }
123
124        let mut files: Vec<OpenedOutput<'a>> = Vec::with_capacity(outputs.len());
125        for (output, path) in outputs.iter().zip(paths) {
126            let file = OpenOptions::new().write(true).create(true).truncate(false).open(&path);
127            let file = file.with_context(|| OutputIoError::Open(output.path.to_path_buf()))?;
128            let handle = Handle::from_file(file);
129            let handle = handle.with_context(|| OutputIoError::Identify(output.path.to_path_buf()))?;
130            let output_identities = files.iter().map(|opened| (&opened.handle, opened.output.path));
131            let input_identities = inputs.iter().map(|input| (&input.handle, input.path.as_path()));
132            for (other_handle, other_path) in output_identities.chain(input_identities) {
133                let distinct = &handle != other_handle;
134                ensure!(distinct, OutputPathConflict::new(output.path.to_path_buf(), other_path.to_path_buf()));
135            }
136            files.push(OpenedOutput { output: *output, handle });
137        }
138        Ok(Self { files })
139    }
140
141    pub(crate) fn write_output(&mut self, output: &FileOutput<'_>) -> Result<()> {
142        let file = self.files.iter_mut().find(|file| file.output.path == output.path);
143        let file = file.with_context(|| format!("Output file was not opened and validated: {}", output.path.display()))?;
144        file.write(output.contents)
145    }
146
147    pub(crate) fn write(self) -> Result<()> {
148        for mut file in self.files {
149            file.write(file.output.contents)?;
150        }
151        Ok(())
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    use std::fs;
158    use std::fs::File;
159    use std::io::Error;
160    use std::io::ErrorKind;
161    use std::io::Seek as _;
162    use std::io::SeekFrom;
163    use std::path::Path;
164    use std::path::PathBuf;
165
166    use assertables::assert_contains;
167    use claims::assert_ok;
168    use claims::assert_some;
169    use pretty_assertions::assert_eq;
170    use rstest::rstest;
171    use same_file::Handle;
172    use tempfile::TempDir;
173    use tempfile::tempdir;
174
175    use super::FileOutput;
176    use super::InputFile;
177    use super::OUTPUT_PATH_CONFLICT;
178    use super::OpenedOutput;
179    use super::OutputFiles;
180    use super::OutputIoError;
181    use super::OutputPathConflict;
182
183    fn output_paths_test_fixture() -> TempDir {
184        let directory = tempdir();
185        assert_ok!(directory, "Failed to create the output-path fixture directory")
186    }
187
188    fn write_file_test_fixture(path: &Path, contents: &[u8]) {
189        let written = fs::write(path, contents);
190        assert_ok!(written, "Failed to write fixture file {}", path.display());
191    }
192
193    fn read_file_test_fixture(path: &Path) -> Vec<u8> {
194        let contents = fs::read(path);
195        assert_ok!(contents, "Failed to read fixture file {}", path.display())
196    }
197
198    #[test]
199    fn test_output_path_conflict_diagnostic() {
200        let system_under_test = OutputPathConflict::new(PathBuf::from("report.md"), PathBuf::from("index.scip"));
201
202        let diagnostic = system_under_test.to_string();
203
204        assert_eq!(diagnostic, format!("{OUTPUT_PATH_CONFLICT}: report.md and index.scip"));
205    }
206
207    #[rstest]
208    #[case::resolve(OutputIoError::Resolve)]
209    #[case::open(OutputIoError::Open)]
210    #[case::identify(OutputIoError::Identify)]
211    #[case::truncate(OutputIoError::Truncate)]
212    #[case::seek(OutputIoError::Seek)]
213    #[case::write(OutputIoError::Write)]
214    fn test_output_io_error_path_diagnostic(#[case] failure: fn(PathBuf) -> OutputIoError) {
215        const NAME_OUTPUT: &str = "report with spaces.md";
216        let system_under_test = failure(PathBuf::from(NAME_OUTPUT));
217
218        let diagnostic = system_under_test.to_string();
219
220        assert!(diagnostic.ends_with(NAME_OUTPUT), "Output I/O diagnostics must identify the requested file: {diagnostic}");
221    }
222
223    #[test]
224    fn test_input_read() {
225        const CONTENTS: &[u8] = b"input\0bytes";
226        let fixture = output_paths_test_fixture();
227        let path = fixture.path().join("index.scip");
228        write_file_test_fixture(&path, CONTENTS);
229        let system_under_test = InputFile::open(&path);
230        let mut system_under_test = assert_ok!(system_under_test, "The input fixture must open for reading");
231
232        let contents = system_under_test.read();
233        let contents = assert_ok!(contents, "The retained input handle must read the fixture bytes");
234
235        assert_eq!(contents, CONTENTS, "Input reading must preserve every byte");
236    }
237
238    #[test]
239    fn test_retained_input_identity() {
240        const CONTENTS_ORIGINAL: &[u8] = b"original input";
241        const CONTENTS_REPLACEMENT: &[u8] = b"replacement input";
242        let fixture = output_paths_test_fixture();
243        let path = fixture.path().join("index.scip");
244        let renamed = fixture.path().join("renamed.scip");
245        write_file_test_fixture(&path, CONTENTS_ORIGINAL);
246        let system_under_test = InputFile::open(&path);
247        let mut system_under_test = assert_ok!(system_under_test, "The original input must open before renaming");
248        let moved = fs::rename(&path, &renamed);
249        assert_ok!(moved, "The opened input must be renamed while its handle is retained");
250        write_file_test_fixture(&path, CONTENTS_REPLACEMENT);
251
252        let contents = system_under_test.read();
253        let contents = assert_ok!(contents, "The retained input handle must remain readable after path replacement");
254        let output = OutputFiles::open(&[FileOutput::new(&renamed, b"overwrite")], &[&system_under_test]);
255        let original = read_file_test_fixture(&renamed);
256        let replacement = read_file_test_fixture(&path);
257
258        assert_eq!(contents, CONTENTS_ORIGINAL, "Reading reopened the input path");
259        let conflict = output.is_err_and(|error| error.is::<OutputPathConflict>());
260        assert!(conflict, "The retained input object was not protected after renaming");
261        assert_eq!(original, CONTENTS_ORIGINAL, "Conflict detection must preserve the renamed input");
262        assert_eq!(replacement, CONTENTS_REPLACEMENT, "Conflict detection must preserve the replacement input");
263    }
264
265    #[rstest]
266    #[case::missing(PathBuf::from("missing.scip"))]
267    #[case::directory(PathBuf::new())]
268    #[case::missing_parent(Path::new("missing").join("index.scip"))]
269    #[case::invalid(PathBuf::from("\0"))]
270    fn test_input_io_errors(#[case] name: PathBuf) {
271        let fixture = output_paths_test_fixture();
272        let path = fixture.path().join(name);
273
274        let system_under_test = InputFile::open(&path).and_then(|mut input| input.read());
275
276        let has_path_and_io_error = system_under_test.is_err_and(|error| {
277            error.downcast_ref::<Error>().is_some() && error.to_string().contains(&path.display().to_string())
278        });
279        assert!(has_path_and_io_error, "Input failures must retain the path and underlying I/O error");
280    }
281
282    #[test]
283    fn test_input_read_error() {
284        let fixture = output_paths_test_fixture();
285        let path = fixture.path().join("write-only.scip");
286        let file = File::create(&path);
287        let file = assert_ok!(file, "The write-only input fixture must be created");
288        let handle = Handle::from_file(file);
289        let handle = assert_ok!(handle, "The write-only input must have a retained identity handle");
290        let mut system_under_test = InputFile { handle, path: path.clone() };
291
292        let result = system_under_test.read();
293
294        let has_path_and_io_error = result.is_err_and(|error| {
295            error.downcast_ref::<Error>().is_some() && error.to_string().contains(&path.display().to_string())
296        });
297        assert!(has_path_and_io_error, "A failed handle read must retain its path and I/O error");
298    }
299
300    #[rstest]
301    #[case::lexical(false)]
302    #[case::hard_link(true)]
303    fn test_output_aliases(#[case] hard_link: bool) {
304        const CONTENTS_EXISTING: &[u8] = b"original";
305        let fixture = output_paths_test_fixture();
306        let earlier = fixture.path().join("diagram.md");
307        let first = fixture.path().join("cycles.md");
308        let second = if hard_link { fixture.path().join("alias.md") } else { fixture.path().join(".").join("cycles.md") };
309        write_file_test_fixture(&earlier, CONTENTS_EXISTING);
310        write_file_test_fixture(&first, CONTENTS_EXISTING);
311        if hard_link {
312            let linked = fs::hard_link(&first, &second);
313            assert_ok!(linked, "The second output path must be a hard link to the first");
314        }
315
316        let outputs = [
317            FileOutput::new(&earlier, b"new diagram"),
318            FileOutput::new(&first, b"new cycles"),
319            FileOutput::new(&second, b"new alias"),
320        ];
321        let system_under_test = OutputFiles::open(&outputs, &[]).and_then(OutputFiles::write);
322        let earlier_contents = read_file_test_fixture(&earlier);
323        let first_contents = read_file_test_fixture(&first);
324        let second_contents = read_file_test_fixture(&second);
325
326        let conflict = system_under_test.is_err_and(|error| error.is::<OutputPathConflict>());
327        assert!(conflict, "Aliased outputs were accepted");
328        assert_eq!(earlier_contents, CONTENTS_EXISTING, "An earlier output was written before validation completed");
329        assert_eq!(first_contents, CONTENTS_EXISTING, "Alias rejection must preserve the first output");
330        assert_eq!(second_contents, CONTENTS_EXISTING, "Alias rejection must preserve the second output");
331    }
332
333    #[rstest]
334    #[case::lexical(false)]
335    #[case::hard_link(true)]
336    fn test_input_overwrite(#[case] hard_link: bool) {
337        const CONTENTS_INPUT: &[u8] = b"protected input";
338        const CONTENTS_OUTPUT_EXISTING: &[u8] = b"existing diagram";
339        let fixture = output_paths_test_fixture();
340        let input = fixture.path().join("index.scip");
341        let earlier = fixture.path().join("diagram.md");
342        let output = if hard_link { fixture.path().join("report.md") } else { fixture.path().join(".").join("index.scip") };
343        write_file_test_fixture(&input, CONTENTS_INPUT);
344        write_file_test_fixture(&earlier, CONTENTS_OUTPUT_EXISTING);
345        if hard_link {
346            let linked = fs::hard_link(&input, &output);
347            assert_ok!(linked, "The output path must be a hard link to the protected input");
348        }
349        let opened_input = InputFile::open(&input);
350        let opened_input = assert_ok!(opened_input, "The protected input must open before validating outputs");
351        let inputs = [&opened_input];
352
353        let outputs = [FileOutput::new(&earlier, b"new diagram"), FileOutput::new(&output, b"overwrite")];
354        let system_under_test = OutputFiles::open(&outputs, &inputs).and_then(OutputFiles::write);
355        let input_contents = read_file_test_fixture(&input);
356        let earlier_contents = read_file_test_fixture(&earlier);
357
358        let conflict = system_under_test.is_err_and(|error| error.is::<OutputPathConflict>());
359        assert!(conflict, "An output could overwrite a protected input");
360        assert_eq!(input_contents, CONTENTS_INPUT, "Conflict rejection must preserve the protected input");
361        assert_eq!(earlier_contents, CONTENTS_OUTPUT_EXISTING, "Conflict rejection must preserve the earlier output");
362    }
363
364    #[test]
365    fn test_duplicate_names_before_creation() {
366        let fixture = output_paths_test_fixture();
367        let earlier = fixture.path().join("diagram.md");
368        let first = fixture.path().join("report.md");
369        let second = fixture.path().join(".").join("report.md");
370
371        let outputs = [
372            FileOutput::new(&earlier, b"diagram"),
373            FileOutput::new(&first, b"first"),
374            FileOutput::new(&second, b"second"),
375        ];
376        let system_under_test = OutputFiles::open(&outputs, &[]);
377        let earlier_contents = fs::read(&earlier);
378        let report_contents = fs::read(&first);
379
380        let conflict = system_under_test.is_err_and(|error| error.is::<OutputPathConflict>());
381        assert!(conflict, "Duplicate lexical output names were accepted");
382        let earlier_missing = earlier_contents.is_err_and(|error| error.kind() == ErrorKind::NotFound);
383        assert!(earlier_missing, "Lexical conflict detection created an earlier output");
384        let report_missing = report_contents.is_err_and(|error| error.kind() == ErrorKind::NotFound);
385        assert!(report_missing, "Lexical conflict detection created a conflicting output");
386    }
387
388    #[test]
389    fn test_protected_input_name_before_creation() {
390        const CONTENTS: &[u8] = b"protected input";
391        let fixture = output_paths_test_fixture();
392        let input = fixture.path().join("index.scip");
393        let renamed = fixture.path().join("renamed.scip");
394        let earlier = fixture.path().join("diagram.md");
395        write_file_test_fixture(&input, CONTENTS);
396        let opened_input = InputFile::open(&input);
397        let opened_input = assert_ok!(opened_input, "The protected input must open before its path is renamed");
398        let inputs = [&opened_input];
399        let moved = fs::rename(&input, &renamed);
400        assert_ok!(moved, "The input must be renamed while its retained handle protects its original name");
401
402        let outputs = [FileOutput::new(&earlier, b"diagram"), FileOutput::new(&input, b"overwrite")];
403        let system_under_test = OutputFiles::open(&outputs, &inputs);
404        let earlier_contents = fs::read(&earlier);
405        let input_contents = fs::read(&input);
406        let renamed_contents = read_file_test_fixture(&renamed);
407
408        let conflict = system_under_test.is_err_and(|error| error.is::<OutputPathConflict>());
409        assert!(conflict, "The lexical input name was not protected after renaming");
410        let earlier_missing = earlier_contents.is_err_and(|error| error.kind() == ErrorKind::NotFound);
411        assert!(earlier_missing, "Protecting the input name must not create an earlier output");
412        let input_missing = input_contents.is_err_and(|error| error.kind() == ErrorKind::NotFound);
413        assert!(input_missing, "Protecting the input name must not recreate the original path");
414        assert_eq!(renamed_contents, CONTENTS, "Protecting the input name must preserve the renamed input");
415    }
416
417    #[rstest]
418    #[case::case_variant("report.md", "REPORT.md")]
419    #[case::distinct("folders.md", "files.md")]
420    fn test_new_output_identity(#[case] first_name: &str, #[case] second_name: &str) {
421        let fixture = output_paths_test_fixture();
422        let first = fixture.path().join(first_name);
423        let second = fixture.path().join(second_name);
424
425        let outputs = [FileOutput::new(&first, b"first"), FileOutput::new(&second, b"second")];
426        let system_under_test = OutputFiles::open(&outputs, &[]);
427        let first_file = File::open(&first);
428        let first_file = assert_ok!(first_file, "The first output must be created during opening");
429        let first_handle = Handle::from_file(first_file);
430        let first_handle = assert_ok!(first_handle, "The first output must have a readable identity handle");
431        let second_file = File::open(&second);
432        let second_file = assert_ok!(second_file, "The second output path must be readable after opening");
433        let second_handle = Handle::from_file(second_file);
434        let second_handle = assert_ok!(second_handle, "The second output must have a readable identity handle");
435        let first_contents = read_file_test_fixture(&first);
436        let second_contents = read_file_test_fixture(&second);
437
438        let aliases = first_handle == second_handle;
439        if aliases {
440            let conflict = system_under_test.is_err_and(|error| error.is::<OutputPathConflict>());
441            assert!(conflict, "Aliased file identities must fail with an output path conflict");
442        } else {
443            assert_ok!(system_under_test, "Distinct file identities must open successfully");
444        }
445        assert!(first_contents.is_empty(), "Opening must not write the first new output");
446        assert!(second_contents.is_empty(), "Opening must not write the second new output");
447    }
448
449    #[rstest]
450    #[case::directory(PathBuf::new())]
451    #[case::missing_parent(Path::new("missing").join("report.md"))]
452    #[case::file_parent(Path::new("existing.md").join("report.md"))]
453    fn test_output_open_failure(#[case] name: PathBuf) {
454        const CONTENTS: &[u8] = b"existing output";
455        let fixture = output_paths_test_fixture();
456        let existing = fixture.path().join("existing.md");
457        let created = fixture.path().join("created.md");
458        let invalid = fixture.path().join(name);
459        write_file_test_fixture(&existing, CONTENTS);
460
461        let outputs = [
462            FileOutput::new(&existing, b"overwrite"),
463            FileOutput::new(&created, b"new output"),
464            FileOutput::new(&invalid, b"invalid output"),
465        ];
466        let system_under_test = OutputFiles::open(&outputs, &[]);
467        let existing_contents = read_file_test_fixture(&existing);
468        let created_contents = read_file_test_fixture(&created);
469
470        let error = assert_some!(system_under_test.err(), "Opening the invalid output must fail");
471        let output_error = error.downcast_ref::<OutputIoError>();
472        let output_error = assert_some!(output_error, "Output opening must retain its operation and path: {error:#}");
473        let opens_invalid_path = matches!(*output_error, OutputIoError::Open(ref path) if path == &invalid);
474        assert!(opens_invalid_path, "Opening must fail at the invalid output path: {error:#}");
475        assert!(error.downcast_ref::<Error>().is_some(), "Opening failures must retain the original I/O error: {error:#}");
476        assert_eq!(existing_contents, CONTENTS, "An opening failure truncated an existing output");
477        assert!(created_contents.is_empty(), "Opening must not write newly created outputs");
478    }
479
480    #[rstest]
481    #[case::empty(Path::new(""))]
482    #[case::invalid(Path::new("\0"))]
483    fn test_invalid_output_path(#[case] path: &Path) {
484        let system_under_test = OutputFiles::open(&[FileOutput::new(path, b"output")], &[]);
485
486        let has_io_error = system_under_test.is_err_and(|error| error.downcast_ref::<Error>().is_some());
487        assert!(has_io_error, "An invalid path must fail with an ordinary I/O error");
488    }
489
490    #[rstest]
491    #[case::replacement(b"new")]
492    #[case::empty(b"")]
493    fn test_output_writes(#[case] contents: &[u8], #[values(false, true)] existing: bool, #[values(false, true)] selected: bool) {
494        const CONTENTS_ORIGINAL: &[u8] = b"old contents longer than the replacement";
495        const CONTENTS_SECOND: &[u8] = b"second output";
496        let fixture = output_paths_test_fixture();
497        let first = fixture.path().join("first.md");
498        let second = fixture.path().join("second.md");
499        if existing {
500            write_file_test_fixture(&first, CONTENTS_ORIGINAL);
501            write_file_test_fixture(&second, CONTENTS_ORIGINAL);
502        }
503
504        let initial_contents = if selected { b"reserved" } else { contents };
505        let outputs = [FileOutput::new(&first, initial_contents), FileOutput::new(&second, CONTENTS_SECOND)];
506        let system_under_test = OutputFiles::open(&outputs, &[]);
507        let mut system_under_test = assert_ok!(system_under_test, "Opening distinct output paths failed");
508        let first_before = read_file_test_fixture(&first);
509        let second_before = read_file_test_fixture(&second);
510        for file in &mut system_under_test.files {
511            let position = file.handle.as_file_mut().seek(SeekFrom::End(0));
512            assert_ok!(position, "Failed to move an output handle to EOF for the write test");
513        }
514        if selected {
515            let first_write = system_under_test.write_output(&FileOutput::new(&first, contents));
516            assert_ok!(first_write, "Writing the selected output failed");
517            let second_reserved = read_file_test_fixture(&second);
518            assert_eq!(second_reserved, second_before, "Writing the first output changed the second reserved output");
519            let second_write = system_under_test.write_output(&FileOutput::new(&second, CONTENTS_SECOND));
520            assert_ok!(second_write, "Writing the second reserved output failed");
521        } else {
522            let plan_write = system_under_test.write();
523            assert_ok!(plan_write, "Writing the opened output plan failed");
524        }
525        let first_after = read_file_test_fixture(&first);
526        let second_after = read_file_test_fixture(&second);
527
528        let before = if existing { CONTENTS_ORIGINAL } else { b"" };
529        assert_eq!(first_before, before, "Opening changed the first output's contents");
530        assert_eq!(second_before, before, "Opening changed the second output's contents");
531        assert_eq!(first_after, contents, "The first output contains incorrect bytes after writing");
532        assert_eq!(second_after, CONTENTS_SECOND, "The second output differs from its planned contents");
533    }
534
535    #[rstest]
536    fn test_output_path_replacement(#[values(false, true)] existing: bool, #[values(false, true)] selected: bool) {
537        const CONTENTS_INPUT: &[u8] = b"protected input";
538        const CONTENTS_OUTPUT: &[u8] = b"new report";
539        let fixture = output_paths_test_fixture();
540        let input = fixture.path().join("index.scip");
541        let output = fixture.path().join("report.md");
542        let renamed = fixture.path().join("renamed.md");
543        write_file_test_fixture(&input, CONTENTS_INPUT);
544        if existing {
545            write_file_test_fixture(&output, b"original report contents");
546        }
547        let opened_input = InputFile::open(&input);
548        let opened_input = assert_ok!(opened_input, "Failed to open the protected input fixture");
549        let inputs = [&opened_input];
550        let system_under_test = OutputFiles::open(&[FileOutput::new(&output, CONTENTS_OUTPUT)], &inputs);
551        let mut system_under_test = assert_ok!(system_under_test, "Failed to open the output before replacing its path");
552
553        let moved = fs::rename(&output, &renamed);
554        assert_ok!(moved, "Failed to rename the output while its handle was open");
555        let linked = fs::hard_link(&input, &output);
556        assert_ok!(linked, "Failed to replace the output path with a hard link to the input");
557        let output_write = if selected {
558            system_under_test.write_output(&FileOutput::new(&output, CONTENTS_OUTPUT))
559        } else {
560            system_under_test.write()
561        };
562        assert_ok!(output_write, "Writing the retained output failed after replacing its path");
563        let input_contents = read_file_test_fixture(&input);
564        let output_contents = read_file_test_fixture(&output);
565        let renamed_contents = read_file_test_fixture(&renamed);
566
567        assert_eq!(input_contents, CONTENTS_INPUT, "Writing modified the protected input's contents");
568        assert_eq!(output_contents, CONTENTS_INPUT, "Replacement hard link contents changed after writing");
569        assert_eq!(renamed_contents, CONTENTS_OUTPUT, "The renamed output differs from the requested contents");
570    }
571
572    #[test]
573    fn test_output_truncation_failure() {
574        const CONTENTS: &[u8] = b"read-only handle";
575        let fixture = output_paths_test_fixture();
576        let path = fixture.path().join("report.md");
577        write_file_test_fixture(&path, CONTENTS);
578        let file = File::open(&path);
579        let file = assert_ok!(file, "The output fixture must open read-only");
580        let handle = Handle::from_file(file);
581        let handle = assert_ok!(handle, "The read-only output must have a retained identity handle");
582        let system_under_test = OutputFiles {
583            files: vec![OpenedOutput { output: FileOutput::new(&path, b"overwrite"), handle }],
584        };
585
586        let result = system_under_test.write();
587        let contents = read_file_test_fixture(&path);
588
589        let error = assert_some!(result.err(), "A read-only output handle must fail during truncation");
590        let output_error = error.downcast_ref::<OutputIoError>();
591        let output_error = assert_some!(output_error, "Output truncation must retain its operation and path: {error:#}");
592        let truncates_path = matches!(*output_error, OutputIoError::Truncate(ref failed_path) if failed_path == &path);
593        assert!(truncates_path, "Truncation must fail on the retained read-only output handle: {error:#}");
594        assert!(error.downcast_ref::<Error>().is_some(), "Truncation failures must retain their I/O error: {error:#}");
595        assert_eq!(contents, CONTENTS, "A failed handle truncation must preserve the output contents");
596    }
597
598    #[rstest]
599    fn test_unplanned_output_write(#[values(false, true)] existing: bool) {
600        const CONTENTS_EXISTING: &[u8] = b"existing unplanned output";
601        let fixture = output_paths_test_fixture();
602        let planned = fixture.path().join("planned.md");
603        let unplanned = fixture.path().join("unplanned.md");
604        if existing {
605            write_file_test_fixture(&unplanned, CONTENTS_EXISTING);
606        }
607        let opened = OutputFiles::open(&[FileOutput::new(&planned, b"planned")], &[]);
608        let mut system_under_test = assert_ok!(opened, "Failed to reserve the planned output");
609
610        let result = system_under_test.write_output(&FileOutput::new(&unplanned, b"unvalidated"));
611        let planned_contents = read_file_test_fixture(&planned);
612        let unplanned_contents = fs::read(&unplanned);
613
614        let error = assert_some!(result.err(), "Writing an unplanned output must return an error");
615        let unplanned_path = unplanned.display().to_string();
616        assert_contains!(error.to_string(), &unplanned_path, "The error must identify the unopened output path: {error:#}");
617        assert!(planned_contents.is_empty(), "An unplanned write changed the reserved output");
618        if existing {
619            let contents = assert_ok!(unplanned_contents, "The unplanned output must remain readable after rejection");
620            assert_eq!(contents, CONTENTS_EXISTING, "Rejecting an unplanned output must preserve its contents");
621        } else {
622            let missing = unplanned_contents.is_err_and(|read_error| read_error.kind() == ErrorKind::NotFound);
623            assert!(missing, "Rejecting an unplanned output must not create it");
624        }
625    }
626
627    #[test]
628    fn test_empty_output_plan() {
629        let system_under_test = OutputFiles::open(&[], &[]);
630        let system_under_test = assert_ok!(system_under_test, "An empty output plan must open successfully");
631
632        let written = system_under_test.write();
633        assert_ok!(written, "Writing an empty output plan must succeed without creating files");
634    }
635}