Configuration can now be assembled from a directory.

This commit is contained in:
David Soulayrol
2022-08-21 11:33:14 +02:00
parent 827a9c1481
commit 23df2c017b

View File

@@ -1,6 +1,7 @@
extern crate serde_derive; extern crate serde_derive;
extern crate toml; extern crate toml;
use crate::lib::errors; use crate::lib::errors;
use std::collections::BTreeMap;
use std::collections::HashMap; use std::collections::HashMap;
use std::env; use std::env;
use std::net; use std::net;
@@ -67,7 +68,11 @@ impl Config {
p.push(&args[1]); p.push(&args[1]);
} }
let fd = fs::read_to_string(p).await.unwrap(); let fd = match p.is_dir() {
false => fs::read_to_string(p).await.unwrap(),
true => merge_directory(p).await.unwrap()
};
let mut config: Config = match toml::from_str(&fd) { let mut config: Config = match toml::from_str(&fd) {
Ok(c) => c, Ok(c) => c,
Err(e) => return Err(Box::new(e)), Err(e) => return Err(Box::new(e)),
@@ -125,3 +130,23 @@ impl Config {
map map
} }
} }
async fn merge_directory(dir_name: path::PathBuf) -> std::io::Result<String> {
let mut entries = fs::read_dir(dir_name).await?;
let mut chunks = BTreeMap::new();
/*
* Directory entries are first read and sorted with their filename.
* Order is important because keys must precede server tables.
*/
while let Some(entry) = entries.next_entry().await? {
let path = entry.file_name();
if path.to_str().unwrap().ends_with(".toml") {
if entry.file_type().await.unwrap().is_file() {
chunks.insert(path, fs::read_to_string(&entry.path()).await?);
}
}
}
Ok(chunks.values().fold(String::new(), |mut acc, chunk| { acc.push_str(chunk); acc }))
}