- Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathmod.rs
More file actions
Latest commit
322 lines (286 loc) · 10.3 KB
/
Copy pathmod.rs
File metadata and controls
322 lines (286 loc) · 10.3 KB
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
use{
crate::config::{
Config,
Content,
OptionValue,
Template,
VariableDefinition,
},
anyhow::Result,
async_trait::async_trait,
fancy_regex::Regex,
handlebars::RenderError,
std::{
collections::{
BTreeMap,
HashMap,
},
env,
},
};
#[cfg(feature = "backend+cli")]
pubmod cli;
pubmod headless;
#[derive(Debug)]
pubenumBackend{
Headless,
#[cfg(feature = "backend+cli")]
CLI,
}
#[derive(Debug)]
pubstructRenderArguments{
pubconfiguration:String,
pubtemplate:Option<String>,
pubvalue_overrides:HashMap<String,String>,
pubshell_trust:ShellTrust,
publoose:bool,
pubbackend:Backend,
}
#[derive(Debug)]
pubstructDirectArguments{
pubtemplate:String,
pubvalues:String,
}
#[derive(Debug,Eq,PartialEq)]
pubenumShellTrust{
None,
Ultimate,
}
pubasyncfnmake_handlebars<'a>(
variable_values:&HashMap<String,String>,
helpers:&'a std::option::Option<HashMap<String,String>>,
shell_trust:&ShellTrust,
strict:bool,
) -> Result<(handlebars::Handlebars<'a>, serde_json::Value)>{
fnrecursive_add(namespace:&mut std::collections::VecDeque<String>,parent:&mut serde_json::Value,value:&str){
let current_namespace = namespace.pop_front().unwrap();
match namespace.len(){
| 0 => {
parent
.as_object_mut()
.unwrap()
.entry(¤t_namespace)
.or_insert(serde_json::Value::String(value.into()));
},
| _ => {
let p = parent
.as_object_mut()
.unwrap()
.entry(¤t_namespace)
.or_insert(serde_json::Value::Object(serde_json::Map::new()));
recursive_add(namespace, p, value);
},
}
}
letmut values_json = serde_json::Value::Object(serde_json::Map::new());
for val in variable_values {
let namespaces_vec:Vec<String> = val.0.split('.').map(|s| s.to_string()).collect();
letmut namespaces = std::collections::VecDeque::from(namespaces_vec);
recursive_add(&mut namespaces,&mut values_json, val.1);
}
letmut hb = handlebars::Handlebars::new();
hb.register_escape_fn(|s| s.into());
hb.set_strict_mode(strict);
ifletSome(helpers) = helpers {
if helpers.len() > 0 && shell_trust != &ShellTrust::Ultimate{
returnErr(anyhow::anyhow!("need trust for executing helper functions").into());
}
for helper in helpers {
let h_func = move |h:&handlebars::Helper,
_:&handlebars::Handlebars,
_:&handlebars::Context,
_:&mut handlebars::RenderContext,
out:&mutdyn handlebars::Output|
-> handlebars::HelperResult{
let param = h.param(0).ok_or(RenderError::new("parameter is not a string"))?;
let cmd = helper.1;
let output = std::process::Command::new("sh")
.arg("-c")
.arg(cmd)
.env(
"VALUE",
param
.value()
.as_str()
.ok_or(RenderError::new("parameter is not a string"))?,
)
.output()?;
if output.status.code().unwrap() != 0{
returnErr(RenderError::new("failed to get command status"));
}
out.write(String::from_utf8(output.stdout)?.as_str())?;
Ok(())
};
hb.register_helper(helper.0,Box::new(h_func))
}
}
Ok((hb, values_json))
}
pubasyncfnselect_template<'a>(
config:&'aConfig,
backend:&Backend,
shell_trust:&ShellTrust,
) -> Result<&'aTemplate>{
let templates = config.templates.keys().cloned().collect::<Vec<String>>();
letmut template_map = BTreeMap::new();
for t in templates {
template_map.insert(t.to_owned(),crate::config::Option{
display: t.to_owned(),
value:OptionValue::Static(t.into()),
});
}
let be = backend.to_input(shell_trust)?;
let selection = be.select("",&template_map).await?;
match config.templates.get(&selection){
| Some(x) => Ok(x),
| None => Err(anyhow::anyhow!("invalid template selection")),
}
}
pubasyncfnpopulate_variables(
vars:&std::collections::HashMap<String,VariableDefinition>,
value_overrides:&std::collections::HashMap<String,String>,
shell_trust:&ShellTrust,
backend:&Backend,
prefix:Option<String>,
) -> Result<HashMap<String,String>>{
letmut values = HashMap::<String,String>::new();
for v_override in value_overrides {
values.insert(v_override.0.into(), v_override.1.into());
}
for var in vars {
ifNone == values.get(var.0){
values.insert(var.0.into(), var.1.execute(shell_trust, backend).await?);
}
}
let values = values
.iter()
.map(|(k, v)| {
letmut key = k.clone();
ifletSome(p) = &prefix {
key = format!("{}.{}", p, key);
}
(key, v.clone())
})
.collect::<HashMap<String,String>>();
Ok(values)
}
pubasyncfnrender_template(
template:&Template,
value_overrides:&HashMap<String,String>,
shell_trust:&ShellTrust,
backend:&Backend,
strict:bool,
) -> Result<String>{
let template_str = match&template.content{
| Content::Inline(x) => x.into(),
| Content::File(x) => std::fs::read_to_string(x)?,
};
let values = ifletSome(variables) = &template.variables{
populate_variables(variables, value_overrides, shell_trust, backend,None).await?
}else{
HashMap::<_,_>::new()
};
let hb = make_handlebars(&values,&template.helpers, shell_trust, strict).await?;
hb.0.render_template(&template_str,&hb.1)
.map_err(|e| anyhow::anyhow!(e))
}
pubasyncfnrender_direct(template:String,values:String) -> Result<String>{
let values = serde_json::from_str::<serde_json::Value>(&values)?;
letmut hb = handlebars::Handlebars::new();
hb.register_escape_fn(|s| s.into());
hb.set_strict_mode(true);
Ok(hb.render_template(&template,&values)?)
}
pubasyncfnselect_and_render(invoke_options:RenderArguments) -> Result<String>{
#[derive(serde::Deserialize)]
structWithVersion{
version:String,
}
let version_check:WithVersion = serde_yaml::from_str(&invoke_options.configuration)
.or::<anyhow::Error>(Err(anyhow::anyhow!("config missing version field")))?;
let version_regex = Regex::new("^([0-9]+)\\.([0-9]+)$")?;
if !version_regex.is_match(&version_check.version)? {
returnErr(anyhow::anyhow!("invalid version: {}", version_check.version));
}
let expected_version = env!("CARGO_PKG_VERSION").split(".").collect::<Vec<_>>()[..2].join(".");
ifenv!("CARGO_PKG_VERSION") != "0.0.0"{
if&version_check.version != &expected_version {
returnErr(anyhow::anyhow!("config file version mismatch to binary"));
}
}
let cfg:Config = serde_yaml::from_str(&invoke_options.configuration)?;
let template = match&invoke_options.template{
| Some(x) => {
cfg.templates
.get(x)
.ok_or_else(|| anyhow::anyhow!("template not found"))?
},
| None => select_template(&cfg,&invoke_options.backend,&invoke_options.shell_trust).await?,
};
render_template(
template,
&invoke_options.value_overrides,
&invoke_options.shell_trust,
&invoke_options.backend,
!invoke_options.loose,
)
.await
}
#[async_trait]
pubtraitResolve{
asyncfnexecute(&self,shell_trust:&ShellTrust,backend:&Backend) -> Result<String>;
}
#[async_trait]
pubtraitUserInput:Send+Sync{
asyncfnprompt(&self,text:&str) -> Result<String>;
asyncfnselect(&self,prompt:&str,options:&BTreeMap<String,crate::config::Option>) -> Result<String>;
asyncfncheck(
&self,
prompt:&str,
separator:&str,
options:&BTreeMap<String,crate::config::Option>,
) -> Result<String>;
}
implBackend{
pubfnto_input<'a>(&self,shell_trust:&'aShellTrust) -> Result<Box<dynUserInput+'a>>{
Ok(matchself{
| Backend::Headless => Box::new(headless::HeadlessBackend::new())asBox<dynUserInput>,
#[cfg(feature = "backend+cli")]
| Backend::CLI => Box::new(cli::CLIBackend::new(shell_trust))asBox<dynUserInput>,
})
}
}
#[async_trait]
implResolveforVariableDefinition{
asyncfnexecute(&self,shell_trust:&ShellTrust,backend:&Backend) -> Result<String>{
let backend_impl = backend.to_input(shell_trust)?;
matchself{
| VariableDefinition::Arg => Err(anyhow::anyhow!("variable missing")),
| VariableDefinition::Env(v) => Ok(env::var(v)?),
| VariableDefinition::Static(v) => Ok(v.into()),
| VariableDefinition::Prompt(v) => backend_impl.prompt(v).await,
| VariableDefinition::Shell(cmd) => shell(cmd,&HashMap::new(), shell_trust).await,
| VariableDefinition::Select{ text, options } => backend_impl.select(text, options).await,
| VariableDefinition::Check{
text,
separator,
options,
} => backend_impl.check(text, separator, options).await,
}
}
}
asyncfnshell(command:&str,env:&HashMap<String,String>,shell_trust:&ShellTrust) -> Result<String>{
match shell_trust {
| ShellTrust::None => returnErr(anyhow::anyhow!("need trust for executing shell commands")),
| ShellTrust::Ultimate => {},
}
let output = std::process::Command::new("sh")
.arg("-c")
.arg(command)
.envs(env)
.output()?;
if output.status.code().unwrap() != 0{
returnErr(anyhow::anyhow!("shell command error:\n{}", command));
}
Ok(String::from_utf8(output.stdout)?)
}