Line data Source code
1 : use anyhow::{Context, Result}; 2 : use regex::Regex; 3 : use std::{ 4 : fs::{read_to_string, write}, 5 : path::Path, 6 : }; 7 : 8 33 : pub fn find_and_replace<R>(path: &Path, re: &str, replacement: R) -> Result<()> 9 33 : where 10 33 : R: AsRef<str>, 11 33 : { 12 33 : let before = read_to_string(path) 13 33 : .with_context(|| format!("`read_to_string` failed for `{}`", path.to_string_lossy()))?; 14 33 : let re = Regex::new(re)?; 15 33 : let after = re.replace_all(&before, replacement.as_ref()); 16 33 : write(path, after.as_bytes()).map_err(Into::into) 17 33 : }