Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Update All Files Recursively In A Directory With A Give Extension With Rust

This is a very simple process that recursively loops over a directory and updates any files with a given extension:

Code

use std::fs;
use std::path::PathBuf;
use walkdir::WalkDir;

fn main() {
    update_files("some/path");
}

fn update_file(file_path: PathBuf) {
    let contents = fs::read_to_string(&file_path).unwrap();
    if !contents.contains("-- site:") {
        let mut new_contents = contents.trim_end().to_string();
        new_contents.push_str("\n-- site: aws\n");
        let _ = fs::write(file_path, new_contents);
    }
}

fn update_files(dir: &str) {
    for entry in WalkDir::new(dir) {
        let pb = entry.unwrap().into_path();
        if match pb.extension() {
            Some(extwrap) => match extwrap.to_str() {
                Some(ext) => match ext {
                    "org" => true,
                    _ => false,
                },
                None => false,
            },
            None => false,
        } {
            update_file(pb);
        }
    }
}

References

  • An efficient and cross platform implementation of recursive directory traversal