2020-11-06 04:18:47 +00:00
|
|
|
use std::{
|
|
|
|
fmt::Debug,
|
|
|
|
fs::File,
|
|
|
|
io::Read,
|
|
|
|
path::Path,
|
|
|
|
};
|
|
|
|
|
|
|
|
use serde::de::DeserializeOwned;
|
|
|
|
|
2020-11-19 01:45:42 +00:00
|
|
|
pub const CONFIG_PERMISSIONS_MODE: u32 = 33152;
|
|
|
|
|
|
|
|
fn load_inner <
|
|
|
|
T: DeserializeOwned
|
|
|
|
> (
|
|
|
|
mut f: File
|
|
|
|
) -> T {
|
2020-11-29 19:05:28 +00:00
|
|
|
let mut buffer = vec! [0_u8; 4096];
|
2020-11-19 01:45:42 +00:00
|
|
|
let bytes_read = f.read (&mut buffer).unwrap_or_else (|_| panic! ("Can't read config"));
|
|
|
|
buffer.truncate (bytes_read);
|
|
|
|
|
|
|
|
let config_s = String::from_utf8 (buffer).unwrap_or_else (|_| panic! ("Can't parse config as UTF-8"));
|
|
|
|
toml::from_str (&config_s).unwrap_or_else (|e| panic! ("Can't parse config as TOML: {}", e))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// For files that contain public-viewable information
|
|
|
|
|
|
|
|
pub fn load_public <
|
|
|
|
T: DeserializeOwned,
|
|
|
|
P: AsRef <Path> + Debug
|
|
|
|
> (
|
|
|
|
config_file_path: P
|
|
|
|
) -> T {
|
2020-11-25 00:16:14 +00:00
|
|
|
let f = File::open (&config_file_path).unwrap_or_else (|_| panic! ("Can't open {:?}", config_file_path));
|
2020-11-19 01:45:42 +00:00
|
|
|
load_inner (f)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// For files that may contain secrets and should have permissions or other
|
|
|
|
/// safeties checked
|
|
|
|
|
2020-11-06 04:18:47 +00:00
|
|
|
pub fn load <
|
|
|
|
T: DeserializeOwned,
|
|
|
|
P: AsRef <Path> + Debug
|
|
|
|
> (
|
|
|
|
config_file_path: P
|
|
|
|
) -> T {
|
2020-11-19 01:45:42 +00:00
|
|
|
use std::os::unix::fs::PermissionsExt;
|
|
|
|
|
2020-11-25 00:16:14 +00:00
|
|
|
let f = File::open (&config_file_path).unwrap_or_else (|_| panic! ("Can't open {:?}", config_file_path));
|
2020-11-06 04:18:47 +00:00
|
|
|
|
2020-11-19 01:45:42 +00:00
|
|
|
let mode = f.metadata ().unwrap ().permissions ().mode ();
|
|
|
|
assert_eq! (mode, CONFIG_PERMISSIONS_MODE, "Config file has bad permissions mode, it should be octal 0600");
|
|
|
|
|
|
|
|
load_inner (f)
|
2020-11-06 04:18:47 +00:00
|
|
|
}
|