mk_findandreplace/
lib.rs

1use glob::glob;
2use std::{collections::HashMap, fs, path::PathBuf};
3
4pub fn findanreplace(directory: &str, config_path: &PathBuf) {
5    println!("directory to process: {directory}");
6    let contents = fs::read_to_string(config_path).expect("File could not be read");
7    let config: HashMap<String, HashMap<String, String>> =
8        serde_yaml::from_str(&contents).expect("Failed to parse config");
9
10    for (k, v) in config.iter() {
11        println!("Processing glob: {k}");
12        for file in glob(&format!("{directory}/{k}")).expect("failed to read file glob") {
13            let path = match file {
14                Ok(path) => path,
15                Err(e) => {
16                    println!("{:?}", e);
17                    continue;
18                }
19            };
20            println!("Processing file: {}", path.display());
21            let mut file_contents = match fs::read_to_string(&path) {
22                Ok(str) => str,
23                Err(_) => continue,
24            };
25            for (b, a) in v.iter() {
26                file_contents = file_contents.replace(b, a);
27            }
28            if let Err(_) = fs::write(&path, file_contents) {
29                println!("Failed to write file");
30            };
31        }
32    }
33}