1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
use anyhow::Context;
use serde::Deserialize;
use std::collections::HashMap;
use std::io::{Read, Write};

#[derive(Deserialize, Debug)]
pub struct Template<'t> {
    // Due to https://github.com/alexcrichton/toml-rs/issues/397 the value in
    // this HashMap cannot be `&'c str` like I'd want.
    #[serde(borrow)]
    pub variables: Option<HashMap<&'t str, String>>,
}

impl<'t> Template<'t> {
    fn extend(&mut self, other: Template<'t>) {
        if other.variables.is_none() {
            return;
        }
        if let Some(variables) = &mut self.variables {
            variables.extend(other.variables.unwrap());
        } else {
            self.variables = other.variables;
        }
    }

    fn substitute(&self, input: String) -> String {
        let mut output = input;
        if let Some(variables) = &self.variables {
            for x in variables {
                let substitution = format!("{{{}}}", x.0);
                output = output.replace(&substitution, x.1);
            }
        }
        output
    }
}

pub fn transform(
    mut input_toml: impl Read,
    template_tomls: &mut [impl Read],
    mut output_toml: impl Write,
    extra_template: Option<Template<'_>>,
) -> anyhow::Result<()> {
    assert!(!template_tomls.is_empty());

    log::info!("Reading input data");
    let input = {
        let mut input = String::new();
        input_toml
            .read_to_string(&mut input)
            .context("Could not read input_toml")?;
        input
    };

    let mut template_texts = Vec::with_capacity(template_tomls.len());
    log::info!("Reading template data");
    for template_toml in template_tomls {
        let mut template = String::new();
        template_toml
            .read_to_string(&mut template)
            .context("Could not read template_toml")?;
        template_texts.push(template);
    }

    log::info!("Parsing template data");
    let mut template = None::<Template>;
    for template_text in &template_texts {
        let template_next: Template =
            toml::from_str(&template_text).context("Could not parse template data")?;
        if let Some(template) = &mut template {
            template.extend(template_next);
        } else {
            template = Some(template_next);
        }
    }
    let mut template = template.unwrap();
    if let Some(extra_template) = extra_template {
        template.extend(extra_template);
    }
    log::trace!("{:#?}", template);

    let output = template.substitute(input);

    log::info!("Writing output data");
    Ok(output_toml.write_all(output.as_bytes())?)
}

#[cfg(test)]
mod test {
    use super::transform;
    use crate::Template;
    use std::collections::HashMap;

    #[test]
    fn id() {
        let input = String::from(
            r#"[package]
name = "tomlplate"
        "#,
        );
        let template = String::new();
        let expected_output = input.clone();

        let mut output = Vec::new();
        transform(
            input.as_bytes(),
            &mut [template.as_bytes()],
            &mut output,
            None,
        )
        .unwrap();
        let output = String::from_utf8(output).unwrap();

        assert_eq!(expected_output, output);
    }

    #[test]
    fn simple_substitution() {
        let input = String::from(
            r#"[package]
name = "Some {name}"
        "#,
        );
        let template = String::from(
            r#"[variables]
name = "tomlplate"
        "#,
        );
        let expected_output = String::from(
            r#"[package]
name = "Some tomlplate"
        "#,
        );

        let mut output = Vec::new();
        transform(
            input.as_bytes(),
            &mut [template.as_bytes()],
            &mut output,
            None,
        )
        .unwrap();
        let output = String::from_utf8(output).unwrap();

        assert_eq!(expected_output, output);
    }

    #[test]
    fn simple_substitution_extra_template() {
        let input = String::from(
            r#"[package]
name = "Some {name}"
        "#,
        );
        let template = String::new();
        let expected_output = String::from(
            r#"[package]
name = "Some tomlplate"
        "#,
        );

        let mut extra_template = Template {
            variables: Some(HashMap::new()),
        };
        extra_template
            .variables
            .as_mut()
            .unwrap()
            .insert("name", "tomlplate".into());

        let mut output = Vec::new();
        transform(
            input.as_bytes(),
            &mut [template.as_bytes()],
            &mut output,
            Some(extra_template),
        )
        .unwrap();
        let output = String::from_utf8(output).unwrap();

        assert_eq!(expected_output, output);
    }

    #[test]
    fn simple_substitution_multiple_templates() {
        let input = String::from(
            r#"[package]
name = "Some {name}"
        "#,
        );
        let template1 = String::from(
            r#"[variables]
name = "tomlplate"
        "#,
        );
        let template2 = String::from(
            r#"[variables]
name = "tomlplate2"
        "#,
        );
        let expected_output = String::from(
            r#"[package]
name = "Some tomlplate2"
        "#,
        );

        let mut output = Vec::new();
        transform(
            input.as_bytes(),
            &mut [template1.as_bytes(), template2.as_bytes()],
            &mut output,
            None,
        )
        .unwrap();
        let output = String::from_utf8(output).unwrap();

        assert_eq!(expected_output, output);
    }
}