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
use ramhorns::{Content, Template};
use serde::{Deserialize, Serialize};
use std::{fs, io, path::Path};
use toml;
#[derive(Content, Debug, Deserialize, Serialize)]
pub struct Reagent {
pub package: Option<String>,
pub description: Option<String>,
pub url: Option<String>,
pub version: Option<String>,
pub license: Option<String>,
pub name: Option<String>,
pub email: Option<String>,
#[serde(default)]
pub debian: bool,
#[serde(default)]
pub redox: bool,
}
impl Reagent {
pub fn from_path<P: AsRef<Path>>(path: P) -> io::Result<Self> {
let toml = fs::read_to_string(path)?;
toml::from_str(&toml).map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))
}
pub fn split(string: &str) -> (&str, &str, &str) {
let mut start_opt = None;
let mut end_opt = None;
let mut last_index = 0;
for (index, newline) in string.match_indices("\n") {
let line = &string[last_index..index];
if line.contains("<reagent>") {
if start_opt.is_some() {
eprintln!("reagent: duplicate <reagent> tag");
}
start_opt = Some(last_index);
}
if line.contains("</reagent>") {
if end_opt.is_some() {
eprintln!("reagent: duplicate </reagent> tag");
}
end_opt = Some(index + newline.len());
}
last_index = index + newline.len();
}
let start = start_opt.unwrap_or(0);
let end = end_opt.unwrap_or(string.len());
(&string[..start], &string[start..end], &string[end..])
}
pub fn generate(
&self,
input: &str,
original_opt: Option<&str>,
) -> Result<String, ramhorns::Error> {
let template = Template::new(input)?;
let rendered = template.render(self);
let rendered_split = Self::split(&rendered);
let original_split = match original_opt {
Some(original) => Self::split(original),
None => rendered_split,
};
let mut updated = String::with_capacity(
original_split.0.len() + rendered_split.1.len() + original_split.2.len(),
);
updated.push_str(original_split.0);
updated.push_str(rendered_split.1);
updated.push_str(original_split.2);
Ok(updated)
}
}