From 529ad751fea384fedec367ca3ff5425a55c691bf Mon Sep 17 00:00:00 2001 From: Filip Bachul Date: Wed, 6 Apr 2022 00:08:27 +0200 Subject: [PATCH] implement deserialization from either a string or toml table --- src/conditional_style.rs | 30 +++++++++++++++++++++++------- src/config.rs | 2 +- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/src/conditional_style.rs b/src/conditional_style.rs index 893a04734..3c9676ffa 100644 --- a/src/conditional_style.rs +++ b/src/conditional_style.rs @@ -1,3 +1,4 @@ +use crate::config::Either; use crate::context::Context; use serde::{Deserialize, Deserializer, Serialize, Serializer}; @@ -75,6 +76,21 @@ impl<'a> StarshipConditionalStyle<'a> { } } +#[derive(Clone, Debug, Default, Serialize, PartialEq)] +pub struct StarshipConditionalStyleConfig<'a>(pub StarshipConditionalStyle<'a>); + +impl<'de: 'a, 'a> Deserialize<'de> for StarshipConditionalStyleConfig<'a> { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let either = Either::, &'a str>::deserialize(deserializer)?; + match either { + Either::First(v) => Ok(Self(v)), + Either::Second(s) => Ok(Self(StarshipConditionalStyle::from(s))), + } + } +} pub fn get_conditional_style<'a>( context: &Context, items: &[StarshipConditionalStyle<'a>], @@ -138,16 +154,16 @@ mod tests { let config = toml::value::Value::String(String::from("bold red dimmed")); let deserializer = ValueDeserializer::new(&config); - let result = StarshipConditionalStyle::deserialize(deserializer); + let result = StarshipConditionalStyleConfig::deserialize(deserializer); assert_eq!( result, - Ok(StarshipConditionalStyle { + Ok(StarshipConditionalStyleConfig(StarshipConditionalStyle { env: None, operator: None, expected_value: None, - style: "bold dimmed red" - }) + style: "bold red dimmed" + })) ); } @@ -161,16 +177,16 @@ mod tests { }; let deserializer = ValueDeserializer::new(&config); - let result = StarshipConditionalStyle::deserialize(deserializer); + let result = StarshipConditionalStyleConfig::deserialize(deserializer); assert_eq!( result, - Ok(StarshipConditionalStyle { + Ok(StarshipConditionalStyleConfig(StarshipConditionalStyle { env: Some("HOSTNAME"), operator: Some(StarshipConditionalStyleOperator::Equal), expected_value: Some("home"), style: "bold dimmed red" - }) + })) ); } diff --git a/src/config.rs b/src/config.rs index ba323dd94..5a2a6f17c 100644 --- a/src/config.rs +++ b/src/config.rs @@ -49,7 +49,7 @@ impl<'a, T: Deserialize<'a> + Default> ModuleConfig<'a, ValueError> for T { } } -#[derive(Clone, Deserialize, Serialize)] +#[derive(Clone, Debug, Deserialize, Serialize)] #[cfg_attr(feature = "config-schema", derive(schemars::JsonSchema))] #[serde(untagged)] pub enum Either {