feat: Ability to edit & remove by name (not index only) #44

Merged
awiteb merged 3 commits from awiteb/fix-36 into master 2024-05-11 07:43:07 +02:00 AGit
2 changed files with 36 additions and 21 deletions
Showing only changes of commit 6e8c214b9e - Show all commits

View file

@ -19,6 +19,7 @@ use std::str::FromStr;
use clap::Args;
use crate::{
utils,
vault::{Vault, Vaults},
LprsCommand,
LprsError,
@ -96,27 +97,9 @@ pub struct Get {
}
impl LprsCommand for Get {
fn run(self, vault_manager: Vaults) -> LprsResult<()> {
let parsed_index = self.location.trim().parse::<usize>();
let Some((index, vault)) = (if let Ok(index) = parsed_index {
vault_manager.vaults.get(index - 1).map(|v| (index, v))
} else {
vault_manager
.vaults
.iter()
.enumerate()
.find(|(_, v)| v.name == self.location)
}) else {
return Err(LprsError::Other(format!(
"There is no vault with the given {} `{}`",
if parsed_index.is_ok() {
"index"
} else {
"name"
},
self.location.trim(),
)));
};
fn run(self, mut vault_manager: Vaults) -> LprsResult<()> {
let (index, vault) =
utils::vault_by_index_or_name(self.location.trim(), &mut vault_manager.vaults)?;
if let Some(field) = self.field {
if field == VaultGetField::Index {

View file

@ -23,6 +23,7 @@ use passwords::{analyzer, scorer};
use reqwest::blocking::Client as BlockingClient;
use sha2::Digest;
use crate::vault::Vault;
use crate::{LprsError, LprsResult};
/// Returns the local project dir joined with the given file name
@ -205,3 +206,34 @@ pub fn apply_custom_fields(
}
}
}
/// Returns the vault with its index by its index or name
///
/// ## Errors
/// - If there is no vault with the given index or name
pub fn vault_by_index_or_name<'a>(
index_or_name: &str,
vaults: &'a mut [Vault],
) -> LprsResult<(usize, &'a mut Vault)> {
let parsed_index = index_or_name.parse::<usize>();
let Some((index, vault)) = (if let Ok(index) = parsed_index {
vaults.get_mut(index - 1).map(|v| (index, v))
} else {
vaults
.iter_mut()
.enumerate()
.find(|(_, v)| v.name == index_or_name)
}) else {
return Err(LprsError::Other(format!(
"There is no vault with the given {} `{}`",
if parsed_index.is_ok() {
"index"
} else {
"name"
},
index_or_name,
)));
};
Ok((index, vault))
}