需求:递归 原地 解压所有压缩文件
以前这种东西都用 python/shell 写
现在正在试着全面转向 rust 的技术栈 反正 rustup 安装也挺方便的(但比 go 还是麻烦了点
(好像设置 rust 和 rs 都没有代码高亮 凑活着看
```rs
use std::env;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::process::Command;
fn unar_file(path: &Path) -> io::Result<()> {
println!("UNAR: {}", path.display());
let parent_dir = path.parent().unwrap();
let filename = path.file_name().unwrap();
let output = Command::new("unar")
.current_dir(parent_dir)
.arg("-s")
.arg("-d")
.arg(filename)
.output();
match output {
Ok(res) => {
if !res.status.success() {
eprintln!("Error processing compressed file {:?}: {}", path, String::from_utf8_lossy(&res.stderr));
return Err(io::ErrorKind::Other.into());
}
}
Err(e) => {
eprintln!("Failed to execute unar for {:?}: {}", path, e);
}
}
Ok(())
}
fn is_compressed(path: &Path) -> bool {
if let Some(ext) = path.extension() {
if let Some(ext) = ext.to_str() {
let ext = ext.to_lowercase();
return ext == "zip" || ext == "rar" || ext == "7z";
}
}
false
}
fn process_compressed_files(path: &Path) -> io::Result<()> {
if !path.is_dir() {
return Err(io::Error::new(io::ErrorKind::Other, "Not a directory"));
}
println!("Processing directory: {}", path.display());
for entry in fs::read_dir(path)? {
let entry_path = entry?.path();
if entry_path.is_dir() {
process_compressed_files(&entry_path)?;
} else if is_compressed(entry_path.as_path()) {
unar_file(&entry_path).expect("UNAR Error.");
}
}
Ok(())
}
fn main() -> io::Result<()> {
let args: Vec<String> = env::args().collect();
let start_path = if args.len() > 1 {
PathBuf::from(args[1].as_str())
} else {
PathBuf::from(".")
};
if start_path.is_file() {
return unar_file(&start_path);
}
process_compressed_files(&start_path)?;
Ok(())
}
```
不知道粗制滥造的代码有没有什么问题 Rust 大佬请指正~ |
|