Skip to main content

os_xtask_utils/
dir.rs

1//! 操作目录。
2
3use std::{
4    fs,
5    io::{ErrorKind, Result},
6    path::Path,
7};
8
9/// 删除指定路径。
10///
11/// 如果返回 `Ok(())`,`path` 将不存在。
12pub fn rm(path: impl AsRef<Path>) -> Result<()> {
13    let path = path.as_ref();
14    if path.is_dir() {
15        fs::remove_dir_all(path)
16    } else if let Err(e) = fs::remove_file(path) {
17        if matches!(e.kind(), ErrorKind::NotFound) {
18            Ok(())
19        } else {
20            Err(e)
21        }
22    } else {
23        Ok(())
24    }
25}
26
27/// 创建 `path` 的父目录。
28#[inline]
29pub fn create_parent(path: impl AsRef<Path>) -> Result<()> {
30    match path.as_ref().parent() {
31        Some(parent) => fs::create_dir_all(parent),
32        None => Ok(()),
33    }
34}
35
36/// 清空 `path` 目录。
37///
38/// 如果返回 `Ok(())`,`path` 将是一个存在的空目录。
39#[inline]
40pub fn clear(path: impl AsRef<Path>) -> Result<()> {
41    rm(&path)?;
42    std::fs::create_dir_all(&path)
43}