Skip to main content

zerolaunch_plugin_api/common/
dir_utils.rs

1use std::fs;
2use std::io;
3use std::path::Path;
4
5/// 跨平台目录工具函数。
6/// SDK 内部自足,不依赖 crate::core。
7pub struct DirUtils;
8
9impl DirUtils {
10    /// 读取一个目标目录,如果读到了,则返回数据,如果没有这个目录,则新建这个目录。
11    /// 参数:path - 目录路径。
12    /// 返回:目录条目迭代器,失败返回错误信息字符串。
13    pub fn read_dir_or_create<P: AsRef<Path>>(path: P) -> Result<fs::ReadDir, String> {
14        match fs::read_dir(&path) {
15            Ok(dir) => Ok(dir),
16            Err(e) if e.kind() == io::ErrorKind::NotFound => {
17                fs::create_dir_all(&path).map_err(|e| format!("无法创建目录: {}", e))?;
18                fs::read_dir(path).map_err(|e| format!("无法读取新创建的目录: {}", e))
19            }
20            Err(e) => Err(format!("无法读取目录: {}", e)),
21        }
22    }
23}