libmake/
interface.rs

1// Copyright notice and licensing information.
2// These lines indicate the copyright of the software and its licensing terms.
3// SPDX-License-Identifier: Apache-2.0 OR MIT indicates dual licensing under Apache 2.0 or MIT licenses.
4// Copyright © 2023-2024 LibMake. All rights reserved.
5
6use crate::macro_replace_placeholder;
7use crate::models::model_params::FileGenerationParams;
8use std::{
9    fs::File,
10    io::{BufRead, BufReader, Write},
11    path::PathBuf,
12};
13
14/// Replaces placeholders in a template file with values from the provided parameters
15/// and writes the result to an output file.
16///
17/// # Arguments
18///
19/// * `template_file` - Path to the template file.
20/// * `output_file` - Path to the output file where the result should be written.
21/// * `params` - Parameters containing values to replace placeholders in the template.
22///
23/// # Errors
24///
25/// Returns an `std::io::Result` error if:
26///
27/// - The template file cannot be read.
28/// - The output file cannot be created or written to.
29/// - There are issues parsing the template or replacing placeholders.
30///
31pub fn replace_placeholders(
32    template_file: &PathBuf,
33    output_file: &PathBuf,
34    params: &FileGenerationParams,
35) -> std::io::Result<()> {
36    let tpl = File::open(template_file)?;
37    let tpl_reader = BufReader::new(tpl);
38    let mut output = File::create(output_file)?;
39    let tpl_lines = tpl_reader.lines();
40
41    for line in tpl_lines {
42        let line = line?;
43        let replaced_line = macro_replace_placeholder!(
44            line,
45            params,
46            author,
47            build,
48            categories,
49            description,
50            documentation,
51            edition,
52            email,
53            homepage,
54            keywords,
55            license,
56            name,
57            output,
58            readme,
59            repository,
60            rustversion,
61            version,
62            website
63        );
64        writeln!(output, "{replaced_line}")?;
65    }
66
67    Ok(())
68}