From 7254f224e3870ed814b694d0e1a3d015dc3dfea3 Mon Sep 17 00:00:00 2001 From: Nikos Kontakis Date: Mon, 18 Sep 2023 12:39:25 +0300 Subject: [PATCH] Alter deserialize of args with regex --- crates/configuration/src/shared/constants.rs | 2 ++ crates/configuration/src/shared/types.rs | 38 ++++++++++++-------- 2 files changed, 25 insertions(+), 15 deletions(-) diff --git a/crates/configuration/src/shared/constants.rs b/crates/configuration/src/shared/constants.rs index 0b288389a..cf4857057 100644 --- a/crates/configuration/src/shared/constants.rs +++ b/crates/configuration/src/shared/constants.rs @@ -9,5 +9,7 @@ pub const RW_FAILED: &str = "Should be able to read/write - failed. "; pub const DEFAULT_TYPESTATE: &str = "'default' overriding should be ensured by typestate."; pub const VALIDATION_CHECK: &str = "Validation failed. "; +pub const PREFIX_CANT_BE_NONE : &str = "Name prefix can't be None if a value exists."; + pub const THIS_IS_A_BUG: &str = "This is a bug please report it: https://github.com/paritytech/zombienet-sdk/issues"; diff --git a/crates/configuration/src/shared/types.rs b/crates/configuration/src/shared/types.rs index fb419a70e..2e7711825 100644 --- a/crates/configuration/src/shared/types.rs +++ b/crates/configuration/src/shared/types.rs @@ -10,8 +10,8 @@ use regex::Regex; use serde::{de, Deserialize, Deserializer, Serialize}; use url::Url; -use super::{constants::INFAILABLE, errors::ConversionError, resources::Resources}; -use crate::shared::constants::{SHOULD_COMPILE, THIS_IS_A_BUG}; +use super::{errors::ConversionError, resources::Resources}; +use crate::shared::constants::{SHOULD_COMPILE, THIS_IS_A_BUG, INFAILABLE, PREFIX_CANT_BE_NONE}; /// An alias for a duration in seconds. pub type Duration = u32; @@ -355,21 +355,29 @@ impl<'de> de::Visitor<'de> for ArgVisitor { where E: de::Error, { - if v.contains('=') || v.starts_with("--") || v.starts_with('-') { - if v.contains('=') { - let split: Vec<&str> = v.split('=').collect::>(); - Ok(Arg::Option(split[0].to_string(), split[1].to_string())) - } else { - let split: Vec<&str> = v.split(' ').collect::>(); - if split.len() == 1 { - Ok(Arg::Flag(v.to_string())) - } else { - Ok(Arg::Option(split[0].to_string(), split[1].to_string())) - } + let re = Regex::new("^(?(?-{1,2})(?[a-zA-Z]+(-[a-zA-Z]+)*))((?=| )(?.+))?$").unwrap(); + let captures = re.captures(v); + + if let Some(captures) = captures { + if let Some(value) = captures.name("value") { + return Ok(Arg::Option( + captures + .name("name_prefix") + .expect(&format!("{} {}", PREFIX_CANT_BE_NONE, THIS_IS_A_BUG)) + .as_str() + .to_string(), + value.as_str().to_string(), + )); + } + + if let Some(name_prefix) = captures.name("name_prefix") { + return Ok(Arg::Flag(name_prefix.as_str().to_string())); } - } else { - Ok(Arg::Flag(v.to_string())) } + + Err(de::Error::custom( + "the provided argument is invalid and doesn't match Arg::Option or Arg::Flag", + )) } }