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
585
586
587
588
589
590
591
592
593
594
595
#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/README.md"))]
#![deny(missing_docs)]

use std::{
    collections::HashMap,
    path::{Path, PathBuf},
    str::FromStr,
};

use serde::{de::DeserializeOwned, Serialize};
use thiserror::Error;
use toml::Value;

/// A source of configuration.
#[derive(Debug, Clone)]
pub enum ConfigSource {
    /// From two configuration sources merged together.
    Merged {
        /// Merged from.
        from: Box<Self>,
        /// Merged into.
        into: Box<Self>,
    },
    /// From a `.toml.env` file (Path may be different if user has specified something different).
    DotEnv(PathBuf),
    /// From a configuration file.
    File(PathBuf),
    /// From environment variables.
    Environment {
        /// The names of the environment variables.
        variable_names: Vec<String>,
    },
}

impl std::fmt::Display for ConfigSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ConfigSource::Merged { from, into } => write!(f, "({from}) merged into ({into})"),
            ConfigSource::DotEnv(path) => write!(f, "dotenv TOML file {path:?}"),
            ConfigSource::File(path) => write!(f, "config TOML file {path:?}"),
            ConfigSource::Environment { variable_names } => {
                let variable_names = variable_names.join(", ");
                write!(f, "environment variables {variable_names}")
            }
        }
    }
}

/// An error that occurs while initializing configuration.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum Error {
    /// Error reading environment variable.
    #[error("Error reading {name} environment variable")]
    ErrorReadingEnvironmentVariable {
        /// Name of the environment variable.
        name: String,
        /// Source of the error.
        #[source]
        error: std::env::VarError,
    },
    /// Error parsing an environment variable as valid TOML.
    #[error("Error parsing {name} environment variable as valid TOML")]
    ErrorParsingEnvironmentVariableAsToml {
        /// Name of the environment variable.
        name: String,
    },
    /// Error reading TOML file.
    #[error("Error reading TOML file {path:?}")]
    ErrorReadingFile {
        /// Path to the file.
        path: PathBuf,
        /// Source of the error.
        #[source]
        error: std::io::Error,
    },
    /// Error parsing TOML file.
    #[error("Error parsing TOML file {path:?}")]
    ErrorParsingTomlFile {
        /// Path to the file.
        path: PathBuf,
        /// Source of the error.
        #[source]
        error: toml::de::Error,
    },
    /// Cannot parse a table in the `.toml.env` file.
    #[error("Cannot parse {key} as environment variable in {path:?}. Advice: {advice}")]
    CannotParseTomlDotEnvFile {
        /// Key in the TOML file.
        key: String,
        /// Path to the file.
        path: PathBuf,
        /// Advice
        advice: String,
    },
    /// Error parsing envirnment variable
    #[error("Error parsing config key ({name}) in TOML config file {path:?}")]
    ErrorParsingTomlDotEnvFileKey {
        /// Name of the key variable.
        name: String,
        /// Path to the file.
        path: PathBuf,
        /// Source of the error.
        #[source]
        error: toml::de::Error,
    },
    /// Error parsing an environment variable as the config.
    #[error("Error parsing environment variable ({name}={value:?}) as the config.")]
    ErrorParsingEnvironmentVariableAsConfig {
        /// Name of the environment variable.
        name: String,
        /// Value of the environment variable.
        value: String,
        /// Source of the error.
        #[source]
        error: toml::de::Error,
    },
    /// Either there was an error parsing the environment variable as the config, or if the value
    /// is a filename, it does not exist.
    #[error(
        "Error parsing config environment variable ({name}={value:?}) as the config or if it is a filename, the file does not exist."
    )]
    ErrorParsingEnvironmentVariableAsConfigOrFile {
        /// Name of the environment variable.
        name: String,
        /// Value of the environment variable.
        value: String,
        /// Source of the error.
        #[source]
        error: toml::de::Error,
    },
    /// Error parsing file as `.env.toml` format.
    #[error(
        "Error parsing the {path:?} as `.env.toml` format file:\n{value:#?}\nTop level should be a table."
    )]
    UnexpectedTomlDotEnvFileFormat {
        /// Path to file.
        path: PathBuf,
        /// Value that was unable to be parsed as `.env.toml` format
        value: Value,
    },
    /// Error parsing merged configuration.
    #[error("Error parsing merged configuration from {source}")]
    ErrorParsingMergedToml {
        /// Source(s) of the configuration.
        source: ConfigSource,
        /// Source of the error.
        #[source]
        error: toml::de::Error,
    },
    /// Error merging configurations.
    #[error("Error merging configuration {from} into {into}: {error}")]
    ErrorMerging {
        /// Error merging from this source.
        from: ConfigSource,
        /// Error merging into this source.
        into: ConfigSource,
        /// Source of the error.
        error: serde_toml_merge::Error,
    },
    /// Invalid TOML key.
    #[error("Invalid TOML key {0}. Expected something resembling a json pointer. e.g. `key` or `key_one.child`")]
    InvalidTomlKey(String),
}

/// Convenience type shorthand for `Result<T, Error>`.
pub type Result<T> = std::result::Result<T, Error>;

/// Default name for attempting to load the configuration (and environment variables) from a file.
pub const DEFAULT_DOTENV_PATH: &str = ".env.toml";

/// Default environment variable name to use for loading configuration from. Also the same name
/// used for the table of the configuration within the `.env.toml`.
pub const DEFAULT_CONFIG_VARIABLE_NAME: &str = "CONFIG";

/// What method of logging for this library to use.
#[derive(Default, Clone, Copy)]
pub enum Logging {
    /// Don't perform any logging
    #[default]
    None,
    /// Use STDOUT for logging.
    StdOut,
    /// Use the [`log`] crate for logging.
    #[cfg(feature = "log")]
    Log,
}

/// A path to a key into a [`toml::Value`].
#[derive(Debug, Clone)]
pub struct TomlKeyPath(Vec<String>);

impl std::fmt::Display for TomlKeyPath {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0.join("."))
    }
}

impl FromStr for TomlKeyPath {
    type Err = Error;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        Ok(Self(s.split('.').map(ToOwned::to_owned).collect()))
    }
}

/// Args as input to [`initialize()`].
pub struct Args<'a, M = HashMap<&'a str, TomlKeyPath>> {
    /// Path to `.env.toml` format file. The value is [`DEFAULT_DOTENV_PATH`] by default.
    pub dotenv_path: &'a Path,
    /// Path to a config file to load.
    pub config_path: Option<&'a Path>,
    /// Name of the environment variable to use that stores the config. The value is [`DEFAULT_CONFIG_VARIABLE_NAME`] by default.
    pub config_variable_name: &'a str,
    /// What method of logging to use (if any). [`Logging::None`] by default.
    pub logging: Logging,
    /// Map the specified environment variables into config keys.
    pub map_env: M,
}

impl<M> Default for Args<'static, M>
where
    M: Default,
{
    fn default() -> Self {
        Self {
            dotenv_path: Path::new(DEFAULT_DOTENV_PATH),
            config_path: None,
            config_variable_name: DEFAULT_CONFIG_VARIABLE_NAME,
            logging: Logging::default(),
            map_env: M::default(),
        }
    }
}

fn log_info(logging: Logging, args: std::fmt::Arguments<'_>) {
    match logging {
        Logging::None => {}
        Logging::StdOut => println!("INFO {}: {}", module_path!(), std::fmt::format(args)),
        #[cfg(feature = "log")]
        Logging::Log => log::info!("{}", std::fmt::format(args)),
    }
}

/// Reads and parses the .env.toml file (or whatever is specified in `dotenv_path`). Returns
/// `Some(C)` if the file contains a table with the name matching `config_variable_name`.
fn initialize_dotenv_toml<'a, C: DeserializeOwned + Serialize>(
    dotenv_path: &'a Path,
    config_variable_name: &'a str,
    logging: Logging,
) -> Result<Option<C>> {
    let path = Path::new(dotenv_path);
    if !path.exists() {
        return Ok(None);
    }

    log_info(
        logging,
        format_args!("Loading config and environment variables from dotenv {path:?}"),
    );

    let env_str = std::fs::read_to_string(path).map_err(|error| Error::ErrorReadingFile {
        path: path.to_owned(),
        error,
    })?;
    let env: Value = toml::from_str(&env_str).map_err(|error| Error::ErrorParsingTomlFile {
        path: path.to_owned(),
        error,
    })?;
    let table: toml::value::Table = match env {
        Value::Table(table) => table,
        unexpected => {
            return Err(Error::UnexpectedTomlDotEnvFileFormat {
                path: path.to_owned(),
                value: unexpected,
            });
        }
    };

    let mut config: Option<C> = None;
    for (key, value) in table {
        let value_string = match value {
            Value::Table(_) => {
                if key.as_str() != config_variable_name {
                    return Err(Error::CannotParseTomlDotEnvFile {
                        key,
                        path: path.to_owned(),
                        advice: format!("Only a table with {config_variable_name} is allowed in a .toml.env format file."),
                    });
                }
                match C::deserialize(value.clone()) {
                    Ok(c) => config = Some(c),
                    Err(error) => {
                        return Err(Error::ErrorParsingTomlDotEnvFileKey {
                            name: key,
                            path: path.to_owned(),
                            error,
                        })
                    }
                }
                None
            }
            Value::String(value) => Some(value),
            Value::Integer(value) => Some(value.to_string()),
            Value::Float(value) => Some(value.to_string()),
            Value::Boolean(value) => Some(value.to_string()),
            Value::Datetime(value) => Some(value.to_string()),
            Value::Array(value) => {
                return Err(Error::CannotParseTomlDotEnvFile {
                    key,
                    path: path.to_owned(),
                    advice: format!("Array values are not supported: {value:?}"),
                })
            }
        };

        if let Some(value_string) = value_string {
            std::env::set_var(key.as_str(), value_string)
        }
    }
    Ok(config)
}

fn initialize_env<'a>(
    logging: Logging,
    map_env: Vec<(&'a str, TomlKeyPath)>,
) -> Result<Option<Value>> {
    if !matches!(logging, Logging::None) && !map_env.is_empty() {
        let mut buffer = String::new();
        buffer.push_str("\n\x1b[34m");
        for (k, v) in &map_env {
            if std::env::var(k).is_ok() {
                buffer.push_str(&format!("\n{k} => {v}"));
            }
        }
        buffer.push_str("\x1b[0m");
        log_info(
            logging,
            format_args!("Loading config from current environment variables: {buffer}"),
        );
    }
    fn parse_toml_value(value: String) -> Value {
        if let Ok(value) = bool::from_str(&value) {
            return Value::Boolean(value);
        }
        if let Ok(value) = f64::from_str(&value) {
            return Value::Float(value);
        }
        if let Ok(value) = i64::from_str(&value) {
            return Value::Integer(value);
        }
        if let Ok(value) = toml::value::Datetime::from_str(&value) {
            return Value::Datetime(value);
        }

        Value::String(value)
    }
    fn insert_toml_value(
        table: &mut toml::Table,
        full_key: &TomlKeyPath,
        mut key: TomlKeyPath,
        value: Value,
    ) {
        if key.0.is_empty() {
            return;
        }

        let current_key = key.0.remove(0);

        if key.0.is_empty() {
            table.insert(current_key, value);
        } else {
            let table = table
                .entry(&current_key)
                .or_insert(toml::Table::new().into())
                .as_table_mut()
                .expect("Expected table");
            return insert_toml_value(table, full_key, key, value);
        }
    }

    let mut map_env = map_env.into_iter().peekable();
    if map_env.peek().is_none() {
        return Ok(None);
    }

    log_info(logging, format_args!("Loading config from environment"));

    let mut config = toml::Table::new();
    for (variable_name, toml_key) in map_env {
        let value = std::env::var(variable_name).map_err(|error| {
            Error::ErrorReadingEnvironmentVariable {
                name: (*variable_name.to_owned()).to_owned(),
                error,
            }
        })?;
        let value = parse_toml_value(value);
        insert_toml_value(&mut config, &toml_key, toml_key.clone(), value);
    }

    Ok(Some(config.into()))
}

/// Initialize configuration from available sources specified in [`Args`].
///
/// If no configuration was found, will return `None`.
///
/// See [`toml-env`](crate).
pub fn initialize<'a, M, C>(args: Args<'a, M>) -> Result<Option<C>>
where
    C: DeserializeOwned + Serialize,
    M: IntoIterator<Item = (&'a str, TomlKeyPath)> + Clone,
{
    let config_variable_name = args.config_variable_name;
    let logging = args.logging;
    let dotenv_path = args.dotenv_path;
    let map_env: Vec<(&'a str, TomlKeyPath)> = args.map_env.into_iter().collect();

    let config_env_config: Option<(Value, ConfigSource)> = match std::env::var(config_variable_name) {
        Ok(variable_value) => match toml::from_str(&variable_value) {
            Ok(config) => {
                log_info(
                    logging,
                    format_args!(
                        "Options loaded from `{config_variable_name}` environment variable"
                    ),
                );
                Ok(Some(config))
            }
            Err(error) => {
                let path = Path::new(&variable_value);
                if path.is_file() {
                    log_info(
                        args.logging,
                        format_args!("Loading environment variables from {path:?}"),
                    );

                    let config_str =
                        std::fs::read_to_string(path).map_err(|error| Error::ErrorReadingFile {
                            path: path.to_owned(),
                            error,
                        })?;
                    let config: Value = toml::from_str(&config_str).map_err(|error| {
                        Error::ErrorParsingTomlFile {
                            path: path.to_owned(),
                            error,
                        }
                    })?;
                    log_info(logging, format_args!("Options loaded from file specified in `{config_variable_name}` environment variable: {path:?}"));
                    Ok(Some(config))
                } else {
                    Err(Error::ErrorParsingEnvironmentVariableAsConfigOrFile {
                        name: config_variable_name.to_owned(),
                        value: variable_value,
                        error,
                    })
                }
            }
        },
        Err(std::env::VarError::NotPresent) => {
            log_info(
                logging,
                format_args!(
                    "No environment variable with the name {config_variable_name} found, using default options."
                ),
            );
            Ok(None)
        }
        Err(error) => Err(Error::ErrorReadingEnvironmentVariable {
            name: config_variable_name.to_owned(),
            error,
        }),
    }?.map(|config| {
        let source = ConfigSource::DotEnv(args.dotenv_path.to_owned());
        (config, source)
    });

    let dotenv_config =
        initialize_dotenv_toml(dotenv_path, config_variable_name, logging)?.map(|config| {
            (
                config,
                ConfigSource::Environment {
                    variable_names: vec![args.config_variable_name.to_owned()],
                },
            )
        });

    let config: Option<(Value, ConfigSource)> = match (dotenv_config, config_env_config) {
        (None, None) => None,
        (None, Some(config)) => Some(config),
        (Some(config), None) => Some(config),
        (Some(from), Some(into)) => {
            let config =
                serde_toml_merge::merge(into.0, from.0).map_err(|error| Error::ErrorMerging {
                    from: from.1.clone(),
                    into: into.1.clone(),
                    error,
                })?;

            let source = ConfigSource::Merged {
                from: from.1.into(),
                into: into.1.into(),
            };

            Some((config, source))
        }
    };

    let env_config = initialize_env(args.logging, map_env.clone())?.map(|value| {
        (
            value,
            ConfigSource::Environment {
                variable_names: map_env
                    .into_iter()
                    .map(|(key, _)| key.to_string())
                    .collect(),
            },
        )
    });

    let config = match (config, env_config) {
        (None, None) => None,
        (None, Some(config)) => Some(config),
        (Some(config), None) => Some(config),
        (Some(from), Some(into)) => {
            let config =
                serde_toml_merge::merge(into.0, from.0).map_err(|error| Error::ErrorMerging {
                    from: from.1.clone(),
                    into: into.1.clone(),
                    error,
                })?;

            let source = ConfigSource::Merged {
                from: from.1.into(),
                into: into.1.into(),
            };
            Some((config, source))
        }
    };

    let file_config: Option<(Value, ConfigSource)> =
        Option::transpose(args.config_path.map(|path| {
            if path.is_file() {
                let file_string =
                    std::fs::read_to_string(path).map_err(|error| Error::ErrorReadingFile {
                        path: path.to_owned(),
                        error,
                    })?;
                return Ok(Some((
                    toml::from_str(&file_string).map_err(|error| Error::ErrorParsingTomlFile {
                        path: path.to_owned(),
                        error,
                    })?,
                    ConfigSource::File(path.to_owned()),
                )));
            }
            Ok(None)
        }))?
        .flatten();

    let config = match (config, file_config) {
        (None, None) => None,
        (None, Some(config)) => Some(config),
        (Some(config), None) => Some(config),
        (Some(from), Some(into)) => {
            let config =
                serde_toml_merge::merge(into.0, from.0).map_err(|error| Error::ErrorMerging {
                    from: from.1.clone(),
                    into: into.1.clone(),
                    error,
                })?;

            let source = ConfigSource::Merged {
                from: from.1.into(),
                into: into.1.into(),
            };
            Some((config, source))
        }
    };

    let config = Option::transpose(config.map(|(config, source)| {
        C::deserialize(config).map_err(|error| Error::ErrorParsingMergedToml { source, error })
    }))?;

    if !matches!((logging, &config), (Logging::None, None)) {
        let config_string = toml::to_string_pretty(&config)
            .expect("Expected to be able to re-serialize config toml");
        log_info(
            logging,
            format_args!("{config_variable_name}:\n\x1b[34m{config_string}\x1b[0m"),
        );
    }

    Ok(config)
}