Skip to content

Commit

Permalink
refactor(config): Centralize loading logic
Browse files Browse the repository at this point in the history
  • Loading branch information
epage committed Aug 8, 2019
1 parent 3d4da68 commit ad4c6dc
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
14 changes: 14 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::io::Read;

pub trait ConfigSource {
/// Skip hidden files and directories.
fn ignore_hidden(&self) -> Option<bool> {
Expand Down Expand Up @@ -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);
Expand Down
8 changes: 2 additions & 6 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
#[macro_use]
extern crate clap;

use std::io::Read;
use std::io::Write;

use structopt::StructOpt;
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit ad4c6dc

Please sign in to comment.