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