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
#![recursion_limit = "128"]
extern crate proc_macro;
#[macro_use]
extern crate quote;
extern crate syn;
use proc_macro::TokenStream;
#[proc_macro_derive(Config)]
pub fn config(input: TokenStream) -> TokenStream {
let input: syn::DeriveInput = syn::parse(input).unwrap();
let gen = impl_config(&input);
gen.into()
}
fn impl_config(ast: &syn::DeriveInput) -> quote::Tokens {
let name = &ast.ident;
quote! {
use std::path::Path;
impl Config for #name {
type ConfigStruct = #name;
fn from_file<T: AsRef<Path>>(file_path: T) -> ConfigResult<Self::ConfigStruct> {
use std::fs::File;
use std::io::Read;
use toml;
let mut file = File::open(file_path)?;
let mut content = String::new();
file.read_to_string(&mut content)?;
let config: Self::ConfigStruct = toml::from_str(&content)?;
Ok(config)
}
fn smart_load<T: AsRef<Path>>(file_paths: &[T]) -> ConfigResult<(Self::ConfigStruct, &Path)> {
for fp in file_paths {
let config = Self::from_file(fp);
if config.is_ok() { return Ok((config.unwrap(), fp.as_ref())) };
}
let failed_configs: Vec<String> = file_paths.iter().map(|x| x.as_ref().to_string_lossy().to_string()).collect();
Err(ConfigError::from_kind(ConfigErrorKind::NoSuitableConfigFound(failed_configs)))
}
fn save<T: AsRef<Path>>(&self, file_path: T) -> ConfigResult<()> {
use std::fs::File;
use std::io::Write;
use toml;
let mut file = File::create(file_path)?;
let content = toml::to_string_pretty(self)?;
file.write_all(content.as_bytes())?;
Ok(())
}
}
}
}