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
use crate::TError;
#[derive(Debug)]
pub struct YamlSolver {
expression: Vec<String>,
}
impl From<&clap::ArgMatches<'_>> for YamlSolver {
fn from(input: &clap::ArgMatches<'_>) -> YamlSolver {
let expression = input
.value_of("expression")
.map(|s| s.split('.').map(String::from).collect::<_>())
.unwrap_or_default();
YamlSolver { expression }
}
}
impl YamlSolver {
pub fn resolve_value(&self, value: &str) -> Result<String, TError> {
let root = serde_yaml::from_str::<serde_yaml::Value>(value)?;
let mut result = vec![&root];
for expr in &self.expression {
result = result
.into_iter()
.map(
|reader| -> Box<dyn Iterator<Item = Result<&serde_yaml::Value, TError>>> {
match reader {
serde_yaml::Value::Sequence(v) => {
let next = v.iter().map(|o| {
o.get(expr.as_str())
.ok_or_else(|| TError::KeyNotExist(expr.clone()))
});
Box::new(next)
}
o => {
let next = std::iter::once(
o.get(expr.as_str())
.ok_or_else(|| TError::KeyNotExist(expr.clone())),
);
Box::new(next)
}
}
},
)
.flatten()
.collect::<Result<Vec<_>, _>>()?;
}
Ok(result
.iter()
.map(|s| format!("{}\n", YamlSolver::value_to_string(s)))
.collect::<String>())
}
fn value_to_string(value: &serde_yaml::Value) -> String {
serde_yaml::to_string(value).unwrap()
}
}
pub fn clap_app() -> clap::App<'static, 'static> {
clap::App::new("yaml")
.about("Perform queries on YAML files")
.arg(
clap::Arg::with_name("expression")
.long("expression")
.help("Expression to evaluate the input with.")
.takes_value(true),
)
.author(clap::crate_authors!())
}