refactor(env): Generalize bool policy

This commit is contained in:
Ed Page 2022-05-12 16:21:11 -05:00
parent 200f6626db
commit 73fc240c57
2 changed files with 11 additions and 5 deletions

View file

@ -1417,8 +1417,8 @@ impl<'help, 'cmd> Parser<'help, 'cmd> {
debug!("Parser::add_env: Found a flag with value `{:?}`", val); debug!("Parser::add_env: Found a flag with value `{:?}`", val);
let predicate = str_to_bool(val.to_str_lossy()); let predicate = str_to_bool(val.to_str_lossy());
debug!("Parser::add_env: Found boolean literal `{}`", predicate); debug!("Parser::add_env: Found boolean literal `{:?}`", predicate);
if predicate { if predicate.unwrap_or(true) {
matcher.add_index_to(&a.id, self.cur_idx.get(), ValueSource::EnvVariable); matcher.add_index_to(&a.id, self.cur_idx.get(), ValueSource::EnvVariable);
} }
} }

View file

@ -1,5 +1,5 @@
/// True values are `y`, `yes`, `t`, `true`, `on`, and `1`. /// True values are `y`, `yes`, `t`, `true`, `on`, and `1`.
// pub(crate) const TRUE_LITERALS: [&str; 6] = ["y", "yes", "t", "true", "on", "1"]; const TRUE_LITERALS: [&str; 6] = ["y", "yes", "t", "true", "on", "1"];
/// False values are `n`, `no`, `f`, `false`, `off`, and `0`. /// False values are `n`, `no`, `f`, `false`, `off`, and `0`.
const FALSE_LITERALS: [&str; 6] = ["n", "no", "f", "false", "off", "0"]; const FALSE_LITERALS: [&str; 6] = ["n", "no", "f", "false", "off", "0"];
@ -9,7 +9,13 @@ const FALSE_LITERALS: [&str; 6] = ["n", "no", "f", "false", "off", "0"];
/// `false` values are `n`, `no`, `f`, `false`, `off`, and `0` (case insensitive). /// `false` values are `n`, `no`, `f`, `false`, `off`, and `0` (case insensitive).
/// ///
/// Any other value will be considered as `true`. /// Any other value will be considered as `true`.
pub(crate) fn str_to_bool(val: impl AsRef<str>) -> bool { pub(crate) fn str_to_bool(val: impl AsRef<str>) -> Option<bool> {
let pat: &str = &val.as_ref().to_lowercase(); let pat: &str = &val.as_ref().to_lowercase();
!FALSE_LITERALS.contains(&pat) if TRUE_LITERALS.contains(&pat) {
Some(true)
} else if FALSE_LITERALS.contains(&pat) {
Some(false)
} else {
None
}
} }