1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! Error values produces when extracting configurations.

use std::fmt::{self, Display};
use std::borrow::Cow;

use serde::{ser, de};

use crate::{Figment, Profile, Metadata, value::Tag};

/// A simple alias to `Result` with an error type of [`Error`].
pub type Result<T> = std::result::Result<T, Error>;

/// An error that occured while producing data or extracting a configuration.
///
/// # Constructing Errors
///
/// An `Error` will generally be constructed indirectly via its implementations
/// of serde's [`de::Error`] and [`ser::Error`], that is, as a result of
/// serialization or deserialization errors. When implementing [`Provider`],
/// however, it may be necessary to construct an `Error` directly.
///
/// [`Provider`]: crate::Provider
///
/// Broadly, there are two ways to construct an `Error`:
///
///   * Via an error message, since `Error` impls `From<String>`:
///
///     ```
///     use figment::Error;
///
///     Error::from("whoops, something went wrong!".to_string());
///     ```
///
///   * Via a [`Kind`], since `Error` impls `From<Kind>`:
///
///     ```
///     use figment::{error::{Error, Kind}, value::Value};
///
///     let value = Value::serialize(&100).unwrap();
///     if !value.as_str().is_some() {
///         let kind = Kind::InvalidType(value.to_actual(), "string".into());
///         let error = Error::from(kind);
///     }
///     ```
///
/// As always, `?` can be used to automatically convert into an `Error` using
/// the available `From` implementations:
///
/// ```
/// use std::fs::File;
///
/// fn try_read() -> Result<(), figment::Error> {
///     let x = File::open("/tmp/foo.boo").map_err(|e| e.to_string())?;
///     Ok(())
/// }
/// ```
///
/// # Display
///
/// By default, `Error` uses all of the available information about the error,
/// including the `Metadata`, `path`, and `profile` to display a message that
/// resembles the following, where `$` is `error.` for some `error: Error`:
///
/// ```text
/// $kind: `$metadata.interpolate($path)` in $($metadata.sources())*
/// ```
///
/// Concretely, such an error may look like:
///
/// ```text
/// invalid type: found sequence, expected u16: `staging.port` in TOML file Config.toml
/// ```
///
/// # Iterator
///
/// An `Error` may contain more than one error. To process all errors, iterate
/// over an `Error`:
///
/// ```rust
/// fn with_error(error: figment::Error) {
///     for error in error {
///         println!("error: {}", error);
///     }
/// }
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct Error {
    /// The tag of the value that errored. We use this to lookup the `metadata`.
    tag: Tag,
    /// The profile that was selected when the error occured, if any.
    pub profile: Option<Profile>,
    /// The metadata for the provider of the value that errored, if known.
    pub metadata: Option<Metadata>,
    /// The path to the configuration key that errored, if known.
    pub path: Vec<String>,
    /// The error kind.
    pub kind: Kind,
    prev: Option<Box<Error>>,
}

/// An error kind, encapsulating serde's [`serde::de::Error`].
#[derive(Clone, Debug, PartialEq)]
pub enum Kind {
    /// A custom error message.
    Message(String),

    /// An invalid type: (actual, expected). See
    /// [`serde::de::Error::invalid_type()`].
    InvalidType(Actual, String),
    /// An invalid value: (actual, expected). See
    /// [`serde::de::Error::invalid_value()`].
    InvalidValue(Actual, String),
    /// Too many or too few items: (actual, expected). See
    /// [`serde::de::Error::invalid_length()`].
    InvalidLength(usize, String),

    /// A variant with an unrecognized name: (actual, expected). See
    /// [`serde::de::Error::unknown_variant()`].
    UnknownVariant(String, &'static [&'static str]),
    /// A field with an unrecognized name: (actual, expected). See
    /// [`serde::de::Error::unknown_field()`].
    UnknownField(String, &'static [&'static str]),
    /// A field was missing: (name). See [`serde::de::Error::missing_field()`].
    MissingField(Cow<'static, str>),
    /// A field appeared more than once: (name). See
    /// [`serde::de::Error::duplicate_field()`].
    DuplicateField(&'static str),

    /// The `isize` was not in range of any known sized signed integer.
    ISizeOutOfRange(isize),
    /// The `usize` was not in range of any known sized unsigned integer.
    USizeOutOfRange(usize),

    /// The serializer or deserializer does not support the `Actual` type.
    Unsupported(Actual),

    /// The type `.0` cannot be used for keys, need a `.1`.
    UnsupportedKey(Actual, Cow<'static, str>),
}

impl Error {
    pub(crate) fn prefixed(mut self, path: &str) -> Self {
        self.path.insert(0, path.into());
        self
    }

    pub(crate) fn chain(self, mut error: Error) -> Self {
        error.prev = Some(Box::new(self));
        error
    }

    pub(crate) fn retagged(mut self, tag: Tag) -> Self {
        if self.tag.is_default() {
            self.tag = tag;
        }

        self
    }

    pub(crate) fn resolved(mut self, config: &Figment) -> Self {
        let mut error = Some(&mut self);
        while let Some(e) = error {
            e.metadata = config.get_metadata(e.tag).cloned();
            e.profile = e.tag.profile()
                .or_else(|| Some(config.profile().clone()));

            error = e.prev.as_deref_mut();
        }

        self
    }
}

impl Error {
    /// Returns `true` if the error's kind is `MissingField`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use figment::error::{Error, Kind};
    ///
    /// let error = Error::from(Kind::MissingField("path".into()));
    /// assert!(error.missing());
    /// ```
    pub fn missing(&self) -> bool {
        matches!(self.kind, Kind::MissingField(..))
    }

    /// Append the string `path` to the error's path.
    ///
    /// # Example
    ///
    /// ```rust
    /// use figment::Error;
    ///
    /// let error = Error::from("an error message".to_string())
    ///     .with_path("some_path");
    /// ```
    pub fn with_path(mut self, path: &str) -> Self {
        self.path.push(path.into());
        self
    }

    /// Returns the number of errors represented by `self`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use figment::{Figment, providers::{Format, Toml}};
    ///
    /// figment::Jail::expect_with(|jail| {
    ///     jail.create_file("Base.toml", r#"
    ///         # oh no, an unclosed array!
    ///         cat = [1
    ///     "#)?;
    ///
    ///     jail.create_file("Release.toml", r#"
    ///         # and now an unclosed string!?
    ///         cat = "
    ///     "#)?;
    ///
    ///     let figment = Figment::from(Toml::file("Base.toml"))
    ///         .merge(Toml::file("Release.toml"));
    ///
    ///     let error = figment.extract_inner::<String>("cat").unwrap_err();
    ///     assert_eq!(error.count(), 2);
    ///
    ///     Ok(())
    /// });
    /// ```
    pub fn count(&self) -> usize {
        1 + self.prev.as_ref().map_or(0, |e| e.count())
    }
}

/// An iterator over all errors in an [`Error`].
pub struct IntoIter(Option<Error>);

impl Iterator for IntoIter {
    type Item = Error;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(mut error) = self.0.take() {
            self.0 = error.prev.take().map(|e| *e);
            Some(error)
        } else {
            None
        }
    }
}

impl IntoIterator for Error {
    type Item = Error;
    type IntoIter = IntoIter;

    fn into_iter(self) -> Self::IntoIter {
        IntoIter(Some(self))
    }
}

/// A type that enumerates all of serde's types, used to indicate that a value
/// of the given type was received.
#[allow(missing_docs)]
#[derive(Clone, Debug, PartialEq)]
pub enum Actual {
    Bool(bool),
    Unsigned(u128),
    Signed(i128),
    Float(f64),
    Char(char),
    Str(String),
    Bytes(Vec<u8>),
    Unit,
    Option,
    NewtypeStruct,
    Seq,
    Map,
    Enum,
    UnitVariant,
    NewtypeVariant,
    TupleVariant,
    StructVariant,
    Other(String),
}

impl fmt::Display for Actual {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Actual::Bool(v) => write!(f, "bool {}", v),
            Actual::Unsigned(v) => write!(f, "unsigned int `{}`", v),
            Actual::Signed(v) => write!(f, "signed int `{}`", v),
            Actual::Float(v) => write!(f, "float `{}`", v),
            Actual::Char(v) => write!(f, "char {:?}", v),
            Actual::Str(v) => write!(f, "string {:?}", v),
            Actual::Bytes(v) => write!(f, "bytes {:?}", v),
            Actual::Unit => write!(f, "unit"),
            Actual::Option => write!(f, "option"),
            Actual::NewtypeStruct => write!(f, "new-type struct"),
            Actual::Seq => write!(f, "sequence"),
            Actual::Map => write!(f, "map"),
            Actual::Enum => write!(f, "enum"),
            Actual::UnitVariant => write!(f, "unit variant"),
            Actual::NewtypeVariant => write!(f, "new-type variant"),
            Actual::TupleVariant => write!(f, "tuple variant"),
            Actual::StructVariant => write!(f, "struct variant"),
            Actual::Other(v) => v.fmt(f),
        }
    }
}

impl From<de::Unexpected<'_>> for Actual {
    fn from(value: de::Unexpected<'_>) -> Actual {
        match value {
            de::Unexpected::Bool(v) => Actual::Bool(v),
            de::Unexpected::Unsigned(v) => Actual::Unsigned(v as u128),
            de::Unexpected::Signed(v) => Actual::Signed(v as i128),
            de::Unexpected::Float(v) => Actual::Float(v),
            de::Unexpected::Char(v) => Actual::Char(v),
            de::Unexpected::Str(v) => Actual::Str(v.into()),
            de::Unexpected::Bytes(v) => Actual::Bytes(v.into()),
            de::Unexpected::Unit => Actual::Unit,
            de::Unexpected::Option => Actual::Option,
            de::Unexpected::NewtypeStruct => Actual::NewtypeStruct,
            de::Unexpected::Seq => Actual::Seq,
            de::Unexpected::Map => Actual::Map,
            de::Unexpected::Enum => Actual::Enum,
            de::Unexpected::UnitVariant => Actual::UnitVariant,
            de::Unexpected::NewtypeVariant => Actual::NewtypeVariant,
            de::Unexpected::TupleVariant => Actual::TupleVariant,
            de::Unexpected::StructVariant => Actual::StructVariant,
            de::Unexpected::Other(v) => Actual::Other(v.into())
        }
    }
}

impl de::Error for Error {
    fn custom<T: Display>(msg: T) -> Self {
        Kind::Message(msg.to_string()).into()
    }

    fn invalid_type(unexp: de::Unexpected, exp: &dyn de::Expected) -> Self {
        Kind::InvalidType(unexp.into(), exp.to_string()).into()
    }

    fn invalid_value(unexp: de::Unexpected, exp: &dyn de::Expected) -> Self {
        Kind::InvalidValue(unexp.into(), exp.to_string()).into()
    }

    fn invalid_length(len: usize, exp: &dyn de::Expected) -> Self {
        Kind::InvalidLength(len, exp.to_string()).into()
    }

    fn unknown_variant(variant: &str, expected: &'static [&'static str]) -> Self {
        Kind::UnknownVariant(variant.into(), expected).into()
    }

    fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self {
        Kind::UnknownField(field.into(), expected).into()
    }

    fn missing_field(field: &'static str) -> Self {
        Kind::MissingField(field.into()).into()
    }

    fn duplicate_field(field: &'static str) -> Self {
        Kind::DuplicateField(field).into()
    }
}

impl ser::Error for Error {
    fn custom<T: Display>(msg: T) -> Self {
        Kind::Message(msg.to_string()).into()
    }
}

impl From<Kind> for Error {
    fn from(kind: Kind) -> Error {
        Error {
            tag: Tag::Default,
            path: vec![],
            profile: None,
            metadata: None,
            prev: None,
            kind,
        }
    }
}

impl From<String> for Error {
    fn from(string: String) -> Error {
        Kind::Message(string).into()
    }
}

impl Display for Kind {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Kind::Message(msg) => f.write_str(&msg),
            Kind::InvalidType(v, exp) => {
                write!(f, "invalid type: found {}, expected {}", v, exp)
            }
            Kind::InvalidValue(v, exp) => {
                write!(f, "invalid value {}, expected {}", v, exp)
            },
            Kind::InvalidLength(v, exp) => {
                write!(f, "invalid length {}, expected {}", v, exp)
            },
            Kind::UnknownVariant(v, exp) => {
                write!(f, "unknown variant: found `{}`, expected `{}`", v, OneOf(exp))
            }
            Kind::UnknownField(v, exp) => {
                write!(f, "unknown field: found `{}`, expected `{}`", v, OneOf(exp))
            }
            Kind::MissingField(v) => {
                write!(f, "missing field `{}`", v)
            }
            Kind::DuplicateField(v) => {
                write!(f, "duplicate field `{}`", v)
            }
            Kind::ISizeOutOfRange(v) => {
                write!(f, "signed integer `{}` is out of range", v)
            }
            Kind::USizeOutOfRange(v) => {
                write!(f, "unsigned integer `{}` is out of range", v)
            }
            Kind::Unsupported(v) => {
                write!(f, "unsupported type `{}`", v)
            }
            Kind::UnsupportedKey(a, e) => {
                write!(f, "unsupported type `{}` for key: must be `{}`", a, e)
            }
        }
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.kind.fmt(f)?;

        if let (Some(profile), Some(md)) = (&self.profile, &self.metadata) {
            if !self.path.is_empty() {
                let key = md.interpolate(profile, &self.path);
                write!(f, " for key {:?}", key)?;
            }
        }

        if let Some(md) = &self.metadata {
            if let Some(source) = &md.source {
                write!(f, " in {} {}", source, md.name)?;
            } else {
                write!(f, " in {}", md.name)?;
            }
        }

        if let Some(prev) = &self.prev {
            write!(f, "\n{}", prev)?;
        }

        Ok(())
    }
}

impl std::error::Error for Error {}

/// A structure that implements [`de::Expected`] signaling that one of the types
/// in the slice was expected.
pub struct OneOf(pub &'static [&'static str]);

impl fmt::Display for OneOf {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.0.len() {
            0 => write!(f, "none"),
            1 => write!(f, "`{}`", self.0[0]),
            2 => write!(f, "`{}` or `{}`", self.0[0], self.0[1]),
            _ => {
                write!(f, "one of ")?;
                for (i, alt) in self.0.iter().enumerate() {
                    if i > 0 { write!(f, ", ")?; }
                    write!(f, "`{}`", alt)?;
                }

                Ok(())
            }
        }
    }
}

impl de::Expected for OneOf {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Display::fmt(self, f)
    }
}