Better category find and replace

I didn't have to do it in two `replace` calls

Now I have to check if the rule has a or several corresponding
categories in the initial and final regex, find whether they have the
same amount of elements, and if so create rules that allow elements from
each category to be mapped 1:1
This commit is contained in:
Lucien Cartier-Tilet 2020-04-04 18:28:27 +02:00
parent 6fb1c287e0
commit 23e3acb182
Signed by: phundrak
GPG Key ID: BD7789E705CB8DCA

View File

@ -284,24 +284,26 @@ impl Settings {
RULESET_CURRENT_VERSION.to_string() RULESET_CURRENT_VERSION.to_string()
} }
// TODO make the return type a Result
fn update_rules(&self) -> Vec<(Regex, String)> { fn update_rules(&self) -> Vec<(Regex, String)> {
let mut rules = self.rules.clone(); let mut rules = self.rules.clone();
// TODO Optimize that shit
// TODO break categories in different rules
for (category, content) in &self.categories { for (category, content) in &self.categories {
let mut temp_rules: Vec<(Regex, String)> = Vec::new(); let mut temp_rules: Vec<(Regex, String)> = Vec::new();
for (from, to) in &rules { for (from, to) in &rules {
let from = Regex::new( let from = Regex::new(
from.to_string() from.to_string()
.replace( .replace(
category.as_str(), format!("%{}", category).as_str(),
format!("[{}]", content).as_str(), format!("[{}]", content).as_str(),
) )
.replace("%", "")
.as_str(), .as_str(),
); );
let to = to.to_string().replace( let to = to.to_string().replace(
category, format!("%{}", category).as_str(),
format!("[{}]", content).replace("%", "").as_str(), format!("[{}]", content).as_str(),
); );
temp_rules.push((from, to)); temp_rules.push((from, to));
} }
@ -334,8 +336,7 @@ impl Settings {
/// // set some input /// // set some input
/// let _output = settings.apply(input); /// let _output = settings.apply(input);
/// ``` /// ```
pub fn apply(&self, s: String) -> String { pub fn apply(&self, s: String) -> std::result::Result<String, String> {
// Replace all `%C`s by their equivalent
let rules = self.update_rules(); let rules = self.update_rules();
let mut s = s.clone(); let mut s = s.clone();
debug!("==============================================="); debug!("===============================================");
@ -345,7 +346,7 @@ impl Settings {
s = from.replace_all(&s, to.as_str()).to_string(); s = from.replace_all(&s, to.as_str()).to_string();
debug!("new: {}", s); debug!("new: {}", s);
} }
s Ok(s)
} }
} }