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.

Create A Parent Directory For A File In Rust

Code

use std::fs;
use std::path::PathBuf;

// TODO: Figure out how to pass an error here with 
// `Error`` of some type

fn make_parent_dir_for_file(file_path: &PathBuf) -> Result<String, String> {
  match file_path.parent() {
    Some(parent_dir) => match fs::create_dir_all(parent_dir) {
      Ok(_) => Ok("Made the dir".to_string()),
      Err(e) => Err(e.to_string())
    },
    None => Err("Could not make directory".to_string())
  }
}

fn main() {
  let target_file = PathBuf::from("create/parent/test/index.html");
  match make_parent_dir(&target_file) {
    Ok(msg) => println!("{}", msg),
    Err(msg) => println!("{}", msg)
  }
}

Results

Made the dir
  • Update this so it checks if the directory exists before trying to create (which I think is a problem that's causing an error)