env_reader/error.rs
1//! What can be wrong with a configuration, and how it reads.
2
3use std::fmt;
4
5/// One thing wrong with one variable.
6///
7/// Each variant names the variable, because the first thing anyone does
8/// with a configuration error is search the deployment for that name.
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub enum Error {
11 /// A required variable is unset or blank.
12 Missing {
13 /// The variable's name.
14 name: String,
15 },
16
17 /// A variable is set to something that is not the shape it must be.
18 Invalid {
19 /// The variable's name.
20 name: String,
21 /// What was expected, as a noun phrase: `a positive integer`.
22 expected: String,
23 /// What was there.
24 ///
25 /// Quoted in the message. Configuration values are operational
26 /// rather than sensitive — and the one kind that is not should be
27 /// read through [`crate::Secret`], which never reaches this type.
28 got: String,
29 },
30
31 /// Two or more variables are individually fine but cannot be combined.
32 Conflict {
33 /// The whole sentence, because a conflict is about a relationship
34 /// and there is no single name to lead with.
35 message: String,
36 },
37}
38
39impl Error {
40 /// A required variable is unset or blank.
41 ///
42 /// # Examples
43 ///
44 /// ```
45 /// use env_reader::Error;
46 ///
47 /// let error = Error::missing("DATABASE_URL");
48 /// assert_eq!(error.to_string(), "missing required configuration: DATABASE_URL");
49 /// ```
50 #[must_use]
51 pub fn missing(name: impl Into<String>) -> Self {
52 Self::Missing { name: name.into() }
53 }
54
55 /// A variable holds something of the wrong shape.
56 ///
57 /// # Examples
58 ///
59 /// ```
60 /// use env_reader::Error;
61 ///
62 /// let error = Error::invalid("PORT", "a whole number", "two");
63 /// assert_eq!(
64 /// error.to_string(),
65 /// r#"invalid configuration: PORT must be a whole number, got "two""#
66 /// );
67 /// ```
68 #[must_use]
69 pub fn invalid(
70 name: impl Into<String>,
71 expected: impl Into<String>,
72 got: impl Into<String>,
73 ) -> Self {
74 Self::Invalid {
75 name: name.into(),
76 expected: expected.into(),
77 got: got.into(),
78 }
79 }
80
81 /// Variables that cannot be combined as configured.
82 ///
83 /// # Examples
84 ///
85 /// ```
86 /// use env_reader::Error;
87 ///
88 /// let error = Error::conflict("Cannot specify both QUEUE_NAME and TOPIC_NAME.");
89 /// assert!(error.to_string().starts_with("Cannot specify both"));
90 /// ```
91 #[must_use]
92 pub fn conflict(message: impl Into<String>) -> Self {
93 Self::Conflict {
94 message: message.into(),
95 }
96 }
97
98 /// The variable this is about, when it is about one.
99 ///
100 /// [`Error::Conflict`] concerns a relationship between variables and so
101 /// names none.
102 ///
103 /// # Examples
104 ///
105 /// ```
106 /// use env_reader::Error;
107 ///
108 /// assert_eq!(Error::missing("PORT").name(), Some("PORT"));
109 /// assert_eq!(Error::conflict("either, not both").name(), None);
110 /// ```
111 #[must_use]
112 pub fn name(&self) -> Option<&str> {
113 match self {
114 Self::Missing { name } | Self::Invalid { name, .. } => Some(name),
115 Self::Conflict { .. } => None,
116 }
117 }
118}
119
120impl fmt::Display for Error {
121 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
122 match self {
123 Self::Missing { name } => {
124 write!(formatter, "missing required configuration: {name}")
125 }
126 Self::Invalid {
127 name,
128 expected,
129 got,
130 } => write!(
131 formatter,
132 "invalid configuration: {name} must be {expected}, got {got:?}"
133 ),
134 Self::Conflict { message } => formatter.write_str(message),
135 }
136 }
137}
138
139impl std::error::Error for Error {}
140
141/// Every problem found while reading a configuration.
142///
143/// Constructed by [`crate::Reader::finish`]. It is never empty: a reader
144/// with no problems returns `Ok` instead.
145///
146/// It renders one problem per line, so a process's last words are the whole
147/// list rather than the first item of it.
148///
149/// # Examples
150///
151/// ```
152/// use env_reader::Reader;
153///
154/// let mut reader = Reader::from_pairs([("PORT", "two")]);
155/// let _: String = reader.required_string("SERVICE_NAME");
156/// let _: u16 = reader.integer_or("PORT", 8080);
157///
158/// let errors = reader.finish().unwrap_err();
159/// assert_eq!(errors.len(), 2);
160/// assert_eq!(
161/// errors.to_string(),
162/// "missing required configuration: SERVICE_NAME\n\
163/// invalid configuration: PORT must be a whole number, got \"two\""
164/// );
165/// ```
166#[derive(Debug, Clone, PartialEq, Eq)]
167pub struct Errors(Vec<Error>);
168
169impl Errors {
170 /// Wrap a non-empty list of problems.
171 ///
172 /// # Panics
173 ///
174 /// Panics if `errors` is empty. An empty error is not a thing this type
175 /// can represent, and a caller that has none should be returning `Ok`.
176 #[must_use]
177 pub fn new(errors: Vec<Error>) -> Self {
178 assert!(!errors.is_empty(), "Errors must hold at least one problem");
179 Self(errors)
180 }
181
182 /// How many problems there are.
183 ///
184 /// # Examples
185 ///
186 /// ```
187 /// use env_reader::{Error, Errors};
188 ///
189 /// let errors = Errors::new(vec![Error::missing("PORT")]);
190 /// assert_eq!(errors.len(), 1);
191 /// assert!(!errors.is_empty());
192 /// ```
193 #[must_use]
194 pub fn len(&self) -> usize {
195 self.0.len()
196 }
197
198 /// Always false; see [`Errors::new`].
199 ///
200 /// Present because clippy asks for it beside [`Errors::len`], and
201 /// because a caller writing `if errors.is_empty()` deserves an answer
202 /// rather than a compile error.
203 #[must_use]
204 pub fn is_empty(&self) -> bool {
205 self.0.is_empty()
206 }
207
208 /// The problems, in the order they were found.
209 ///
210 /// # Examples
211 ///
212 /// ```
213 /// use env_reader::{Error, Errors};
214 ///
215 /// let errors = Errors::new(vec![Error::missing("A"), Error::missing("B")]);
216 /// let names: Vec<_> = errors.iter().filter_map(Error::name).collect();
217 /// assert_eq!(names, ["A", "B"]);
218 /// ```
219 pub fn iter(&self) -> std::slice::Iter<'_, Error> {
220 self.0.iter()
221 }
222
223 /// The problems, consuming this.
224 #[must_use]
225 pub fn into_inner(self) -> Vec<Error> {
226 self.0
227 }
228}
229
230impl fmt::Display for Errors {
231 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
232 let mut first = true;
233 for error in &self.0 {
234 if !first {
235 writeln!(formatter)?;
236 }
237 write!(formatter, "{error}")?;
238 first = false;
239 }
240 Ok(())
241 }
242}
243
244impl std::error::Error for Errors {}
245
246impl<'a> IntoIterator for &'a Errors {
247 type Item = &'a Error;
248 type IntoIter = std::slice::Iter<'a, Error>;
249
250 fn into_iter(self) -> Self::IntoIter {
251 self.0.iter()
252 }
253}
254
255impl IntoIterator for Errors {
256 type Item = Error;
257 type IntoIter = std::vec::IntoIter<Error>;
258
259 fn into_iter(self) -> Self::IntoIter {
260 self.0.into_iter()
261 }
262}
263
264#[cfg(test)]
265mod tests {
266 use super::*;
267
268 #[test]
269 fn a_missing_variable_names_itself() {
270 assert_eq!(
271 Error::missing("DATABASE_URL").to_string(),
272 "missing required configuration: DATABASE_URL"
273 );
274 }
275
276 #[test]
277 fn an_invalid_value_is_quoted_so_whitespace_is_visible() {
278 // `got: "2576 "` and `got: "2576"` are different diagnoses, and the
279 // quoting is the only thing that shows which one happened.
280 assert_eq!(
281 Error::invalid("PORT", "a whole number", "2576 ").to_string(),
282 r#"invalid configuration: PORT must be a whole number, got "2576 ""#
283 );
284 }
285
286 #[test]
287 fn problems_render_one_per_line() {
288 let errors = Errors::new(vec![
289 Error::missing("A"),
290 Error::invalid("B", "a whole number", "x"),
291 ]);
292 let text = errors.to_string();
293 assert_eq!(text.lines().count(), 2);
294 assert!(text.starts_with("missing required configuration: A\n"));
295 }
296
297 #[test]
298 fn a_conflict_names_no_single_variable() {
299 assert_eq!(Error::conflict("either, not both").name(), None);
300 assert_eq!(Error::missing("A").name(), Some("A"));
301 assert_eq!(Error::invalid("B", "x", "y").name(), Some("B"));
302 }
303
304 #[test]
305 #[should_panic(expected = "at least one problem")]
306 fn an_empty_error_list_is_not_representable() {
307 let _ = Errors::new(Vec::new());
308 }
309}