Refactor reading configuration file into a separate function

This allows for reusing it elsewhere (eg. for job configuration files)
This commit is contained in:
Kienan Stewart 2022-09-25 16:39:25 -04:00
parent 1bbebe76db
commit 514209dae2
1 changed files with 46 additions and 29 deletions

View File

@ -22,36 +22,13 @@ impl Conf {
} }
pub fn update_from_file(&mut self, path: &Path) { pub fn update_from_file(&mut self, path: &Path) {
let mut file = match std::fs::File::open(path) { let items = match read_conf_file(path) {
Err(why) => { Err(_) => return,
println!("Could not open file '{}': {}", path.display(), why); return; Ok(items) => items,
},
Ok(file) => file,
}; };
let mut content = String::new(); for item in items.iter() {
match file.read_to_string(&mut content) { let key = item.0.as_str();
Err(why) => println!("Could not read from file '{}': {}", path.display(), why), let value = item.1.as_str();
Ok(_) => (),
}
let lines = content.lines();
for line in lines {
if line.starts_with('#') {
continue;
}
let result = line.split_once('=');
if result.is_none() {
println!("Skipping configuration line '{}', no key-value delimiter (=) found", line);
continue;
}
let key = result.unwrap().0.trim();
let value = result.unwrap().1.trim();
if key.eq("") || value.eq("") {
println!("Skipping configuration line '{}', no key or value side is empty", line);
continue;
}
match key { match key {
"job_dir" => { "job_dir" => {
println!("{} changed from '{}' to '{}' by line in '{}'", println!("{} changed from '{}' to '{}' by line in '{}'",
@ -83,6 +60,46 @@ impl Conf {
} }
} }
pub fn read_conf_file(path: &Path) -> Result<std::vec::Vec<(String, String)>, &str> {
let mut file = match std::fs::File::open(path) {
Err(why) => {
println!("Could not open file '{}': {}", path.display(), why);
return Err("Could not open file");
},
Ok(file) => file,
};
let mut content = String::new();
match file.read_to_string(&mut content) {
Err(why) => {
println!("Could not read from file '{}': {}", path.display(), why);
return Err("Could not read file");
},
Ok(_) => (),
}
let mut results = std::vec::Vec::<(String, String)>::new();
let lines = content.lines();
for line in lines {
if line.starts_with('#') {
continue;
}
let result = line.split_once('=');
if result.is_none() {
println!("Skipping configuration line '{}', no key-value delimiter (=) found", line);
continue;
}
let key = result.unwrap().0.trim();
let value = result.unwrap().1.trim();
if key.eq("") || value.eq("") {
println!("Skipping configuration line '{}', no key or value side is empty", line);
continue;
}
results.push((key.to_string(), value.to_string()));
}
return Ok(results);
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {