env_reader/value.rs
1//! Turning a raw variable value into something typed.
2//!
3//! These are free functions taking values rather than variable names, so
4//! they are testable without touching the process environment.
5//! [`crate::Reader`] is what pairs them with a name.
6
7/// A value if it is present, `None` if it is absent or blank.
8///
9/// **Blank is absent**, and every other reader in this crate goes through
10/// this function. Leading and trailing whitespace is stripped; what is
11/// left, if anything, is the value.
12///
13/// A templated deployment whose source was empty produces `PORT=` routinely
14/// — an `.env` line with nothing after the `=`, a substituted variable that
15/// resolved to nothing — and treating that as "configured, to the empty
16/// string" produces failures a long way from their cause.
17///
18/// # Examples
19///
20/// ```
21/// use env_reader::present;
22///
23/// assert_eq!(present(Some("orders")), Some("orders"));
24/// assert_eq!(present(Some(" 8080 ")), Some("8080"));
25/// assert_eq!(present(Some(" ")), None);
26/// assert_eq!(present(Some("")), None);
27/// assert_eq!(present(None), None);
28/// ```
29#[must_use]
30pub fn present(raw: Option<&str>) -> Option<&str> {
31 raw.map(str::trim).filter(|value| !value.is_empty())
32}
33
34/// The spellings [`parse_bool`] accepts as true.
35pub const TRUE_SPELLINGS: [&str; 4] = ["true", "1", "yes", "on"];
36
37/// The spellings [`parse_bool`] accepts as false.
38pub const FALSE_SPELLINGS: [&str; 4] = ["false", "0", "no", "off"];
39
40/// Read a value as a boolean, strictly.
41///
42/// [`TRUE_SPELLINGS`] and [`FALSE_SPELLINGS`], in any case, after trimming.
43/// Anything else — including an absent or blank value — is `None`, so the
44/// caller decides between a default and an error rather than this function
45/// guessing.
46///
47/// # Why strict is the default here
48///
49/// The tempting alternative is "anything not false-ish is true", and it is
50/// a trap: `ENABLED=disabled`, `ENABLED=nope` and `ENABLED=flase` all come
51/// out true, and the deployment that wrote them looks configured. See
52/// [`parse_bool_lenient`] for when you nonetheless need that behaviour.
53///
54/// # Examples
55///
56/// ```
57/// use env_reader::parse_bool;
58///
59/// assert_eq!(parse_bool(Some("false")), Some(false));
60/// assert_eq!(parse_bool(Some("OFF")), Some(false));
61/// assert_eq!(parse_bool(Some(" Yes ")), Some(true));
62/// // Unrecognised is not silently true.
63/// assert_eq!(parse_bool(Some("disabled")), None);
64/// assert_eq!(parse_bool(Some(" ")), None);
65/// ```
66#[must_use]
67pub fn parse_bool(raw: Option<&str>) -> Option<bool> {
68 let value = present(raw)?.to_ascii_lowercase();
69
70 if TRUE_SPELLINGS.contains(&value.as_str()) {
71 Some(true)
72 } else if FALSE_SPELLINGS.contains(&value.as_str()) {
73 Some(false)
74 } else {
75 None
76 }
77}
78
79/// Read a value as a boolean, leniently: anything not false-ish is true.
80///
81/// [`FALSE_SPELLINGS`] are false; **any other non-blank value is true**.
82/// Deliberately lopsided, and not what [`parse_bool`] does.
83///
84/// This exists because deployments exist. A variable that has been set to
85/// `disabled` or `enabled` or `y` for years is a value some running system
86/// depends on, and a stricter reader would turn a working deployment into a
87/// failing one at the worst possible moment. Reach for this when adopting
88/// an existing estate, not when designing a new variable.
89///
90/// # Examples
91///
92/// ```
93/// use env_reader::parse_bool_lenient;
94///
95/// assert_eq!(parse_bool_lenient(Some("false")), Some(false));
96/// assert_eq!(parse_bool_lenient(Some("0")), Some(false));
97/// assert_eq!(parse_bool_lenient(Some("true")), Some(true));
98/// // The lopsided part.
99/// assert_eq!(parse_bool_lenient(Some("disabled")), Some(true));
100/// assert_eq!(parse_bool_lenient(Some(" ")), None);
101/// ```
102#[must_use]
103pub fn parse_bool_lenient(raw: Option<&str>) -> Option<bool> {
104 present(raw).map(|value| !FALSE_SPELLINGS.contains(&value.to_ascii_lowercase().as_str()))
105}
106
107/// Split a comma-separated value into its non-empty, trimmed elements.
108///
109/// An absent, blank, or all-separators value yields an empty vector;
110/// whether that is acceptable is the caller's decision.
111///
112/// # Examples
113///
114/// ```
115/// use env_reader::parse_csv;
116///
117/// assert_eq!(parse_csv(Some("245,212, 192 ,224")), ["245", "212", "192", "224"]);
118/// // Empty elements are dropped, not preserved as empty strings.
119/// assert_eq!(parse_csv(Some("a,,b,")), ["a", "b"]);
120/// assert!(parse_csv(Some(" , , ")).is_empty());
121/// assert!(parse_csv(None).is_empty());
122/// ```
123#[must_use]
124pub fn parse_csv(raw: Option<&str>) -> Vec<String> {
125 parse_separated(raw, ',')
126}
127
128/// [`parse_csv`], with a separator of your choosing.
129///
130/// For a `PATH`-shaped variable, or any list whose elements can contain a
131/// comma.
132///
133/// # Examples
134///
135/// ```
136/// use env_reader::parse_separated;
137///
138/// assert_eq!(parse_separated(Some("/usr/bin:/bin"), ':'), ["/usr/bin", "/bin"]);
139/// assert_eq!(parse_separated(Some("a b c"), ' '), ["a", "b", "c"]);
140/// ```
141#[must_use]
142pub fn parse_separated(raw: Option<&str>, separator: char) -> Vec<String> {
143 present(raw)
144 .map(|value| {
145 value
146 .split(separator)
147 .map(str::trim)
148 .filter(|element| !element.is_empty())
149 .map(str::to_string)
150 .collect()
151 })
152 .unwrap_or_default()
153}
154
155#[cfg(test)]
156mod tests {
157 use super::*;
158
159 #[test]
160 fn blank_is_the_same_as_absent() {
161 assert_eq!(present(Some("")), None);
162 assert_eq!(present(Some(" \t\n")), None);
163 assert_eq!(present(None), None);
164 }
165
166 #[test]
167 fn values_are_trimmed() {
168 assert_eq!(present(Some("\t orders \n")), Some("orders"));
169 }
170
171 #[test]
172 fn the_strict_reader_accepts_four_spellings_each_way() {
173 for text in ["true", "TRUE", "True", "1", "yes", "YES", "on", "ON"] {
174 assert_eq!(parse_bool(Some(text)), Some(true), "{text}");
175 }
176 for text in ["false", "FALSE", "False", "0", "no", "NO", "off", "OFF"] {
177 assert_eq!(parse_bool(Some(text)), Some(false), "{text}");
178 }
179 }
180
181 #[test]
182 fn the_strict_reader_refuses_to_guess() {
183 // The trap the lenient reader falls into, stated as a test.
184 for text in ["disabled", "enabled", "nope", "flase", "y", "n", "2"] {
185 assert_eq!(parse_bool(Some(text)), None, "{text}");
186 }
187 }
188
189 #[test]
190 fn the_lenient_reader_is_lopsided_on_purpose() {
191 for text in ["false", "FALSE", "0", "no", "off"] {
192 assert_eq!(parse_bool_lenient(Some(text)), Some(false), "{text}");
193 }
194 for text in ["true", "1", "yes", "on", "disabled", "nope", "flase"] {
195 assert_eq!(parse_bool_lenient(Some(text)), Some(true), "{text}");
196 }
197 }
198
199 #[test]
200 fn a_blank_boolean_has_no_opinion_either_way() {
201 // The caller supplies the default.
202 assert_eq!(parse_bool(Some(" ")), None);
203 assert_eq!(parse_bool(None), None);
204 assert_eq!(parse_bool_lenient(Some(" ")), None);
205 assert_eq!(parse_bool_lenient(None), None);
206 }
207
208 #[test]
209 fn a_list_drops_empty_elements() {
210 assert_eq!(parse_csv(Some("ADT_A05, ,ADT_A39,")), ["ADT_A05", "ADT_A39"]);
211 }
212
213 #[test]
214 fn a_list_of_nothing_is_empty_not_one_empty_element() {
215 // The trap `"".split(',')` sets: it yields one empty string.
216 assert!(parse_csv(Some("")).is_empty());
217 assert!(parse_csv(Some(",")).is_empty());
218 assert!(parse_csv(None).is_empty());
219 }
220
221 #[test]
222 fn a_list_can_use_another_separator() {
223 assert_eq!(parse_separated(Some("/usr/bin:/bin:"), ':'), ["/usr/bin", "/bin"]);
224 }
225}