Skip to content

Commit

Permalink
fix: implement ser + deser for keyvals to correctly parse the config
Browse files Browse the repository at this point in the history
  • Loading branch information
cestef committed Jun 21, 2024
1 parent 9643026 commit 5ce8593
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 3 deletions.
5 changes: 2 additions & 3 deletions src/cli/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@ use clap::{
builder::TypedValueParser,
error::{ContextKind, ContextValue, ErrorKind},
};
use serde::{Deserialize, Serialize};
use tabled::Tabled;
use url::Url;

#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize, Tabled)]
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Tabled)]
pub struct KeyVal<T: Display, U: Display>(
#[tabled(rename = "Key")] pub T,
#[tabled(rename = "Value")] pub U,
Expand Down Expand Up @@ -61,7 +60,7 @@ impl TypedValueParser for KeyValParser {
}
}

#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub struct KeyOrKeyVal<T: Display, U: Display>(pub T, pub Option<U>);

impl Display for KeyOrKeyVal<String, String> {
Expand Down
58 changes: 58 additions & 0 deletions src/cli/opts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,64 @@ impl Serialize for Wordlist {
}
}

// deserialize keyorkeyval

impl<'de> Deserialize<'de> for KeyOrKeyVal<String, String> {
fn deserialize<D>(deserializer: D) -> Result<KeyOrKeyVal<String, String>, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
let parts = s.split(':').collect::<Vec<_>>();
if parts.len() == 1 {
Ok(KeyOrKeyVal(parts[0].to_string(), None))
} else {
Ok(KeyOrKeyVal(
parts[0].to_string(),
Some(parts[1].to_string()),
))
}
}
}

impl Serialize for KeyOrKeyVal<String, String> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
format!(
"{}{}",
self.0,
if let Some(v) = &self.1 {
format!(":{}", v)
} else {
"".to_string()
}
)
.serialize(serializer)
}
}

impl<'de> Deserialize<'de> for KeyVal<String, String> {
fn deserialize<D>(deserializer: D) -> Result<KeyVal<String, String>, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
let parts = s.split(':').collect::<Vec<_>>();
Ok(KeyVal(parts[0].to_string(), parts[1].to_string()))
}
}

impl Serialize for KeyVal<String, String> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
format!("{}:{}", self.0, self.1).serialize(serializer)
}
}

impl Opts {
pub async fn from_path<T>(path: T) -> Result<Self>
where
Expand Down

0 comments on commit 5ce8593

Please sign in to comment.