langtool: New command remove-ampersands

This commit is contained in:
Henrik Rydgård
2026-08-31 11:31:35 +02:00
parent 04a6166c90
commit 6ef95ebff7
2 changed files with 59 additions and 0 deletions
+19
View File
@@ -114,6 +114,10 @@ enum Command {
section: String,
key: String,
},
RemoveAmpersands {
section: String,
key: String,
},
ApplyRegex {
section: String,
key: String,
@@ -261,6 +265,15 @@ fn remove_linebreaks(target_ini: &mut IniFile, section: &str, key: &str) -> io::
Ok(())
}
fn remove_ampersands(target_ini: &mut IniFile, section: &str, key: &str) -> io::Result<()> {
if let Some(old_section) = target_ini.get_section_mut(section) {
old_section.remove_ampersands(key);
} else {
println!("No section {section}");
}
Ok(())
}
fn add_new_key(
target_ini: &mut IniFile,
section: &str,
@@ -1044,6 +1057,12 @@ fn execute_command(cmd: Command, ai: Option<&Ai>, dry_run: bool, verbose: bool)
} => {
remove_linebreaks(&mut target_ini, section, key).unwrap();
}
Command::RemoveAmpersands {
ref section,
ref key,
} => {
remove_ampersands(&mut target_ini, section, key).unwrap();
}
Command::ImportSingle {
filename: _,
ref section,
+40
View File
@@ -48,6 +48,24 @@ pub fn marked_same(comment: &str) -> bool {
comment.to_ascii_lowercase().starts_with("same")
}
#[cfg(test)]
mod tests {
use super::Section;
#[test]
fn remove_ampersands_removes_ampersands_from_values() {
let mut section = Section {
name: "Test".to_string(),
title_line: "[Test]".to_string(),
lines: vec!["Menu = &Open &Close # Example".to_string()],
};
section.remove_ampersands("Menu");
assert_eq!(section.lines[0], "Menu = Open Close # Example");
}
}
impl Section {
pub fn apply_regex(&mut self, key: &str, pattern: &str, replacement: &str) {
let re = Regex::new(pattern).unwrap();
@@ -103,6 +121,28 @@ impl Section {
}
}
pub fn remove_ampersands(&mut self, key: &str) {
for line in self.lines.iter_mut() {
let prefix = if let Some(pos) = line.find(" =") {
&line[0..pos]
} else {
continue;
};
if !prefix.trim().eq(key) {
continue;
}
if let Some((_, value)) = split_line(line) {
let (value_without_comment, comment) = split_comment(value);
let cleaned_value = value_without_comment.replace('&', "").trim().to_string();
if comment.is_empty() {
*line = format!("{} = {}", key, cleaned_value);
} else {
*line = format!("{} = {} # {}", key, cleaned_value, comment);
}
}
}
}
pub fn get_line(&self, key: &str) -> Option<String> {
for line in self.lines.iter() {
let prefix = if let Some(pos) = line.find(" =") {