From 0b020a1cb61710b8e8e05ea71ff9dcf73b3accf4 Mon Sep 17 00:00:00 2001 From: Awiteb Date: Thu, 9 May 2024 13:28:06 +0300 Subject: [PATCH] chore: Create new utils for custom fields Is `get_duplicated_field` and `apply_custom_fields` utils --- src/utils.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/utils.rs b/src/utils.rs index 525b0ce..fc2a979 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -14,6 +14,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use std::collections::BTreeMap; use std::{fs, path::PathBuf}; use inquire::{validator::Validation, Password, PasswordDisplayMode}; @@ -174,3 +175,33 @@ pub fn lprs_version() -> LprsResult> { } Ok(None) } + +/// Returns the duplicated field from the custom field (unprocessed fields) +pub fn get_duplicated_field(fields: &[(String, String)]) -> Option<&str> { + fields.iter().find_map(|(key, _)| { + if fields.iter().filter(|(k, _)| key == k).count() > 1 { + return Some(key.as_str()); + } + None + }) +} + +/// Apply the edited fields to the vault fields. +/// This will: +/// - Add the field if it's not in the fields map. +/// - Update the field if it's in the map. +/// - Remove the field if its value is empty string. +pub fn apply_custom_fields( + fields: &mut BTreeMap, + edited_fields: Vec<(String, String)>, +) { + for (key, value) in edited_fields { + if fields.contains_key(&key) && value.is_empty() { + fields.remove(&key); + } else { + // The field is not there or its value not empty, + // so add it or update its value + fields.insert(key, value); + } + } +}