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
use std::{
    env,
    path::{Path, PathBuf},
};

#[cfg(feature = "config-json")]
use figment::providers::Json;
#[cfg(feature = "config-yaml")]
use figment::providers::Yaml;
use figment::{
    providers::{Env, Format, Serialized, Toml},
    Figment, Profile,
};
use serde::{de::DeserializeOwned, Serialize};
use thiserror::Error;
use tracing::{debug, info};
#[cfg(feature = "xdg")]
use xdg;

use crate::str::to_train_case;

#[allow(clippy::large_enum_variant)]
#[derive(Error, Debug)]
pub enum ConfigError {
    /// The current directory could not be determined.
    #[error("Unable to determine the current directory.")]
    GetCurrentDir {
        #[from]
        source: std::io::Error,
    },
    /// None of the provided paths were valid configuration files.
    #[error("None of the provided paths were valid configuration files.")]
    NoValidPath,
    /// A config file format was not speicfied and we were unable to infer one
    /// from the path.
    #[error("Unable to derive config file format from extension.")]
    UnknownExtension,
    #[error("Unable to extract config from providers: {source}")]
    ExtractConfig {
        #[from]
        source: figment::Error,
    },
}

#[derive(Clone)]
pub enum ConfigFileFormat {
    #[cfg(feature = "config-json")]
    Json,
    Toml,
    #[cfg(feature = "config-yaml")]
    Yaml,
}

/// Attempts to read a Config object from the specified path.
///
/// The expected file format can be optionally specified. If a format is not
/// specified, the library will attempt to infer it from the file extension.
pub fn figment_from_file<P: AsRef<Path>>(
    path: P,
    format: Option<ConfigFileFormat>,
) -> Result<Figment, ConfigError> {
    let path = path.as_ref();

    let format = match format {
        Some(format) => format,
        None => infer_format_from_path(path)?,
    };

    info!("Reading config file from {}", path.display());

    let figment = Figment::new();

    let figment = match format {
        #[cfg(feature = "config-json")]
        ConfigFileFormat::Json => figment.merge(Json::file(path)),
        ConfigFileFormat::Toml => figment.merge(Toml::file(path)),
        #[cfg(feature = "config-yaml")]
        ConfigFileFormat::Yaml => figment.merge(Yaml::file(path)),
    };

    Ok(figment)
}

/// Attempts to read a Config object from the specified path.
///
/// The expected file format can be optionally specified. If a format is not
/// specified, the library will attempt to infer it from the file extension.
pub fn from_file<P: AsRef<Path>, C: DeserializeOwned>(
    path: P,
    format: Option<ConfigFileFormat>,
) -> Result<C, ConfigError> {
    extract(figment_from_file(path, format)?)
}

/// Attempts to read a Config object from the specified paths.
pub fn figment_from_paths<P: AsRef<Path>>(
    paths: Vec<(P, Option<ConfigFileFormat>)>,
) -> Result<Option<Figment>, ConfigError> {
    for (path, format) in paths {
        if path.as_ref().exists() {
            return Ok(Some(figment_from_file(path, format)?));
        }
    }

    Ok(None)
}

/// Attempts to read a Config object from the specified paths.
pub fn from_paths<P: AsRef<Path>, C: DeserializeOwned>(
    paths: Vec<(P, Option<ConfigFileFormat>)>,
) -> Result<C, ConfigError> {
    match figment_from_paths(paths)? {
        Some(figment) => extract(figment),
        None => Err(ConfigError::NoValidPath),
    }
}

/// Attempts to read a Config object from the current directory.
///
/// The configuration file is expected to be a file named `config.ext` where
/// `ext` is one of `json`, `toml`, or `yaml`.
pub fn from_current_dir<C: DeserializeOwned>(format: ConfigFileFormat) -> Result<C, ConfigError> {
    let current_path = get_current_dir_config_path(&format)?;

    from_file(current_path, Some(format))
}

/// Similar to `from_paths`. Uses a default set of paths:
///
/// - CURRENT_WORKING_DIRECTORY/config.toml
/// - /etc/CRATE/config.toml
pub fn from_default_paths<P: AsRef<Path>, C: DeserializeOwned>(
    application_name: &str,
    additional_paths: &[(P, Option<ConfigFileFormat>)],
    format: ConfigFileFormat,
) -> Result<C, ConfigError> {
    let mut paths = as_paths(additional_paths);

    paths.push((get_current_dir_config_path(&format)?, Some(format.clone())));
    paths.push((
        get_name_config_path(application_name, &format),
        Some(format),
    ));

    from_paths(paths)
}

/// Similar to `from_paths`. Uses a default set of paths:
///
/// - CURRENT_WORKING_DIRECTORY/config.toml
/// - /etc/CRATE/config.toml
pub fn from_defaults<P: AsRef<Path>, C: DeserializeOwned + Default + Serialize>(
    application_name: &str,
    additional_paths: &[(P, Option<ConfigFileFormat>)],
    format: ConfigFileFormat,
) -> Result<C, ConfigError> {
    let mut paths = as_paths(additional_paths);

    paths.push((get_current_dir_config_path(&format)?, Some(format.clone())));
    paths.push((
        get_name_config_path(application_name, &format),
        Some(format),
    ));

    let default_config: C = Default::default();
    let figment = Figment::from(Serialized::from(default_config, Profile::default()));

    let figment = match figment_from_paths(paths)? {
        Some(file_figment) => figment.merge(file_figment),
        None => figment,
    };

    let env_prefix = format!("{}_", to_train_case(application_name));

    debug!("Using env prefix: {}", &env_prefix);

    extract(figment.merge(Env::prefixed(&env_prefix)))
}

fn as_paths<P: AsRef<Path>>(
    path_refs: &[(P, Option<ConfigFileFormat>)],
) -> Vec<(PathBuf, Option<ConfigFileFormat>)> {
    let mut paths: Vec<(PathBuf, Option<ConfigFileFormat>)> = vec![];

    for (path, format) in path_refs {
        let mut pathbuf = PathBuf::new();

        pathbuf.push(path);

        paths.push((pathbuf, format.clone()));
    }

    paths
}

fn get_current_dir_config_path(format: &ConfigFileFormat) -> Result<PathBuf, ConfigError> {
    let mut current_path =
        env::current_dir().map_err(|source| ConfigError::GetCurrentDir { source })?;

    current_path.push(get_default_filename_from_format(format));

    Ok(current_path)
}

fn get_name_config_path(application_name: &str, format: &ConfigFileFormat) -> PathBuf {
    let mut config_path = PathBuf::from("/etc/");

    config_path.push(application_name);
    config_path.push(get_default_filename_from_format(format));

    config_path
}

#[cfg(feature = "xdg")]
pub fn get_name_xdg_config_path(
    application_name: &str,
    format: &ConfigFileFormat,
) -> Option<PathBuf> {
    let xdg_dirs = xdg::BaseDirectories::with_prefix(application_name).ok();

    if let Some(xdg_dirs) = xdg_dirs {
        xdg_dirs.find_config_file(get_default_filename_from_format(format))
    } else {
        None
    }
}

fn infer_format_from_path<P: AsRef<Path>>(path: P) -> Result<ConfigFileFormat, ConfigError> {
    match path.as_ref().extension() {
        Some(extension) => match extension.to_str() {
            Some("yaml") => Ok(ConfigFileFormat::Yaml),
            Some("yml") => Ok(ConfigFileFormat::Yaml),
            Some("json") => Ok(ConfigFileFormat::Json),
            Some("toml") => Ok(ConfigFileFormat::Toml),
            _ => Err(ConfigError::UnknownExtension),
        },
        _ => Err(ConfigError::UnknownExtension),
    }
}

fn get_default_filename_from_format(format: &ConfigFileFormat) -> &'static str {
    match format {
        #[cfg(feature = "config-json")]
        ConfigFileFormat::Json => "config.json",
        ConfigFileFormat::Toml => "config.toml",
        #[cfg(feature = "config-yaml")]
        ConfigFileFormat::Yaml => "config.yaml",
    }
}

fn extract<C: DeserializeOwned>(figment: Figment) -> Result<C, ConfigError> {
    figment
        .extract()
        .map_err(|source| ConfigError::ExtractConfig { source })
}