feat(client_config): add config root parsing with regex

- introduce regex-based parsing for config root strings
- support 'h', 'r', and 'c' prefixes for home, root, and crate paths
- add tests for parsing different config root types
This commit is contained in:
Jeremiah Russell
2025-10-16 11:00:25 +01:00
committed by Jeremiah Russell
parent 8ab89cdb0a
commit b17e72e6f3

View File

@@ -1,5 +1,9 @@
use std::{env, fmt::Display}; use std::{env, fmt::Display};
use lazy_regex::{Lazy, Regex, lazy_regex};
static ROOT_CONFIG: Lazy<Regex> = lazy_regex!(r"^(?P<class>[hrc]):(?P<path>.+)$");
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub enum ConfigRoot { pub enum ConfigRoot {
#[default] #[default]
@@ -28,16 +32,87 @@ impl Display for ConfigRoot {
impl ConfigRoot { impl ConfigRoot {
pub fn parse(s: &str) -> Self { pub fn parse(s: &str) -> Self {
if !s.is_empty() { log::debug!("parsing the string `{s}`");
match s.chars().nth(0) { let Some(captures) = ROOT_CONFIG.captures(s) else {
Some('h') => ConfigRoot::Home(s.to_string()), return ConfigRoot::None;
Some('r') => ConfigRoot::Root(s.to_string()), };
Some('c') => ConfigRoot::Crate(s.to_string()), log::debug!("found captures `{captures:?}`");
Some(_) => ConfigRoot::Crate(s.to_string()),
None => ConfigRoot::None, let path = String::from(if let Some(p) = captures.name("path") {
} p.as_str()
} else { } else {
ConfigRoot::None ""
});
log::debug!("set the path to `{path}`");
let Some(class) = captures.name("class") else {
return ConfigRoot::None;
};
log::debug!("found the class `{class:?}`");
match class.as_str() {
"h" => ConfigRoot::Home(path),
"r" => ConfigRoot::Root(path),
"c" => ConfigRoot::Crate(path),
_ => unreachable!(),
} }
} }
} }
enum ConfigRootError {}
#[cfg(test)]
mod tests {
use std::env;
use super::*;
use crate::test_utils::get_test_logger;
#[test]
fn test_parse_to_home() {
get_test_logger();
let input = "h:.cull-gmail".to_string();
log::debug!("Input set to: `{input}`");
let dir_part = input[2..].to_string();
let user_home = env::home_dir().unwrap();
let expected = user_home.join(dir_part).display().to_string();
assert_eq!(expected, ConfigRoot::parse(&input).to_string());
}
#[test]
fn test_parse_to_root() {
get_test_logger();
let input = "r:.cull-gmail".to_string();
log::debug!("Input set to: `{input}`");
let dir_part = input[2..].to_string();
let expected = format!("/{dir_part}");
assert_eq!(expected, ConfigRoot::parse(&input).to_string());
}
#[test]
fn test_parse_to_crate() {
get_test_logger();
let input = "c:.cull-gmail".to_string();
log::debug!("Input set to: `{input}`");
let expected = input[2..].to_string();
assert_eq!(expected, ConfigRoot::parse(&input).to_string());
}
#[test]
fn test_parse_to_none() {
get_test_logger();
let input = ".cull-gmail".to_string();
log::debug!("Input set to: `{input}`");
let expected = "".to_string();
assert_eq!(expected, ConfigRoot::parse(&input).to_string());
}
}