Skip to content

Commit

Permalink
✨ Add an option to pick any field
Browse files Browse the repository at this point in the history
  • Loading branch information
uzimaru0000 committed Sep 24, 2021
1 parent f47905a commit fbca75a
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/application.rs
Expand Up @@ -9,6 +9,7 @@ pub struct Application<'a, 'b> {
app: App<'a, 'b>,
path: Option<String>,
sort_key: Option<String>,
pick: Option<String>,
align: Align,
style: Style,
no_headers: bool,
Expand Down Expand Up @@ -58,6 +59,14 @@ impl<'a, 'b> Application<'a, 'b> {
.short("r")
.long("recursive")
.help("Recursive display"),
)
.arg(
Arg::with_name("pick")
.short("p")
.long("pick")
.value_name("PICK FIELD")
.help("Pick up field")
.takes_value(true),
);

let matcher = app.clone().get_matches();
Expand All @@ -75,6 +84,7 @@ impl<'a, 'b> Application<'a, 'b> {
.unwrap_or(Style::Ascii);
let no_headers = matcher.is_present("no headers");
let recursive = matcher.is_present("recursive");
let pick = matcher.value_of("pick").map(String::from);

Self {
app,
Expand All @@ -84,6 +94,7 @@ impl<'a, 'b> Application<'a, 'b> {
style,
no_headers,
recursive,
pick,
}
}

Expand All @@ -103,6 +114,10 @@ impl<'a, 'b> Application<'a, 'b> {
}?;

let mut data = Data::from(&raw)?;

if let Some(key) = self.pick.clone() {
data = data.pick(key)?;
}
data.set_sort_key(self.sort_key.clone());

self.show(data);
Expand Down
29 changes: 29 additions & 0 deletions src/data.rs
Expand Up @@ -160,6 +160,35 @@ impl Data {
})
.collect()
}

pub fn pick(&self, key: String) -> Result<Self> {
let keys = key.split(".").collect::<Vec<_>>();
let data = self
.data
.iter()
.filter_map(|x| match x {
Json::Object(obj) => {
let (&head, tail) = keys.split_first()?;
let init = obj.get(head)?;
tail.iter().try_fold(init, |acc, &x| match acc {
serde_json::Value::Object(obj) => obj.get(x),
_ => None,
})
}
_ => None,
})
.map(|x| match x {
serde_json::Value::Object(obj) => Json::Object(obj.clone()),
_ => Json::Value(x.clone()),
})
.collect::<Vec<_>>();

if data.is_empty() {
return Err(anyhow::Error::msg(format!("{} is not found", key)));
}

Ok(Self::new(data))
}
}

impl Into<Table<String>> for Data {
Expand Down

0 comments on commit fbca75a

Please sign in to comment.