From 72e5a544fc92eb5313a1fa895bd5b9042a8cc601 Mon Sep 17 00:00:00 2001 From: filip Date: Wed, 30 Jun 2021 01:33:43 +0200 Subject: [PATCH] feat: treat empty string as none when formating (#2738) * treat empty string as none when formating * update docs * format & clippy --- docs/config/README.md | 2 +- src/formatter/string_formatter.rs | 37 +++++++++++++++++++++++++++++-- 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/docs/config/README.md b/docs/config/README.md index 67a68501..7555ba13 100644 --- a/docs/config/README.md +++ b/docs/config/README.md @@ -107,7 +107,7 @@ A conditional format string wrapped in `(` and `)` will not render if all variab For example: -- `(@$region)` will show nothing if the variable `region` is `None`, otherwise `@` followed by the value of region. +- `(@$region)` will show nothing if the variable `region` is `None` or empty string, otherwise `@` followed by the value of region. - `(some text)` will always show nothing since there are no variables wrapped in the braces. - When `$all` is a shortcut for `\[$a$b\] `, `($all)` will show nothing only if `$a` and `$b` are both `None`. This works the same as `(\[$a$b\] )`. diff --git a/src/formatter/string_formatter.rs b/src/formatter/string_formatter.rs index 01d6bd9a..f8be0128 100644 --- a/src/formatter/string_formatter.rs +++ b/src/formatter/string_formatter.rs @@ -284,7 +284,7 @@ impl<'a> StringFormatter<'a> { .unwrap_or_else(|| Ok(Vec::new())), FormatElement::Conditional(format) => { // Show the conditional format string if all the variables inside are not - // none. + // none or empty string. fn should_show_elements<'a>( format_elements: &[FormatElement], variables: &'a VariableMapType<'a>, @@ -307,7 +307,12 @@ impl<'a> StringFormatter<'a> { &meta_variables, ) } - _ => true, + VariableValue::Plain(plain_value) => { + !plain_value.is_empty() + } + VariableValue::Styled(segments) => { + segments.iter().any(|x| !x.value.is_empty()) + } }) // The variable is None or Err, or a meta variable // that shouldn't show @@ -578,6 +583,34 @@ mod tests { match_next!(result_iter, " shouldn't", None); } + #[test] + fn test_empty() { + const FORMAT_STR: &str = "(@$empty)"; + + let formatter = StringFormatter::new(FORMAT_STR) + .unwrap() + .map(|var| match var { + "empty" => Some(Ok("")), + _ => None, + }); + let result = formatter.parse(None).unwrap(); + assert_eq!(result.len(), 0); + } + + #[test] + fn test_styled_empty() { + const FORMAT_STR: &str = "[(@$empty)](red bold)"; + + let formatter = StringFormatter::new(FORMAT_STR) + .unwrap() + .map(|variable| match variable { + "empty" => Some(Ok("")), + _ => None, + }); + let result = formatter.parse(None).unwrap(); + assert_eq!(result.len(), 0); + } + #[test] fn test_nested_conditional() { const FORMAT_STR: &str = "($some ($none)) and ($none ($some))";