moved toml file read to a helper function

This commit is contained in:
Valerie Wolfe 2024-07-30 09:30:39 -04:00
parent 0010e07366
commit 970c6b3856
2 changed files with 27 additions and 17 deletions

View file

@ -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<Map<String, Value>>,
@ -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,14 +30,10 @@ 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) {
if let Some(toml) = util::read_toml(file_local.as_path()) {
local = Some(toml);
break;
}
}
}
path_local = parent;
}

View file

@ -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<Value> {
@ -14,3 +24,14 @@ pub fn matches(macrosection: Array, to_match: String) -> Vec<Value> {
}).map(|value| value.to_owned()).collect()
}
pub fn read_toml(path: &Path) -> Option<Map<String, Value>> {
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
}