Skip to content

Commit

Permalink
feat: treat empty string as none when formating (starship#2738)
Browse files Browse the repository at this point in the history
* treat empty string as none when formating

* update docs

* format & clippy
  • Loading branch information
cymruu authored Jun 29, 2021
1 parent c811e0e commit 72e5a54
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
2 changes: 1 addition & 1 deletion docs/config/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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\] )`.
Expand Down
37 changes: 35 additions & 2 deletions src/formatter/string_formatter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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>,
Expand All @@ -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
Expand Down Expand Up @@ -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))";
Expand Down

0 comments on commit 72e5a54

Please sign in to comment.