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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
use crate::{parse::AutoPath, res, Error, Result};
use std::{
  borrow::Cow,
  fs,
  io::{self, Write as _},
  path::{Path, PathBuf},
};

#[cfg(feature = "encode")]
use crate::system::encode::auto_decode;

///
#[cfg(feature = "encode")]
pub fn auto_read<'a, P>(path: P) -> Result<String>
where
  P: AsRef<Path>,
{
  let data = fs::read(&path)?;
  Ok(auto_decode(&data).unwrap_or(String::from_utf8_lossy(&data).to_string()))
}

/// 主要针对兼容中文
#[cfg(feature = "encode")]
pub fn auto_read_gpk<P>(path: P) -> Result<String>
where
  P: AsRef<Path>,
{
  auto_read(path)
}

/// 树形目录,返回完整路径的字符串数组
pub fn tree_folder2<P>(dir_path: P) -> Result<Vec<PathBuf>>
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_folder2(&file_path)?;
          result.extend(sub_directory_files);
        } else {
          // 如果是文件,将完整路径添加到结果中
          result.push(file_path);
        }
      }
    }
  } else {
    result.push(dir_path.as_ref().to_path_buf())
  }
  Ok(result)
}
/// 树形目录,返回完整路径的字符串数组
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())
  }
}
/// 自动化转换路径
pub fn convert_path(path_str: &str) -> String {
  if cfg!(target_os = "windows") {
    path_str.replace('/', "\\")
  } else {
    String::from(path_str)
  }
}

/// 复制目录
pub fn auto_copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<()> {
  let from_path = from.as_ref();
  let to_path = to.as_ref();

  if from_path.is_file() {
    // 如果是文件,直接复制
    fs::copy(from_path, to_path)?;
  } else if from_path.is_dir() {
    to_path.auto_create_dir()?;
    // 遍历目录中的所有条目
    for entry in fs::read_dir(from_path)? {
      let entry = entry?;
      let from_entry_path = entry.path();
      let to_entry_path = to_path.join(
        from_entry_path
          .file_name()
          .ok_or(Error::Str("无法解析文件名".into()))?,
      );
      // 递归复制每个条目
      auto_copy(from_entry_path, to_entry_path)?;
    }
  } else {
    // 如果既不是文件也不是目录,返回错误
    return Err(res::Error::Io(io::Error::new(
      io::ErrorKind::Other,
      "Path is neither a file nor a directory",
    )));
  }
  Ok(())
}

/// 写入
fn write<'a>(
  path: &PathBuf,
  bytes: Cow<'a, [u8]>,
  is_sync: bool,
  is_append: bool,
) -> crate::Result<()> {
  if !is_append && path.exists() {
    path.auto_remove_file()?;
  }
  let mut f = fs::OpenOptions::new()
    .read(true)
    .write(true)
    .create(true)
    .append(is_append)
    .open(path)?;
  f.write_all(&bytes)?;
  if is_sync {
    f.sync_data()?;
  }
  Ok(())
}
/// 写入GBK格式
#[cfg(feature = "encode")]
pub fn write_gbk<'a>(
  path: &PathBuf,
  content: &'a str,
  is_sync: bool,
  is_append: bool,
) -> crate::Result<()> {
  let (bytes, _encode, had_errors) = encoding_rs::GBK.encode(content);
  if had_errors {
    return Err("写入GBK失败".into());
  } else {
    write(path, bytes, is_sync, is_append)
  }
}
/// 写入UTF-8格式
#[cfg(feature = "encode")]
pub fn write_utf8<'a>(
  path: &PathBuf,
  content: &'a str,
  is_sync: bool,
  is_append: bool,
) -> crate::Result<()> {
  let (bytes, _encode, had_errors) = encoding_rs::UTF_8.encode(content);
  if had_errors {
    return Err("写入UTF-8失败".into());
  } else {
    write(path, bytes, is_sync, is_append)
  }
}
/// 异步写入
#[cfg(feature = "tokio")]
pub mod async_runtime {
  use std::{borrow::Cow, path::PathBuf};
  use tokio::{fs, io::AsyncWriteExt as _};

  /// 异步写入
  async fn async_write<'a>(
    path: &PathBuf,
    bytes: Cow<'a, [u8]>,
    is_sync: bool,
    is_append: bool,
  ) -> crate::Result<()> {
    if !is_append && path.exists() {
      fs::remove_file(path).await?
    }
    let mut f = fs::OpenOptions::new()
      .read(true)
      .write(true)
      .create(true)
      .append(is_append)
      .open(path)
      .await?;
    f.write_all(&bytes).await?;
    if is_sync {
      f.sync_data().await?;
    }
    Ok(())
  }
  /// 异步写入GBK格式
  #[cfg(feature = "encode")]
  pub async fn async_write_gbk<'a>(
    path: &PathBuf,
    content: &'a str,
    is_sync: bool,
    is_append: bool,
  ) -> crate::Result<()> {
    let (bytes, _encode, had_errors) = encoding_rs::GBK.encode(content);
    if had_errors {
      return Err("异步写入GBK失败".into());
    } else {
      async_write(path, bytes, is_sync, is_append).await
    }
  }
  /// 异步写入UTF-8格式
  #[cfg(feature = "encode")]
  pub async fn async_write_utf8<'a>(
    path: &PathBuf,
    content: &'a str,
    is_sync: bool,
    is_append: bool,
  ) -> crate::Result<()> {
    let (bytes, _encode, had_errors) = encoding_rs::UTF_8.encode(content);
    if had_errors {
      return Err("异步写入UTF-8失败".into());
    } else {
      async_write(path, bytes, is_sync, is_append).await
    }
  }
}