feat: Add --json flag to the list command
All checks were successful
Rust CI / Rust CI (pull_request) Successful in 1m58s
Write changelog / write-changelog (push) Successful in 3s
Rust CI / Rust CI (push) Successful in 1m54s

This commit is contained in:
Awiteb 2024-05-10 16:07:55 +03:00
parent 21befeaa58
commit a7ad8b4682
Signed by: awiteb
GPG key ID: 3F6B55640AA6682F

View file

@ -15,7 +15,7 @@
// along with this program. If not, see <https://www.gnu.org/licenses/gpl-3.0.html>. // along with this program. If not, see <https://www.gnu.org/licenses/gpl-3.0.html>.
use clap::Args; use clap::Args;
use inquire::Select; use inquire::{InquireError, Select};
use crate::{vault::Vaults, LprsCommand, LprsError, LprsResult}; use crate::{vault::Vaults, LprsCommand, LprsError, LprsResult};
@ -29,6 +29,9 @@ pub struct List {
/// Enable regex when use `--filter` option /// Enable regex when use `--filter` option
#[arg(short, long)] #[arg(short, long)]
regex: bool, regex: bool,
/// Returns the output as `json` list of vaults
#[arg(long)]
json: bool,
} }
impl LprsCommand for List { impl LprsCommand for List {
@ -51,29 +54,25 @@ impl LprsCommand for List {
let re = regex::Regex::new(&pattern)?; let re = regex::Regex::new(&pattern)?;
let vaults_list = vault_manager let vaults_list = vault_manager.vaults.iter().enumerate().filter(|(_, v)| {
.vaults re.is_match(&v.name)
.iter()
.enumerate()
.filter_map(|(idx, v)| {
if re.is_match(&v.name)
|| v.username.as_deref().is_some_and(|u| re.is_match(u)) || v.username.as_deref().is_some_and(|u| re.is_match(u))
|| v.service.as_deref().is_some_and(|s| re.is_match(s)) || v.service.as_deref().is_some_and(|s| re.is_match(s))
|| v.note.as_deref().is_some_and(|n| re.is_match(n)) || v.note.as_deref().is_some_and(|n| re.is_match(n))
{ });
return Some(format!("{}) {}", idx + 1, v.list_name()));
}
None
})
.collect::<Vec<_>>();
if vaults_list.is_empty() { if self.json {
return Err(LprsError::Other( print!(
"There is no result match your filter".to_owned(), "{}",
)); serde_json::to_string(&vaults_list.map(|(_, v)| v).collect::<Vec<_>>())?
} )
} else {
let vault_idx = Select::new("Select a vault to view:", vaults_list) let vault_idx = Select::new(
"Select a vault to view:",
vaults_list
.map(|(idx, v)| format!("{}) {}", idx + 1, v.list_name()))
.collect(),
)
.with_formatter(&|s| { .with_formatter(&|s| {
s.value s.value
.split_once(") ") .split_once(") ")
@ -81,7 +80,13 @@ impl LprsCommand for List {
.1 .1
.to_owned() .to_owned()
}) })
.prompt()? .prompt()
.map_err(|err| {
if matches!(err, InquireError::InvalidConfiguration(_)) {
return LprsError::Other("There is no result match your filter".to_owned());
}
err.into()
})?
.split_once(')') .split_once(')')
.expect("The bracket are hard coded above") .expect("The bracket are hard coded above")
.0 .0
@ -97,6 +102,7 @@ impl LprsCommand for List {
.get(vault_idx - 1) .get(vault_idx - 1)
.expect("The index is correct") .expect("The index is correct")
); );
}
Ok(()) Ok(())
} }