Skip to content

Commit

Permalink
refactor: simplify regex mod
Browse files Browse the repository at this point in the history
Adjusting to new config getters
  • Loading branch information
roosta committed Dec 13, 2024
1 parent 5a78d51 commit 3c633f7
Showing 1 changed file with 29 additions and 24 deletions.
53 changes: 29 additions & 24 deletions src/regex.rs
Original file line number Diff line number Diff line change
@@ -1,35 +1,40 @@
use crate::Config;
pub use regex::Regex;
use std::error::Error;
use std::collections::HashMap;

pub type Point = (Regex, String);
/// A compiled regex pattern and its corresponding replacement string
pub type Pattern = (Regex, String);

/// Holds compiled regex patterns for different window properties
#[derive(Debug)]
pub struct Compiled {
pub class: Vec<Point>,
pub instance: Vec<Point>,
pub name: Vec<Point>,
pub class: Vec<Pattern>,
pub instance: Vec<Pattern>,
pub name: Vec<Pattern>,
}

/// Compiles a single regex pattern from a key-value pair
fn compile_pattern((pattern, replacement): (&String, &String)) -> Result<Pattern, Box<dyn Error>> {
Ok((
Regex::new(pattern).map_err(|e| format!("Invalid regex pattern '{}': {}", pattern, e))?,
replacement.to_owned(),
))
}

fn compile((k, v): (&String, &String)) -> Result<Point, Box<dyn Error>> {
let re = Regex::new(&format!(r"{}", k))?;
Ok((re, v.to_owned()))
/// Compiles a collection of patterns from a HashMap
fn compile_patterns(patterns: &HashMap<String, String>) -> Result<Vec<Pattern>, Box<dyn Error>> {
patterns
.iter()
.map(|(k, v)| compile_pattern((k, v)))
.collect()
}

/// Parses the configuration into compiled regex patterns
pub fn parse_config(config: &Config) -> Result<Compiled, Box<dyn Error>> {
let classes = match config.aliases.class.iter().map(compile).collect() {
Ok(v) => v,
Err(e) => Err(e)?,
};
let instances = match config.aliases.instance.iter().map(compile).collect() {
Ok(v) => v,
Err(e) => Err(e)?,
};
let names = match config.aliases.name.iter().map(compile).collect() {
Ok(v) => v,
Err(e) => Err(e)?,
};
return Ok(Compiled {
class: classes,
instance: instances,
name: names,
});
Ok(Compiled {
class: compile_patterns(&config.aliases.class)?,
instance: compile_patterns(&config.aliases.instance)?,
name: compile_patterns(&config.aliases.name)?,
})
}

0 comments on commit 3c633f7

Please sign in to comment.