ptth/src/load_toml.rs

55 lines
1.4 KiB
Rust

use std::{
fmt::Debug,
fs::File,
io::Read,
path::Path,
};
use serde::de::DeserializeOwned;
pub const CONFIG_PERMISSIONS_MODE: u32 = 33152;
fn load_inner <
T: DeserializeOwned
> (
mut f: File
) -> T {
let mut buffer = vec! [0u8; 4096];
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 {
let mut f = File::open (&config_file_path).unwrap_or_else (|_| panic! ("Can't open {:?}", config_file_path));
load_inner (f)
}
/// For files that may contain secrets and should have permissions or other
/// safeties checked
pub fn load <
T: DeserializeOwned,
P: AsRef <Path> + Debug
> (
config_file_path: P
) -> T {
use std::os::unix::fs::PermissionsExt;
let mut f = File::open (&config_file_path).unwrap_or_else (|_| panic! ("Can't open {:?}", config_file_path));
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)
}