Debian Codegraph @

fcheck-testdata/src/output.rs

raw
1 // SPDX-FileCopyrightText: Peter Pentchev <[email protected]>
2 // SPDX-License-Identifier: BSD-2-Clause
3 //! Test file output routines for the feature-check test generator.
4
5 use std::io::Write;
6 use std::path::Path;
7
8 use anyhow::Context;
9 use handlebars::Handlebars;
10 use tempfile::NamedTempFile;
11 use tracing::debug;
12
13 use crate::defs::{Config, Error, TestData, TEMPLATE_NAME};
14
15 /// Render the test data into the specified output file.
16 ///
17 /// # Errors
18 ///
19 /// Fails on template rendering errors or on filesystem errors when
20 /// writing out or renaming the temporary file.
21 pub fn write_output_file(
22 cfg: &Config,
23 template: &Handlebars<'_>,
24 test_data: &TestData,
25 ) -> Result<(), Error> {
26 let output = template
27 .render(TEMPLATE_NAME, &test_data)
28 .map_err(|err| Error::Render(cfg.template_path.clone(), cfg.data_path.clone(), err))?;
29 debug!(
30 "About to write {count} characters to {output}",
31 count = output.len(),
32 output = cfg.output_path
33 );
34
35 let opath = Path::new(&cfg.output_path);
36 let odir = opath
37 .parent()
38 .with_context(|| {
39 format!(
40 "Could not determine the parent directory of {output}",
41 output = cfg.output_path
42 )
43 })
44 .map_err(Error::IO)?;
45 let mut tempf = NamedTempFile::new_in(odir)
46 .with_context(|| {
47 format!(
48 "Could not create a temporary file in the {odir} directory",
49 odir = odir.display()
50 )
51 })
52 .map_err(Error::IO)?;
53 let tempf_path = tempf.path().display().to_string();
54 debug!("Using {tempf_path} as a temporary output file");
55 tempf
56 .write_all(output.as_bytes())
57 .with_context(|| format!("Could not write to the {tempf_path} temporary file"))
58 .map_err(Error::IO)?;
59 debug!("Overwriting the output file");
60 tempf
61 .persist(&cfg.output_path)
62 .with_context(|| {
63 format!(
64 "Could not rename the {tempf_path} temporary file to {output}",
65 output = cfg.output_path
66 )
67 })
68 .map_err(Error::IO)?;
69 Ok(())
70 }