Skip to content

Commit

Permalink
feat(*): 删除指定目录下面的文件1.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
LeonRust committed Mar 24, 2022
0 parents commit 8e59272
Show file tree
Hide file tree
Showing 4 changed files with 367 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/target
288 changes: 288 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[package]
name = "rmf"
version = "1.0.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
clap = { version = "3.1.6", features = ["derive"] }
chrono = "0.4.19"
68 changes: 68 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
use std::{path::Path, time::{self, UNIX_EPOCH}, fs};

use chrono::Local;
use clap::Parser;

/// 删除指定路径下面的所有文件
#[derive(Parser, Debug)]
#[clap(
name = "rmf",
version = "1.0.0",
author = "作者: 技安 <[email protected]>",
about = "删除指定路径下面的所有文件, 帮助输入 `-h`",
long_about = None,
arg_required_else_help(true)
)]
struct Cli {
/// 要删除的文件上级路径
#[clap(short, long)]
path: String,

/// 保留最近文件的天数
#[clap(short, long, default_value = "1")]
days: u32,
}

fn main() {
let cli = Cli::parse();

let path = Path::new(&cli.path);
if !path.is_dir() {
println!("{} is not a directory", cli.path);
return;
}

// 开始时间
let start = time::Instant::now();

// 现在的时间
let timestamp = if cli.days > 0 {
Local::today().and_hms(0, 0, 0).timestamp() - ((cli.days as i64 - 1) * 24 * 60 * 60)
} else {
Local::now().timestamp() + 100
};

for dir_entry in path.read_dir()
.expect("Unable to read directory").
into_iter() {
if let Ok(dir_entry) = dir_entry {
if let Ok(metadata) = dir_entry.metadata() {
if let Ok(time) = metadata.modified() {
if let Ok(time) = time.duration_since(UNIX_EPOCH) {
if (time.as_secs() as i64) < timestamp {
if metadata.is_file() {
fs::remove_file(dir_entry.path()).expect("Unable to remove file");
} else if metadata.is_dir() {
fs::remove_dir_all(dir_entry.path()).expect("Unable to remove directory");
}
}
}
}
}
}
}

// 用时
let elapsed = start.elapsed();
println!("duration: {:?}", elapsed);
}

0 comments on commit 8e59272

Please sign in to comment.