1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
use crate::Result;
use std::{fs, path::Path};

/// 树形目录,返回完整路径的字符串数组
pub fn tree_folder<P>(dir_path: P) -> Result<Vec<String>>
where
  P: AsRef<Path>,
{
  let mut result = Vec::new();
  if dir_path.as_ref().is_dir() {
    // 递归处理目录
    let entries = fs::read_dir(dir_path)?;
    for entry in entries {
      if let Ok(entry) = entry {
        // 获取完整路径
        let file_path = entry.path();
        // 判断是文件还是目录
        if file_path.is_dir() {
          // 如果是目录,递归调用,并将结果合并到当前结果中
          let sub_directory_files = tree_folder(&file_path)?;
          result.extend(sub_directory_files);
        } else {
          // 如果是文件,将完整路径添加到结果中
          if let Some(file_name) = file_path.to_str() {
            result.push(file_name.to_string());
          }
        }
      }
    }
  } else {
    result.push(dir_path.as_ref().display().to_string())
  }
  Ok(result)
}

/// 重命名
pub fn rename_file<P, P2>(src: P, dst: P2) -> Result<()>
where
  P: AsRef<Path>,
  P2: AsRef<Path>,
{
  let src = src.as_ref();
  let dst = dst.as_ref();
  if src.exists() && src.is_file() {
    if dst.exists() && !dst.is_file() {
      Err(format!("目标已存在,并非文件格式 {}", dst.display()).into())
    } else {
      fs::rename(src, dst)?;
      if dst.exists() && dst.is_file() {
        Ok(())
      } else {
        Err(format!("源{} 目标移动失败 {}", src.display(), dst.display()).into())
      }
    }
  } else {
    Err(format!("原始缓存文件不存在 {}", src.display()).into())
  }
}