use std::fmt;
#[derive(Clone, PartialEq, Eq)]
pub struct Secret(String);
impl Secret {
pub fn expose(&self) -> &str {
&self.0
}
}
impl fmt::Debug for Secret {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Secret(<redacted>)")
}
}
pub(crate) fn secret_value(value: Option<&str>) -> Option<Secret> {
if cfg!(feature = "secrets") {
value.map(|v| Secret(crate::unquote(v).to_string()))
} else {
None
}
}
#[cfg(test)]
pub(crate) fn expected(value: &str) -> Option<&str> {
cfg!(feature = "secrets").then_some(value)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn debug_hides_the_value() {
let secret = Secret("$9$abc".to_string());
assert_eq!(format!("{secret:?}"), "Secret(<redacted>)");
assert_eq!(secret.expose(), "$9$abc");
}
#[cfg(feature = "secrets")]
#[test]
fn reads_and_unquotes_with_the_feature() {
assert_eq!(secret_value(Some("\"$9$abc\"")).unwrap().expose(), "$9$abc");
assert_eq!(secret_value(None), None);
}
#[cfg(not(feature = "secrets"))]
#[test]
fn reads_nothing_without_the_feature() {
assert_eq!(secret_value(Some("$9$abc")), None);
}
}