blob: db46f4d0fdde35590ec03538108713435a16540c (
plain)
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
|
pub mod general;
pub mod keymap;
pub mod mimetype;
pub mod option;
pub mod preview;
pub mod theme;
pub use self::general::AppConfig;
pub use self::keymap::*;
pub use self::mimetype::*;
pub use self::preview::*;
pub use self::theme::*;
use serde::de::DeserializeOwned;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use crate::error::JoshutoError;
use crate::error::JoshutoResult;
use crate::CONFIG_HIERARCHY;
pub trait TomlConfigFile {
fn get_config(file_name: &str) -> Self;
}
// searches a list of folders for a given file in order of preference
pub fn search_directories<P>(filename: &str, directories: &[P]) -> Option<PathBuf>
where
P: AsRef<Path>,
{
for path in directories.iter() {
let filepath = path.as_ref().join(filename);
if filepath.exists() {
return Some(filepath);
}
}
None
}
// parses a config file into its appropriate format
fn parse_to_config_file<T, S>(filename: &str) -> JoshutoResult<S>
where
T: DeserializeOwned,
S: From<T>,
{
match search_directories(filename, &CONFIG_HIERARCHY) {
Some(file_path) => {
let file_contents = fs::read_to_string(&file_path)?;
let config = toml::from_str::<T>(&file_contents)?;
Ok(S::from(config))
}
None => {
let error_kind = io::ErrorKind::NotFound;
let error = JoshutoError::new(
crate::error::JoshutoErrorKind::Io(error_kind),
"No config directory found".to_string(),
);
Err(error)
}
}
}
|