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::{ use std::{
fs::read_to_string,
env::{current_dir, var}, env::{current_dir, var},
path::Path path::Path
}; };
@ -9,7 +8,7 @@ use toml::{
map::Map map::Map
}; };
use crate::error; use crate::{ error, util };
pub struct Config { pub struct Config {
pub local: Option<Map<String, Value>>, pub local: Option<Map<String, Value>>,
@ -23,13 +22,7 @@ impl Config {
// initialize global config, if it exists // initialize global config, if it exists
let str_path_global = var("HOME").unwrap() + "/.config/open.toml"; let str_path_global = var("HOME").unwrap() + "/.config/open.toml";
let path_global = Path::new(&str_path_global); let path_global = Path::new(&str_path_global);
let global = let global = util::read_toml(path_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 };
// propagate up for local config, if it exists // propagate up for local config, if it exists
let cwd = current_dir().unwrap(); let cwd = current_dir().unwrap();
@ -37,14 +30,10 @@ impl Config {
let mut local = None; let mut local = None;
while let Some(parent) = path_local.parent() { while let Some(parent) = path_local.parent() {
let file_local = path_local.join(".open"); let file_local = path_local.join(".open");
if file_local.exists() { if let Some(toml) = util::read_toml(file_local.as_path()) {
if let Ok(raw) = read_to_string(file_local) {
if let Ok(Value::Table(toml)) = toml::from_str(&raw) {
local = Some(toml); local = Some(toml);
break; break;
} }
}
}
path_local = parent; 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. /// gets array entries with matching "match" values.
pub fn matches(macrosection: Array, to_match: String) -> Vec<Value> { 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() }).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
}