Skip to main content

util_easy/
fs.rs

1//! Contains functions for working with the filesystem.
2
3use std::path::Path;
4
5/// Ensures that the directory at the given path exists, creating it if necessary.
6///
7/// # Arguments
8/// * `path` - The directory path to ensure exists.
9///
10/// # Returns
11/// * `Ok(())` if the directory exists or was successfully created.
12/// * `Err(std::io::Error)` if there was an error creating the directory.
13pub fn ensure_dir_exists(path: impl AsRef<Path>) -> std::io::Result<()> {
14    let path = path.as_ref();
15
16    std::fs::create_dir_all(path).map_err(|err| {
17        std::io::Error::new(
18            err.kind(),
19            format!("failed to create directory '{}': {err}", path.display()),
20        )
21    })
22}
23
24/// Ensures that the parent directory of the given path exists, creating it if necessary.
25///
26/// # Arguments
27/// * `path` - The file path whose parent directory should exist.
28///
29/// # Returns
30/// * `Ok(())` if the parent directory exists or was successfully created.
31/// * `Err(std::io::Error)` if there was an error creating the parent directory.
32pub fn ensure_parent_dir_exists(path: impl AsRef<Path>) -> std::io::Result<()> {
33    if let Some(parent) = path.as_ref().parent()
34        && !parent.as_os_str().is_empty()
35    {
36        ensure_dir_exists(parent)?;
37    }
38
39    Ok(())
40}
41
42/// Removes the file at the given path if it exists.
43///
44/// # Arguments
45/// * `path` - The file path to remove if it exists.
46///
47/// # Returns
48/// * `Ok(())` if the file was successfully removed or did not exist.
49/// * `Err(std::io::Error)` if there was an error removing the file.
50pub fn remove_file_if_exists(path: impl AsRef<Path>) -> std::io::Result<()> {
51    let path = path.as_ref();
52    match std::fs::remove_file(path) {
53        Ok(()) => Ok(()),
54        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
55        Err(err) => Err(std::io::Error::new(
56            err.kind(),
57            format!("failed to remove file '{}': {err}", path.display()),
58        )),
59    }
60}
61
62/// Removes the directory and its contents at the given path if it exists.
63///
64/// # Arguments
65/// * `path` - The directory path to remove if it exists.
66///
67/// # Returns
68/// * `Ok(())` if the directory was successfully removed or did not exist.
69/// * `Err(std::io::Error)` if there was an error removing the directory.
70pub fn remove_dir_all_if_exists(path: impl AsRef<Path>) -> std::io::Result<()> {
71    let path = path.as_ref();
72    match std::fs::remove_dir_all(path) {
73        Ok(()) => Ok(()),
74        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
75        Err(err) => Err(std::io::Error::new(
76            err.kind(),
77            format!("failed to remove directory '{}': {err}", path.display()),
78        )),
79    }
80}
81
82#[cfg(test)]
83mod tests;