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
#![doc = include_str!("../README.md")]

mod error;

use crate::error::{
    DeserializationError, Result, SerializationError, UniversalConfigError as Error,
    UniversalConfigError,
};
use dirs::{config_dir, home_dir};
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::fs;
use std::path::{Path, PathBuf};
use tracing::debug;

/// Supported config formats.
pub enum Format {
    /// `.json` file
    #[cfg(feature = "json")]
    Json,
    /// `.yaml` or `.yml` files.
    #[cfg(feature = "yaml")]
    Yaml,
    /// `.toml` files.
    #[cfg(feature = "toml")]
    Toml,
    /// `.corn` files.
    #[cfg(feature = "corn")]
    Corn,
    /// `.xml` files.
    #[cfg(feature = "xml")]
    Xml,
    /// `.ron` files.
    #[cfg(feature = "ron")]
    Ron,
}

impl Format {
    const fn extension(&self) -> &str {
        match self {
            #[cfg(feature = "json")]
            Self::Json => "json",
            #[cfg(feature = "yaml")]
            Self::Yaml => "yaml",
            #[cfg(feature = "toml")]
            Self::Toml => "toml",
            #[cfg(feature = "corn")]
            Self::Corn => "corn",
            #[cfg(feature = "xml")]
            Self::Xml => "xml",
            #[cfg(feature = "ron")]
            Self::Ron => "ron",
        }
    }
}

/// The main loader struct.
///
/// Create a new loader and configure as appropriate
/// to load your config file.
pub struct ConfigLoader<'a> {
    /// The name of your program, used when determining the directory path.
    app_name: &'a str,
    /// The name of the file (*excluding* extension) to search for.
    /// Defaults to `config`.
    file_name: &'a str,
    /// Allowed file formats.
    /// Defaults to all formats.
    /// Set to disable formats you do not wish to allow.
    formats: &'a [Format],
    /// The directory to load the config file from.
    /// Defaults to your system config dir (`$XDG_CONFIG_DIR` on Linux),
    /// or your home dir if that does not exist.
    config_dir: Option<&'a str>,
}

impl<'a> ConfigLoader<'a> {
    /// Creates a new config loader for the provided app name.
    /// Uses a default file name of "config" and all formats.
    #[must_use]
    pub const fn new(app_name: &'a str) -> ConfigLoader<'a> {
        Self {
            app_name,
            file_name: "config",
            formats: &[
                #[cfg(feature = "json")]
                Format::Json,
                #[cfg(feature = "yaml")]
                Format::Yaml,
                #[cfg(feature = "toml")]
                Format::Toml,
                #[cfg(feature = "corn")]
                Format::Corn,
                #[cfg(feature = "xml")]
                Format::Xml,
                #[cfg(feature = "ron")]
                Format::Ron,
            ],
            config_dir: None,
        }
    }

    /// Specifies the file name to look for, excluding the extension.
    ///
    /// If not specified, defaults to "config".
    #[must_use]
    pub const fn with_file_name(mut self, file_name: &'a str) -> Self {
        self.file_name = file_name;
        self
    }

    /// Specifies which file formats to search for, and in which order.
    ///
    /// If not specified, all formats are checked for
    /// in the order JSON, YAML, TOML, Corn.
    #[must_use]
    pub const fn with_formats(mut self, formats: &'a [Format]) -> Self {
        self.formats = formats;
        self
    }

    /// Specifies which directory the config should be loaded from.
    ///
    /// If not specified, loads from `$XDG_CONFIG_DIR/<app_name>`
    /// or `$HOME/.<app_name>` if the config dir does not exist.
    #[must_use]
    pub const fn with_config_dir(mut self, dir: &'a str) -> Self {
        self.config_dir = Some(dir);
        self
    }

    /// Attempts to locate a config file on disk and load it.
    ///
    /// # Errors
    ///
    /// Will return a `UniversalConfigError` if any error occurs
    /// when looking for, reading, or deserializing a config file.
    pub fn find_and_load<T: DeserializeOwned>(&self) -> Result<T> {
        let file = self.try_find_file()?;
        debug!("Found file at: '{}", file.display());
        Self::load(&file)
    }

    /// Attempts to find the directory in which the config file is stored.
    fn get_config_dir(&self) -> std::result::Result<PathBuf, UniversalConfigError> {
        self.config_dir
            .map(Into::into)
            .or_else(|| config_dir().map(|dir| dir.join(self.app_name)))
            .or_else(|| home_dir().map(|dir| dir.join(format!(".{}", self.app_name))))
            .ok_or(Error::MissingUserDir)
    }

    /// Attempts to find a config file for the given app name
    /// in the app's config directory
    /// that matches any of the allowed formats.
    fn try_find_file(&self) -> Result<PathBuf> {
        let config_dir = self.get_config_dir()?;

        let extensions = self.get_extensions();

        debug!("Using config dir: {}", config_dir.display());

        let file = extensions.into_iter().find_map(|extension| {
            let full_path = config_dir.join(format!("{}.{extension}", self.file_name));

            if Path::exists(&full_path) {
                Some(full_path)
            } else {
                None
            }
        });

        file.ok_or(Error::FileNotFound)
    }

    /// Loads the file at the given path,
    /// deserializing it into a new `T`.
    ///
    /// The type is automatically determined from the file extension.
    ///
    /// # Errors
    ///
    /// Will return a `UniversalConfigError` if unable to read or deserialize the file.
    pub fn load<T: DeserializeOwned, P: AsRef<Path>>(path: P) -> Result<T> {
        let str = fs::read_to_string(&path)?;

        let extension = path
            .as_ref()
            .extension()
            .unwrap_or_default()
            .to_str()
            .unwrap_or_default();

        let config = Self::deserialize(&str, extension)?;
        Ok(config)
    }

    /// Gets a list of supported and enabled file extensions.
    fn get_extensions(&self) -> Vec<&'static str> {
        let mut extensions = vec![];

        for format in self.formats {
            match format {
                #[cfg(feature = "json")]
                Format::Json => extensions.push("json"),
                #[cfg(feature = "yaml")]
                Format::Yaml => {
                    extensions.push("yaml");
                    extensions.push("yml");
                }
                #[cfg(feature = "toml")]
                Format::Toml => extensions.push("toml"),
                #[cfg(feature = "corn")]
                Format::Corn => extensions.push("corn"),
                #[cfg(feature = "xml")]
                Format::Xml => extensions.push("xml"),
                #[cfg(feature = "ron")]
                Format::Ron => extensions.push("ron"),
            }
        }

        extensions
    }

    /// Attempts to deserialize the provided input into `T`,
    /// based on the provided file extension.
    fn deserialize<T: DeserializeOwned>(
        str: &str,
        extension: &str,
    ) -> std::result::Result<T, DeserializationError> {
        let res = match extension {
            #[cfg(feature = "json")]
            "json" => serde_json::from_str(str).map_err(DeserializationError::from),
            #[cfg(feature = "toml")]
            "toml" => toml::from_str(str).map_err(DeserializationError::from),
            #[cfg(feature = "yaml")]
            "yaml" | "yml" => serde_yaml::from_str(str).map_err(DeserializationError::from),
            #[cfg(feature = "corn")]
            "corn" => libcorn::from_str(str).map_err(DeserializationError::from),
            #[cfg(feature = "xml")]
            "xml" => serde_xml_rs::from_str(str).map_err(DeserializationError::from),
            #[cfg(feature = "ron")]
            "ron" => ron::from_str(str).map_err(DeserializationError::from),
            _ => Err(DeserializationError::UnsupportedExtension(
                extension.to_string(),
            )),
        }?;

        Ok(res)
    }

    /// Saves the provided configuration into a file of the specified format.
    ///
    /// The file is stored in the app's configuration directory.
    /// Directories are automatically created if required.
    ///
    /// # Errors
    ///
    /// If the provided config cannot be serialised into the format, an error will be returned.
    /// The `.corn` format is not supported, and the function will error if specified.
    ///
    /// If a valid config dir cannot be found, an error will be returned.
    ///
    /// If the file cannot be written to the specified path, an error will be returned.
    pub fn save<T: Serialize>(&self, config: &T, format: &Format) -> Result<()> {
        let str = match format {
            #[cfg(feature = "json")]
            Format::Json => serde_json::to_string_pretty(config).map_err(SerializationError::from),
            #[cfg(feature = "yaml")]
            Format::Yaml => serde_yaml::to_string(config).map_err(SerializationError::from),
            #[cfg(feature = "toml")]
            Format::Toml => toml::to_string_pretty(config).map_err(SerializationError::from),
            #[cfg(feature = "corn")]
            Format::Corn => Err(SerializationError::UnsupportedExtension("corn".to_string())),
            #[cfg(feature = "xml")]
            Format::Xml => serde_xml_rs::to_string(config).map_err(SerializationError::from),
            #[cfg(feature = "ron")]
            Format::Ron => ron::to_string(config).map_err(SerializationError::from),
        }?;

        let config_dir = self.get_config_dir()?;
        let file_name = format!("{}.{}", self.file_name, format.extension());
        let full_path = config_dir.join(file_name);

        fs::create_dir_all(config_dir)?;
        fs::write(full_path, str)?;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::Deserialize;

    #[derive(Deserialize)]
    struct ConfigContents {
        test: String,
    }

    #[test]
    fn test_json() {
        let res: ConfigContents = ConfigLoader::load("test_configs/config.json").unwrap();
        assert_eq!(res.test, "hello world")
    }

    #[test]
    fn test_yaml() {
        let res: ConfigContents = ConfigLoader::load("test_configs/config.yaml").unwrap();
        assert_eq!(res.test, "hello world")
    }

    #[test]
    fn test_toml() {
        let res: ConfigContents = ConfigLoader::load("test_configs/config.toml").unwrap();
        assert_eq!(res.test, "hello world")
    }

    #[test]
    fn test_corn() {
        let res: ConfigContents = ConfigLoader::load("test_configs/config.corn").unwrap();
        assert_eq!(res.test, "hello world")
    }

    #[test]
    fn test_xml() {
        let res: ConfigContents = ConfigLoader::load("test_configs/config.xml").unwrap();
        assert_eq!(res.test, "hello world")
    }

    #[test]
    fn test_ron() {
        let res: ConfigContents = ConfigLoader::load("test_configs/config.ron").unwrap();
        assert_eq!(res.test, "hello world")
    }

    #[test]
    fn test_find_load() {
        let config = ConfigLoader::new("universal-config");
        let res: ConfigContents = config
            .with_config_dir("test_configs")
            .find_and_load()
            .unwrap();
        assert_eq!(res.test, "hello world")
    }
}