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
use std::{
borrow::Cow,
collections::HashMap,
fs,
io::{self, Read},
};
use crate::{cli, error::Error};
#[derive(Debug)]
pub struct Source {
pub content: String,
pub file: Option<String>,
}
pub fn load_sources(
source_args: &[cli::SourceArg],
template_args: &[cli::TemplateArg],
) -> Result<Vec<Source>, Error> {
let context = Context::from(template_args);
let mut result = Vec::new();
for source_arg in source_args.iter() {
let (file, raw_content) = load_content(source_arg)?;
let content = render_source(&context, raw_content.as_ref());
result.push(Source { content, file });
}
Ok(result)
}
fn load_content(
source_arg: &cli::SourceArg,
) -> Result<(Option<String>, Cow<'_, str>), Error> {
use cli::SourceArg::*;
match source_arg {
Pipe => {
let stdin = io::stdin();
let mut handle = stdin.lock();
let mut buffer = String::new();
handle
.read_to_string(&mut buffer)
.map_err(|_| Error::CannotReadStdIn)?;
Ok((None, Cow::Owned(buffer)))
}
Expr(e) => Ok((None, Cow::Borrowed(e.as_str()))),
File(f) => {
let mut file = fs::File::open(f).map_err(|_| {
Error::CannotReadFile(f.to_string_lossy().to_string())
})?;
let mut buffer = String::new();
file.read_to_string(&mut buffer).map_err(|_| {
Error::CannotReadFile(f.to_string_lossy().to_string())
})?;
Ok((Some(f.to_string_lossy().to_string()), Cow::Owned(buffer)))
}
}
}
fn render_source(context: &Context, source: &str) -> String {
let after_shebang = if source.starts_with("#!") {
match source.split_once('\n') {
Some((_, remaining)) => remaining,
None => "",
}
} else {
source
}
.trim();
if let Some(ref regex) = context.regex {
let mut fragments = Vec::<String>::new();
let mut remaining = after_shebang;
while let Some(captures) = regex.captures(remaining) {
let full_match = captures.get(0).unwrap();
let (upto, after) = remaining.split_at(full_match.end());
let (before, _) = upto.split_at(full_match.start());
fragments.push(before.to_string());
let value = context
.table
.get(captures.get(1).unwrap().as_str())
.unwrap();
fragments.push(value.clone());
remaining = after;
}
fragments.push(remaining.to_string());
fragments.join("")
} else {
after_shebang.into()
}
}
#[derive(Debug)]
struct Context {
table: HashMap<String, String>,
regex: Option<regex::Regex>,
}
impl From<&[cli::TemplateArg]> for Context {
fn from(template_args: &[cli::TemplateArg]) -> Self {
let table = template_args.iter().fold(HashMap::new(), |mut m, a| {
if let Some(ref n) = a.name {
m.insert(n.clone(), a.value.clone());
}
if let Some(i) = a.pos {
m.insert((i + 1).to_string(), a.value.clone());
}
m
});
let regex = if table.is_empty() {
None
} else {
let keys = table
.keys()
.map(|s| regex::escape(s))
.collect::<Vec<String>>();
let key_union = keys.join("|");
let pat = format!(r#"#nr\s*\[\s*({})\s*\]"#, key_union,);
Some(regex::Regex::new(&pat).unwrap())
};
Self { table, regex }
}
}