refactor(config): Centralize loading logic

This commit is contained in:
Ed Page 2019-08-07 10:05:06 -05:00
parent 3d4da686ad
commit ad4c6dcd77
2 changed files with 16 additions and 6 deletions

View file

@ -1,3 +1,5 @@
use std::io::Read;
pub trait ConfigSource {
/// Skip hidden files and directories.
fn ignore_hidden(&self) -> Option<bool> {
@ -43,6 +45,18 @@ pub struct Config {
}
impl Config {
pub fn from_file(path: &std::path::Path) -> Result<Self, failure::Error> {
let mut file = std::fs::File::open(path)?;
let mut s = String::new();
file.read_to_string(&mut s)?;
Self::from_toml(&s)
}
pub fn from_toml(data: &str) -> Result<Self, failure::Error> {
let content = toml::from_str(data)?;
Ok(content)
}
pub fn update(&mut self, source: &dyn ConfigSource) {
if let Some(source) = source.ignore_hidden() {
self.ignore_hidden = Some(source);

View file

@ -2,7 +2,6 @@
#[macro_use]
extern crate clap;
use std::io::Read;
use std::io::Write;
use structopt::StructOpt;
@ -45,7 +44,7 @@ struct Options {
#[structopt(short = "c", long = "config")]
/// Custom config file
custom_config: Option<String>,
custom_config: Option<std::path::PathBuf>,
#[structopt(long, raw(overrides_with = r#""check-filenames""#))]
/// Skip verifying spelling in file names.
@ -258,10 +257,7 @@ fn run() -> Result<i32, failure::Error> {
let mut config = config::Config::default();
if let Some(path) = options.custom_config.as_ref() {
let mut file = std::fs::File::open(path)?;
let mut s = String::new();
file.read_to_string(&mut s)?;
let custom: config::Config = toml::from_str(&s)?;
let custom = config::Config::from_file(path)?;
config.update(&custom);
}
config.update(&options);