Skip to main content

src/create_parent_directory.rs

1use std::fs;
2use std::io;
3use std::path::PathBuf;
5/// Create the parent directory of a given path.
6///
7/// Example:
8///
9/// create_parent_directory("path/to/images/index.html")
10/// ~> creates "path/to/images/"
11///
12pub fn create_parent_directory(path: &PathBuf) -> io::Result<()> {
13 // Quoting from the Rust docs for PathBuf.parent() [1]:
14 //
15 // Returns None if the path terminates in a root or prefix,
16 // or if it’s the empty string.
17 //
18 // This function should only ever be called on paths to files, so
19 // .parent() will never return None.
20 //
21 // [1]: https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.parent
22 let parent_dir = path.parent().unwrap();
24 fs::create_dir_all(&parent_dir)
27#[cfg(test)]
28mod test_create_parent_directory {
29 use super::*;
30 use crate::test_utils::test_dir;
32 #[test]
33 fn it_creates_a_directory() {
34 let t = test_dir();
35 assert!(!t.exists());
37 let path = t.join("path/to/images").join("index.html");
38 assert!(create_parent_directory(&path).is_ok());
40 assert!(t.exists());
41 assert!(t.join("path/to/images").exists());
42 assert!(!path.exists());
43 }