-
Notifications
You must be signed in to change notification settings - Fork 14
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Adjusting to new config getters
- Loading branch information
Showing
1 changed file
with
29 additions
and
24 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)?, | ||
}) | ||
} |