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
#![crate_name = "amethyst_config"]
#![warn(
missing_debug_implementations,
missing_docs,
rust_2018_idioms,
rust_2018_compatibility
)]
#![warn(clippy::all)]
#![allow(clippy::new_without_default)]
use std::{
error::Error,
fmt, io,
path::{Path, PathBuf},
};
use log::error;
use ron::{self, de::Error as DeError, ser::Error as SerError};
use serde::{Deserialize, Serialize};
#[derive(Debug)]
pub enum ConfigError {
File(io::Error),
Parser(DeError),
Serializer(SerError),
Extension(PathBuf),
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
ConfigError::File(ref err) => write!(f, "{}", err),
ConfigError::Parser(ref msg) => write!(f, "{}", msg),
ConfigError::Serializer(ref msg) => write!(f, "{}", msg),
ConfigError::Extension(ref path) => {
let found = match path.extension() {
Some(extension) => format!("{:?}", extension),
None => "a directory.".to_string(),
};
write!(
f,
"{}: Invalid path extension, expected \"ron\", got {}.",
path.display().to_string(),
found,
)
}
}
}
}
impl From<io::Error> for ConfigError {
fn from(e: io::Error) -> ConfigError {
ConfigError::File(e)
}
}
impl From<DeError> for ConfigError {
fn from(e: DeError) -> Self {
ConfigError::Parser(e)
}
}
impl From<SerError> for ConfigError {
fn from(e: SerError) -> Self {
ConfigError::Serializer(e)
}
}
impl Error for ConfigError {
fn description(&self) -> &str {
match *self {
ConfigError::File(_) => "Project file error",
ConfigError::Parser(_) => "Project parser error",
ConfigError::Serializer(_) => "Project serializer error",
ConfigError::Extension(_) => "Invalid extension or directory for a file",
}
}
fn cause(&self) -> Option<&dyn Error> {
match *self {
ConfigError::File(ref err) => Some(err),
_ => None,
}
}
}
pub trait Config
where
Self: Sized,
{
fn load<P: AsRef<Path>>(path: P) -> Self;
fn load_no_fallback<P: AsRef<Path>>(path: P) -> Result<Self, ConfigError>;
fn load_bytes(bytes: &[u8]) -> Result<Self, ConfigError>;
fn write<P: AsRef<Path>>(&self, path: P) -> Result<(), ConfigError>;
}
impl<T> Config for T
where
T: for<'a> Deserialize<'a> + Serialize + Default,
{
fn load<P: AsRef<Path>>(path: P) -> Self {
Self::load_no_fallback(path.as_ref()).unwrap_or_else(|e| {
if let Some(path) = path.as_ref().to_str() {
error!("Failed to load config file '{}': {}", path, e);
} else {
error!("Failed to load config: {}", e);
}
Self::default()
})
}
fn load_no_fallback<P: AsRef<Path>>(path: P) -> Result<Self, ConfigError> {
use std::{fs::File, io::Read};
let path = path.as_ref();
let content = {
let mut file = File::open(path)?;
let mut buffer = Vec::new();
file.read_to_end(&mut buffer)?;
buffer
};
if path.extension().and_then(std::ffi::OsStr::to_str) == Some("ron") {
Self::load_bytes(&content)
} else {
Err(ConfigError::Extension(path.to_path_buf()))
}
}
fn load_bytes(bytes: &[u8]) -> Result<Self, ConfigError> {
let mut de = ron::de::Deserializer::from_bytes(bytes)?;
let val = T::deserialize(&mut de)?;
de.end()?;
Ok(val)
}
fn write<P: AsRef<Path>>(&self, path: P) -> Result<(), ConfigError> {
use ron::ser::to_string_pretty;
use std::{fs::File, io::Write};
let s = to_string_pretty(self, Default::default())?;
File::create(path)?.write_all(s.as_bytes())?;
Ok(())
}
}