From 6e8c214b9e28d7c182b1edb619bc9cc6d30fc836 Mon Sep 17 00:00:00 2001 From: Awiteb Date: Fri, 10 May 2024 17:59:51 +0300 Subject: [PATCH] chore: Use new util to get the vault by index or name --- src/cli/get_command.rs | 25 ++++--------------------- src/utils.rs | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 21 deletions(-) diff --git a/src/cli/get_command.rs b/src/cli/get_command.rs index 5c79568..73f72eb 100644 --- a/src/cli/get_command.rs +++ b/src/cli/get_command.rs @@ -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::(); - 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 { diff --git a/src/utils.rs b/src/utils.rs index 04c2ff3..71b999d 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -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::(); + + 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)) +}