rspack_style/util/
file.rs

1use std::ffi::OsString;
2use std::path::Path;
3
4///
5/// 返回命令行执行的目录
6///
7pub fn cmd_path() -> String {
8  std::env::current_dir()
9    .unwrap()
10    .into_os_string()
11    .into_string()
12    .unwrap()
13}
14
15///
16/// 返回合并路径
17/// 路径 a + b
18///
19pub fn path_join(basepath: &str, joinpath: &str) -> String {
20  Path::new(basepath)
21    .join(joinpath)
22    .into_os_string()
23    .into_string()
24    .unwrap()
25}
26
27///
28/// 返回 join += 命令行执行的目录
29///
30pub fn cmd_path_resolve(path: &str) -> String {
31  std::env::current_dir()
32    .unwrap()
33    .join(path)
34    .into_os_string()
35    .into_string()
36    .unwrap()
37}
38
39///
40/// 返回当前 workspace 下 同 cargo.toml 文件 package 路径中文件
41/// path -> join ./cargo.toml/../{path}
42///
43pub fn path_resolve(path: &str) -> String {
44  let work_cwd = env!("CARGO_MANIFEST_DIR");
45  let os_work_cwd = OsString::from(work_cwd);
46  Path::new(&os_work_cwd)
47    .join(path)
48    .into_os_string()
49    .into_string()
50    .unwrap()
51}
52
53///
54/// 执行安全的 读取 某路径文件
55///
56pub fn readfile(path: &str) -> Result<String, String> {
57  let filepath = Path::new(path);
58
59  if filepath.exists() {
60    if filepath.is_dir() {
61      return Err(format!(
62        "file is not file maybe is dir ?! filepath is{}",
63        path
64      ));
65    }
66    match std::fs::read_to_string(filepath) {
67      Ok(content) => Ok(content),
68      Err(ex) => Err(ex.to_string()),
69    }
70  } else {
71    Err(format!("file is not exists filepath is {}", path))
72  }
73}
74
75///
76/// 获取指定文件的路径
77/// 如果是路径 -> 直接返回该路径
78///
79pub fn get_dir(path_value: &str) -> Result<String, String> {
80  let path = Path::new(path_value);
81  if path.is_file() {
82    Ok(path.parent().unwrap().to_str().unwrap().to_string())
83  } else if path.is_dir() {
84    Ok(path_value.to_string())
85  } else {
86    Err(format!(
87      "path type is file or dir please check {}",
88      path_value
89    ))
90  }
91}