pub fn replace_key(mut text: String, section: &str, key: &str, new_value: &str) -> String {
let mut in_section = false;
let mut new_lines = Vec::new();
for line in text.lines() {
let trimmed = line.trim();
if trimmed.starts_with('[') && trimmed.ends_with(']') {
in_section = trimmed == format!("[{}]", section);
new_lines.push(line.to_string());
continue;
}
if in_section && trimmed.starts_with(&format!("{key} =")) {
if new_value.parse::<i64>().is_ok() || new_value.parse::<f64>().is_ok() {
new_lines.push(format!("{key} = {}", new_value));
} else {
new_lines.push(format!("{key} = \"{}\"", new_value));
}
} else {
new_lines.push(line.to_string());
}
}
text.clear();
text.push_str(&new_lines.join("\n"));
text
}
pub fn uncomment_key(mut text: String, section: &str, key: &str) -> String {
let mut in_section = false;
let mut new_lines = Vec::new();
for line in text.lines() {
let trimmed = line.trim();
if trimmed.starts_with('[') && trimmed.ends_with(']') {
in_section = trimmed == format!("[{}]", section);
new_lines.push(line.to_string());
continue;
}
if in_section && trimmed.starts_with(&format!("# {key} =")) {
let mut string = line.to_string();
string.remove(0);
string.remove(0);
new_lines.push(string);
} else {
new_lines.push(line.to_string());
}
}
text.clear();
text.push_str(&new_lines.join("\n"));
text
}
pub fn uncomment_section(mut text: String, section: &str) -> String {
let mut new_lines = Vec::new();
for line in text.lines() {
let trimmed = line.trim();
if trimmed.starts_with(&format!("# [{section}")) && trimmed.ends_with(']') {
let mut string = line.to_string();
string.remove(0);
string.remove(0);
new_lines.push(string);
} else {
new_lines.push(line.to_string());
}
}
text.clear();
text.push_str(&new_lines.join("\n"));
text
}
pub fn comment_out_key(mut text: String, section: &str, key: &str) -> String {
let mut in_section = false;
let mut new_lines = Vec::new();
for line in text.lines() {
let trimmed = line.trim();
if trimmed.starts_with('[') && trimmed.ends_with(']') {
in_section = trimmed == format!("[{}]", section);
new_lines.push(line.to_string());
continue;
}
if in_section && trimmed.starts_with(&format!("{key} =")) {
new_lines.push(format!("# {}", trimmed));
} else {
new_lines.push(line.to_string());
}
}
text.clear();
text.push_str(&new_lines.join("\n"));
text
}
pub fn comment_out_section(mut text: String, section: &str) -> String {
let mut new_lines = Vec::new();
for line in text.lines() {
let trimmed = line.trim();
if trimmed.starts_with(&format!("[{section}")) && trimmed.ends_with(']') {
new_lines.push(format!("# {}", line));
} else {
new_lines.push(line.to_string());
}
}
text.clear();
text.push_str(&new_lines.join("\n"));
text
}