fix: more checks for config

this time i added a check for duplicate keys in the config
This commit is contained in:
Vladimir Rubin 2025-05-03 03:22:22 +03:00
parent d351555e35
commit 0bb27cd4ae
Signed by: vavakado
GPG key ID: CAB744727F36B524

View file

@ -1,6 +1,7 @@
//! hinoirisetr library //! hinoirisetr library
//! Contains core logic for computing temperature and gamma and applying settings. //! Contains core logic for computing temperature and gamma and applying settings.
use std::collections::HashSet;
use std::fs::File; use std::fs::File;
use std::io::{BufRead, BufReader}; use std::io::{BufRead, BufReader};
use std::path::Path; use std::path::Path;
@ -80,6 +81,7 @@ pub enum ConfigError {
InvalidGamma(String), InvalidGamma(String),
InvalidGammaBackend(String), InvalidGammaBackend(String),
InvalidTempBackend(String), InvalidTempBackend(String),
DuplicateKey(String),
} }
impl From<std::io::Error> for ConfigError { impl From<std::io::Error> for ConfigError {
@ -99,6 +101,8 @@ impl Config {
trace!("Config::load({path:?})"); trace!("Config::load({path:?})");
let mut config = Self::default(); // Start with default values let mut config = Self::default(); // Start with default values
let mut seen_keys = HashSet::new();
let config_file = File::open(path)?; let config_file = File::open(path)?;
let reader = BufReader::new(config_file); let reader = BufReader::new(config_file);
let mut current_section = String::new(); let mut current_section = String::new();
@ -113,12 +117,21 @@ impl Config {
trace!("line: {line}"); trace!("line: {line}");
if line.starts_with('[') && line.contains(']') { if line.starts_with('[') && line.contains(']') {
current_section = line[1..line.find(']').unwrap()].to_string(); current_section = line[1..line.find(']').unwrap()].to_string();
seen_keys.clear();
trace!("current_section: {current_section}"); trace!("current_section: {current_section}");
} else if let Some((key, value)) = line.split_once('=') { } else if let Some((key, value)) = line.split_once('=') {
trace!("key: {key}, value: {value}"); trace!("key: {key}, value: {value}");
let key_trimmed_string = key.trim().replace('"', ""); let key_trimmed_string = key.trim().replace('"', "");
let key_trimmed = key_trimmed_string.as_str(); let key_trimmed = key_trimmed_string.as_str();
// Check for duplicate key in current section
if seen_keys.contains(key_trimmed) {
return Err(ConfigError::DuplicateKey(format!(
"Duplicate key '{key_trimmed}' in section '{current_section}'",
)));
}
seen_keys.insert(key_trimmed.to_string());
let value = value.trim().replace('"', ""); let value = value.trim().replace('"', "");
match current_section.as_str() { match current_section.as_str() {
"" => match key_trimmed { "" => match key_trimmed {
@ -236,6 +249,8 @@ impl Config {
))); )));
} }
debug!("Seen: {:#?}", seen_keys);
Ok(config) Ok(config)
} }
} }