From 970c6b3856d2c460957ae8faae6452acea090362 Mon Sep 17 00:00:00 2001 From: Valerie Date: Tue, 30 Jul 2024 09:30:39 -0400 Subject: [PATCH] moved toml file read to a helper function --- src/config.rs | 21 +++++---------------- src/util.rs | 23 ++++++++++++++++++++++- 2 files changed, 27 insertions(+), 17 deletions(-) diff --git a/src/config.rs b/src/config.rs index 18b90fc..f92e541 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,5 +1,4 @@ use std::{ - fs::read_to_string, env::{current_dir, var}, path::Path }; @@ -9,7 +8,7 @@ use toml::{ map::Map }; -use crate::error; +use crate::{ error, util }; pub struct Config { pub local: Option>, @@ -23,13 +22,7 @@ impl Config { // initialize global config, if it exists let str_path_global = var("HOME").unwrap() + "/.config/open.toml"; let path_global = Path::new(&str_path_global); - let global = - if path_global.exists() { - if let Ok(raw) = read_to_string(path_global) { - if let Ok(Value::Table(toml)) = toml::from_str(&raw) { Some(toml) } - else { None } - } else { None } - } else { None }; + let global = util::read_toml(path_global); // propagate up for local config, if it exists let cwd = current_dir().unwrap(); @@ -37,13 +30,9 @@ impl Config { let mut local = None; while let Some(parent) = path_local.parent() { let file_local = path_local.join(".open"); - if file_local.exists() { - if let Ok(raw) = read_to_string(file_local) { - if let Ok(Value::Table(toml)) = toml::from_str(&raw) { - local = Some(toml); - break; - } - } + if let Some(toml) = util::read_toml(file_local.as_path()) { + local = Some(toml); + break; } path_local = parent; diff --git a/src/util.rs b/src/util.rs index 1985b05..78bd552 100644 --- a/src/util.rs +++ b/src/util.rs @@ -1,5 +1,15 @@ +use std::{ + fs::read_to_string, + path::Path +}; -use toml::{ value::Array, Value }; +use toml::{ + self, + Value, + + map::Map, + value::Array, +}; /// gets array entries with matching "match" values. pub fn matches(macrosection: Array, to_match: String) -> Vec { @@ -14,3 +24,14 @@ pub fn matches(macrosection: Array, to_match: String) -> Vec { }).map(|value| value.to_owned()).collect() } +pub fn read_toml(path: &Path) -> Option> { + if path.exists() { + if let Ok(raw) = read_to_string(path) { + if let Ok(Value::Table(toml)) = toml::from_str(&raw) { + return Some(toml); + } + } + } + None +} +