use crate::Result;
use std::{fs, path::Path};
#[cfg(feature = "encode")]
use encoding::{all::GBK, DecoderTrap, Encoding};
#[cfg(feature = "encode")]
pub fn auto_read_gpk<P>(path: P) -> Result<String>
where
P: AsRef<Path>,
{
let _res = String::from_utf8(fs::read(&path)?);
let res = _res.unwrap_or(
GBK.decode(&fs::read(path)?, DecoderTrap::Strict)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, format!("GPK解码失败{}", e)))?,
);
Ok(res)
}
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())
}
}