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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
use std::panic::Location;

use serde::de::Deserialize;

use crate::{Profile, Provider, Metadata};
use crate::error::{Kind, Result};
use crate::value::{Value, Map, Dict, Tag, ConfiguredValueDe};
use crate::coalesce::{Coalescible, Order};

/// Combiner of [`Provider`]s for configuration value extraction.
///
/// # Overview
///
/// A `Figment` combines providers by merging or joining their provided data.
/// The combined value or a subset of the combined value can be extracted into
/// any type that implements [`Deserialize`]. Additionally, values can be nested
/// in _profiles_, and a profile can be selected via [`Figment::select()`] for
/// extraction; the profile to be extracted can be retrieved with
/// [`Figment::profile()`] and defaults to [`Profile::Default`]. The [top-level
/// docs](crate) contain a broad overview of these topics.
///
/// ## Merging vs. Joining
///
/// _Merging_ and _joining_ control whether duplicate values are replaced or
/// discarded. A _merged_ value replaces an existing value with the same key,
/// while a _joined_ value is discarded if a value with the same key exists:
///
/// ```rust
/// use figment::Figment;
///
/// let figment = Figment::from(("key", "original"));
///
/// let original: String = figment.extract_inner("key").unwrap();
/// assert_eq!(original, "original");
///
/// let figment = figment.merge(("key", "replaced"));
/// let replaced: String = figment.extract_inner("key").unwrap();
/// assert_eq!(replaced, "replaced");
///
/// let figment = figment.join(("key", "joined"));
/// let joined: String = figment.extract_inner("key").unwrap();
/// assert_eq!(joined, "replaced");
/// ```
///
/// ## Extraction
///
/// The configuration or a subset thereof can be extracted from a `Figment` in
/// one of several ways:
///
///   * [`Figment::extract()`], which extracts the complete value into any `T:
///     Deserialize`.
///   * [`Figment::extract_inner()`], which extracts a subset of the value for a
///     given key path.
///   * [`Figment::find_value()`], which returns the raw, serialized [`Value`]
///     for a given key path.
///
/// A "key path" is a string of the form `a.b.c` (e.g, `item`, `item.fruits`,
/// etc.) where each component delimited by a `.` is a key for the dictionary of
/// the preceding key in the path, or the root dictionary if it is the first key
/// in the path. See [`Value::find()`] for examples.
///
/// ## Metadata
///
/// Every value collected by a `Figment` is accompanied by the metadata produced
/// by the value's provider. Additionally, [`Metadata::provide_location`] is set
/// by `from`, `merge` and `join` to the caller's location. `Metadata` can be
/// retrieved in one of several ways:
///
///   * [`Figment::metadata()`], which returns an iterator over all of the
///     metadata for all values.
///   * [`Figment::find_metadata()`], which returns the metadata for a value at
///     a given key path.
///   * [`Figment::get_metadata()`], which returns the metadata for a given
///     [`Tag`], itself retrieved via [`Tagged`] or [`Value::tag()`].
///
/// [`Tagged`]: crate::value::magic::Tagged
#[derive(Clone, Debug)]
pub struct Figment {
    pub(crate) profile: Profile,
    pub(crate) metadata: Map<Tag, Metadata>,
    pub(crate) value: Result<Map<Profile, Dict>>,
}

impl Figment {
    /// Creates a new `Figment` with the default profile selected and no
    /// providers.
    ///
    /// ```rust
    /// use figment::Figment;
    ///
    /// let figment = Figment::new();
    /// # assert_eq!(figment.profile(), "default");
    /// assert_eq!(figment.metadata().count(), 0);
    /// ```
    pub fn new() -> Self {
        Figment {
            metadata: Map::new(),
            profile: Profile::Default,
            value: Ok(Map::new()),
        }
    }

    /// Creates a new `Figment` with the default profile selected and an initial
    /// `provider`.
    ///
    /// ```rust
    /// use figment::Figment;
    /// use figment::providers::Env;
    ///
    /// let figment = Figment::from(Env::raw());
    /// # assert_eq!(figment.profile(), "default");
    /// assert_eq!(figment.metadata().count(), 1);
    /// ```
    #[track_caller]
    pub fn from<T: Provider>(provider: T) -> Self {
        Figment::new().merge(provider)
    }

    #[track_caller]
    fn provide<T: Provider>(mut self, provider: T, order: Order) -> Self {
        if let Some(map) = provider.__metadata_map() {
            self.metadata.extend(map);
        }

        if let Some(profile) = provider.profile() {
            self.profile = self.profile.coalesce(profile, order);
        }

        let mut metadata = provider.metadata();
        metadata.provide_location = Some(Location::caller());

        let tag = Tag::next();
        self.metadata.insert(tag, metadata);
        self.value = match (provider.data(), self.value) {
            (Ok(_), e@Err(_)) => e,
            (Err(e), Ok(_)) => Err(e.retagged(tag)),
            (Err(e), Err(prev)) => Err(e.retagged(tag).chain(prev)),
            (Ok(mut new), Ok(old)) => {
                new.iter_mut()
                    .map(|(p, map)| std::iter::repeat(p).zip(map.values_mut()))
                    .flatten()
                    .for_each(|(p, v)| v.map_tag(|t| *t = tag.for_profile(p)));

                Ok(old.coalesce(new, order))
            }
        };

        self
    }

    /// Joins `provider` into the current figment. See [merging vs.
    /// joining](#merging-vs-joining) for details.
    ///
    /// ```rust
    /// use figment::Figment;
    /// use figment::providers::Env;
    ///
    /// let figment = Figment::new().join(Env::raw());
    /// assert_eq!(figment.metadata().count(), 1);
    /// ```
    #[track_caller]
    pub fn join<T: Provider>(self, provider: T) -> Self {
        self.provide(provider, Order::Join)
    }

    /// Merges `provider` into the current figment. See [merging vs.
    /// joining](#merging-vs-joining) for details.
    ///
    /// ```rust
    /// use figment::Figment;
    /// use figment::providers::Env;
    ///
    /// let figment = Figment::new().merge(Env::raw());
    /// assert_eq!(figment.metadata().count(), 1);
    /// ```
    #[track_caller]
    pub fn merge<T: Provider>(self, provider: T) -> Self {
        self.provide(provider, Order::Merge)
    }

    /// Sets the profile to extract from to `profile`.
    ///
    /// # Example
    ///
    /// ```
    /// use figment::Figment;
    ///
    /// let figment = Figment::new().select("staging");
    /// assert_eq!(figment.profile(), "staging");
    /// ```
    pub fn select<P: Into<Profile>>(mut self, profile: P) -> Self {
        self.profile = profile.into();
        self
    }

    /// Merges the selected profile with the default and global profiles.
    fn merged(&self) -> Result<Value> {
        let mut map = self.value.clone().map_err(|e| e.resolved(self))?;
        let def = map.remove(&Profile::Default).unwrap_or_default();
        let global = map.remove(&Profile::Global).unwrap_or_default();

        let map = match map.remove(&self.profile) {
            Some(v) if self.profile.is_custom() => def.merge(v).merge(global),
            _ => def.merge(global)
        };

        Ok(Value::Dict(Tag::Default, map))
    }

    /// Returns a new `Figment` containing only the sub-dictionaries at `key`.
    ///
    /// This "sub-figment" is a _focusing_ of `self` with the property that:
    ///
    ///   * `self.find(key + ".sub")` <=> `focused.find("sub")`
    ///
    /// In other words, all values in `self` with a key starting with `key` are
    /// in `focused` _without_ the prefix and vice-versa.
    ///
    /// # Example
    ///
    /// ```rust
    /// use figment::{Figment, providers::{Format, Toml}};
    ///
    /// figment::Jail::expect_with(|jail| {
    ///     jail.create_file("Config.toml", r#"
    ///         cat = [1, 2, 3]
    ///         dog = [4, 5, 6]
    ///
    ///         [subtree]
    ///         cat = "meow"
    ///         dog = "woof!"
    ///
    ///         [subtree.bark]
    ///         dog = true
    ///         cat = false
    ///     "#)?;
    ///
    ///     let root = Figment::from(Toml::file("Config.toml"));
    ///     assert_eq!(root.extract_inner::<Vec<u8>>("cat").unwrap(), vec![1, 2, 3]);
    ///     assert_eq!(root.extract_inner::<Vec<u8>>("dog").unwrap(), vec![4, 5, 6]);
    ///     assert_eq!(root.extract_inner::<String>("subtree.cat").unwrap(), "meow");
    ///     assert_eq!(root.extract_inner::<String>("subtree.dog").unwrap(), "woof!");
    ///
    ///     let subtree = root.focus("subtree");
    ///     assert_eq!(subtree.extract_inner::<String>("cat").unwrap(), "meow");
    ///     assert_eq!(subtree.extract_inner::<String>("dog").unwrap(), "woof!");
    ///     assert_eq!(subtree.extract_inner::<bool>("bark.cat").unwrap(), false);
    ///     assert_eq!(subtree.extract_inner::<bool>("bark.dog").unwrap(), true);
    ///
    ///     let bark = subtree.focus("bark");
    ///     assert_eq!(bark.extract_inner::<bool>("cat").unwrap(), false);
    ///     assert_eq!(bark.extract_inner::<bool>("dog").unwrap(), true);
    ///
    ///     let not_a_dict = root.focus("cat");
    ///     assert!(not_a_dict.extract_inner::<bool>("cat").is_err());
    ///     assert!(not_a_dict.extract_inner::<bool>("dog").is_err());
    ///
    ///     Ok(())
    /// });
    /// ```
    pub fn focus(&self, key: &str) -> Self {
        fn try_focus(figment: &Figment, key: &str) -> Result<Map<Profile, Dict>> {
            let map = figment.value.clone().map_err(|e| e.resolved(figment))?;
            let new_map = map.into_iter()
                .filter_map(|(k, v)| {
                    let focused = Value::Dict(Tag::Default, v).find(key)?;
                    let dict = focused.into_dict()?;
                    Some((k, dict))
                })
                .collect();

            Ok(new_map)
        }

        Figment {
            profile: self.profile.clone(),
            metadata: self.metadata.clone(),
            value: try_focus(self, key)
        }
    }

    /// Deserializes the collected value into `T`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use serde::Deserialize;
    ///
    /// use figment::{Figment, providers::{Format, Toml, Json, Env}};
    ///
    /// #[derive(Debug, PartialEq, Deserialize)]
    /// struct Config {
    ///     name: String,
    ///     numbers: Option<Vec<usize>>,
    ///     debug: bool,
    /// }
    ///
    /// figment::Jail::expect_with(|jail| {
    ///     jail.create_file("Config.toml", r#"
    ///         name = "test"
    ///         numbers = [1, 2, 3, 10]
    ///     "#)?;
    ///
    ///     jail.set_env("config_name", "env-test");
    ///
    ///     jail.create_file("Config.json", r#"
    ///         {
    ///             "name": "json-test",
    ///             "debug": true
    ///         }
    ///     "#)?;
    ///
    ///     let config: Config = Figment::new()
    ///         .merge(Toml::file("Config.toml"))
    ///         .merge(Env::prefixed("CONFIG_"))
    ///         .join(Json::file("Config.json"))
    ///         .extract()?;
    ///
    ///     assert_eq!(config, Config {
    ///         name: "env-test".into(),
    ///         numbers: vec![1, 2, 3, 10].into(),
    ///         debug: true
    ///     });
    ///
    ///     Ok(())
    /// });
    /// ```
    pub fn extract<'a, T: Deserialize<'a>>(&self) -> Result<T> {
        T::deserialize(ConfiguredValueDe::from(self, &self.merged()?))
    }

    /// Deserializes the value at the `key` path in the collected value into
    /// `T`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use figment::{Figment, providers::{Format, Toml, Json}};
    ///
    /// figment::Jail::expect_with(|jail| {
    ///     jail.create_file("Config.toml", r#"
    ///         numbers = [1, 2, 3, 10]
    ///     "#)?;
    ///
    ///     jail.create_file("Config.json", r#"{ "debug": true } "#)?;
    ///
    ///     let numbers: Vec<usize> = Figment::new()
    ///         .merge(Toml::file("Config.toml"))
    ///         .join(Json::file("Config.json"))
    ///         .extract_inner("numbers")?;
    ///
    ///     assert_eq!(numbers, vec![1, 2, 3, 10]);
    ///
    ///     Ok(())
    /// });
    /// ```
    pub fn extract_inner<'a, T: Deserialize<'a>>(&self, key: &str) -> Result<T> {
        T::deserialize(ConfiguredValueDe::from(self, &self.find_value(key)?))
    }

    /// Returns an iterator over the metadata for all of the collected values in
    /// the order in which they were added to `self`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use figment::{Figment, providers::{Format, Toml, Json}};
    ///
    /// let figment = Figment::new()
    ///     .merge(Toml::file("Config.toml"))
    ///     .join(Json::file("Config.json"));
    ///
    /// assert_eq!(figment.metadata().count(), 2);
    /// for (i, md) in figment.metadata().enumerate() {
    ///     match i {
    ///         0 => assert!(md.name.starts_with("TOML")),
    ///         1 => assert!(md.name.starts_with("JSON")),
    ///         _ => unreachable!(),
    ///     }
    /// }
    /// ```
    // In fact, the order in which they were added globally. Why? Because
    // `BTreeMap` returns values in order of keys, and we generate a new ID,
    // monotonically greater than the previous, each time a new item is
    // provided. It's important that the IDs are unique globally since we can
    // allow combining `Figment`s.
    pub fn metadata(&self) -> impl Iterator<Item = &Metadata> {
        self.metadata.values()
    }

    /// Returns the selected profile.
    ///
    /// # Example
    ///
    /// ```
    /// use figment::Figment;
    ///
    /// let figment = Figment::new();
    /// assert_eq!(figment.profile(), "default");
    ///
    /// let figment = figment.select("staging");
    /// assert_eq!(figment.profile(), "staging");
    /// ```
    pub fn profile(&self) -> &Profile {
        &self.profile
    }

    /// Returns an iterator over profiles with valid configurations in this
    /// figment. **Note:** this may not include the selected profile if the
    /// selected profile has no configured values.
    ///
    /// # Example
    ///
    /// ```
    /// use figment::{Figment, providers::Serialized};
    ///
    /// let figment = Figment::new();
    /// let profiles = figment.profiles().collect::<Vec<_>>();
    /// assert_eq!(profiles.len(), 0);
    ///
    /// let figment = Figment::new()
    ///     .join(Serialized::default("key", "hi"))
    ///     .join(Serialized::default("key", "hey").profile("debug"));
    ///
    /// let mut profiles = figment.profiles().collect::<Vec<_>>();
    /// profiles.sort();
    /// assert_eq!(profiles, &["debug", "default"]);
    ///
    /// let figment = Figment::new()
    ///     .join(Serialized::default("key", "hi").profile("release"))
    ///     .join(Serialized::default("key", "hi").profile("testing"))
    ///     .join(Serialized::default("key", "hey").profile("staging"))
    ///     .select("debug");
    ///
    /// let mut profiles = figment.profiles().collect::<Vec<_>>();
    /// profiles.sort();
    /// assert_eq!(profiles, &["release", "staging", "testing"]);
    /// ```
    pub fn profiles(&self) -> impl Iterator<Item = &Profile> {
        self.value.as_ref()
            .ok()
            .map(|v| v.keys())
            .into_iter()
            .flatten()
    }

    /// Finds the value at `key` path in the combined value. See
    /// [`Value::find()`] for details on the syntax for `key`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use serde::Deserialize;
    ///
    /// use figment::{Figment, providers::{Format, Toml, Json, Env}};
    ///
    /// figment::Jail::expect_with(|jail| {
    ///     jail.create_file("Config.toml", r#"
    ///         name = "test"
    ///
    ///         [package]
    ///         name = "my-package"
    ///     "#)?;
    ///
    ///     jail.create_file("Config.json", r#"
    ///         {
    ///             "author": { "name": "Bob" }
    ///         }
    ///     "#)?;
    ///
    ///     let figment = Figment::new()
    ///         .merge(Toml::file("Config.toml"))
    ///         .join(Json::file("Config.json"));
    ///
    ///     let name = figment.find_value("name")?;
    ///     assert_eq!(name.as_str(), Some("test"));
    ///
    ///     let package_name = figment.find_value("package.name")?;
    ///     assert_eq!(package_name.as_str(), Some("my-package"));
    ///
    ///     let author_name = figment.find_value("author.name")?;
    ///     assert_eq!(author_name.as_str(), Some("Bob"));
    ///
    ///     Ok(())
    /// });
    /// ```
    pub fn find_value(&self, key: &str) -> Result<Value> {
        self.merged()?
            .find(key)
            .ok_or_else(|| Kind::MissingField(key.to_string().into()).into())
    }

    /// Finds the metadata for the value at `key` path. See [`Value::find()`]
    /// for details on the syntax for `key`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use serde::Deserialize;
    ///
    /// use figment::{Figment, providers::{Format, Toml, Json, Env}};
    ///
    /// figment::Jail::expect_with(|jail| {
    ///     jail.create_file("Config.toml", r#" name = "test" "#)?;
    ///     jail.set_env("CONF_AUTHOR", "Bob");
    ///
    ///     let figment = Figment::new()
    ///         .merge(Toml::file("Config.toml"))
    ///         .join(Env::prefixed("CONF_").only(&["author"]));
    ///
    ///     let name_md = figment.find_metadata("name").unwrap();
    ///     assert!(name_md.name.starts_with("TOML"));
    ///
    ///     let author_md = figment.find_metadata("author").unwrap();
    ///     assert!(author_md.name.contains("CONF_"));
    ///     assert!(author_md.name.contains("environment"));
    ///
    ///     Ok(())
    /// });
    /// ```
    pub fn find_metadata(&self, key: &str) -> Option<&Metadata> {
        self.metadata.get(&self.find_value(key).ok()?.tag())
    }

    /// Returns the metadata with the given `tag` if this figment contains a
    /// value with said metadata.
    ///
    /// # Example
    ///
    /// ```rust
    /// use serde::Deserialize;
    ///
    /// use figment::{Figment, providers::{Format, Toml, Json, Env}};
    ///
    /// figment::Jail::expect_with(|jail| {
    ///     jail.create_file("Config.toml", r#" name = "test" "#)?;
    ///     jail.create_file("Config.json", r#" { "author": "Bob" } "#)?;
    ///
    ///     let figment = Figment::new()
    ///         .merge(Toml::file("Config.toml"))
    ///         .join(Json::file("Config.json"));
    ///
    ///     let name = figment.find_value("name").unwrap();
    ///     let metadata = figment.get_metadata(name.tag()).unwrap();
    ///     assert!(metadata.name.starts_with("TOML"));
    ///
    ///     let author = figment.find_value("author").unwrap();
    ///     let metadata = figment.get_metadata(author.tag()).unwrap();
    ///     assert!(metadata.name.starts_with("JSON"));
    ///
    ///     Ok(())
    /// });
    /// ```
    pub fn get_metadata(&self, tag: Tag) -> Option<&Metadata> {
        self.metadata.get(&tag)
    }
}

impl Provider for Figment {
    fn metadata(&self) -> Metadata { Metadata::default() }

    fn data(&self) -> Result<Map<Profile, Dict>> { self.value.clone() }

    fn profile(&self) -> Option<Profile> {
        Some(self.profile.clone())
    }

    fn __metadata_map(&self) -> Option<Map<Tag, Metadata>> {
        Some(self.metadata.clone())
    }
}

impl Default for Figment {
    fn default() -> Self {
        Figment::new()
    }
}

#[test]
#[cfg(test)]
fn is_send_sync() {
    fn check_for_send_sync<T: Send + Sync>() {}
    check_for_send_sync::<Figment>();
}