Skip to main content

xtask_kit/
fs.rs

1use std::fs;
2use std::path::Path;
3
4use anyhow::{Context, Result, bail};
5
6/// Ensure that `path` exists and is a regular file.
7pub fn ensure_file(path: impl AsRef<Path>) -> Result<()> {
8    let path = path.as_ref();
9    let metadata = fs::metadata(path).with_context(|| format!("stat {}", path.display()))?;
10    if metadata.is_file() {
11        Ok(())
12    } else {
13        bail!("missing file {}", path.display())
14    }
15}
16
17/// Ensure that `path` exists and is a directory.
18pub fn ensure_dir(path: impl AsRef<Path>) -> Result<()> {
19    let path = path.as_ref();
20    let metadata = fs::metadata(path).with_context(|| format!("stat {}", path.display()))?;
21    if metadata.is_dir() {
22        Ok(())
23    } else {
24        bail!("missing directory {}", path.display())
25    }
26}
27
28/// Create `path` and any missing parent directories.
29pub fn create_dir_all(path: impl AsRef<Path>) -> Result<()> {
30    let path = path.as_ref();
31    fs::create_dir_all(path).with_context(|| format!("create directory {}", path.display()))
32}
33
34/// Copy a file, creating the destination parent directory when needed.
35pub fn copy_file(from: impl AsRef<Path>, to: impl AsRef<Path>) -> Result<u64> {
36    let from = from.as_ref();
37    let to = to.as_ref();
38    if let Some(parent) = to.parent() {
39        create_dir_all(parent)?;
40    }
41    fs::copy(from, to).with_context(|| format!("copy {} -> {}", from.display(), to.display()))
42}
43
44/// Remove a file or directory tree if it exists.
45pub fn remove_path(path: impl AsRef<Path>) -> Result<()> {
46    let path = path.as_ref();
47    if !path.exists() {
48        return Ok(());
49    }
50    let metadata =
51        fs::symlink_metadata(path).with_context(|| format!("stat {}", path.display()))?;
52    if metadata.is_dir() {
53        fs::remove_dir_all(path).with_context(|| format!("remove directory {}", path.display()))
54    } else {
55        fs::remove_file(path).with_context(|| format!("remove file {}", path.display()))
56    }
57}
58
59/// Write UTF-8 text, creating the destination parent directory when needed.
60pub fn write_string(path: impl AsRef<Path>, content: impl AsRef<str>) -> Result<()> {
61    let path = path.as_ref();
62    if let Some(parent) = path.parent() {
63        create_dir_all(parent)?;
64    }
65    fs::write(path, content.as_ref()).with_context(|| format!("write {}", path.display()))
66}