-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.rs
53 lines (42 loc) · 1.43 KB
/
main.rs
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
use std::{env, error::Error, io, path::PathBuf};
use clap::{crate_authors, crate_version, Clap};
use humansize::{file_size_opts, FileSize};
use tokio::fs;
#[derive(Clap)]
#[clap(version = crate_version!(), author = crate_authors!())]
/// Calculate space usage of a directory tree
struct Opts {
/// Directory to start from (default = current directory)
dir: Option<PathBuf>,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let opts = Opts::parse();
let start_dir = match opts.dir {
Some(dir) => dir,
_ => env::current_dir()?,
};
let usage = calc_space_usage(start_dir.clone()).await?;
let human_usage = usage.file_size(file_size_opts::CONVENTIONAL)?;
println!("{}\t{}", human_usage, start_dir.display());
Ok(())
}
async fn calc_space_usage(path: PathBuf) -> Result<u64, io::Error> {
let mut meta_queue = vec![path];
let mut size = 0;
while let Some(path) = meta_queue.pop() {
let meta = fs::symlink_metadata(&path).await?;
let file_type = meta.file_type();
if file_type.is_symlink() {
// don't follow symlinks
} else if file_type.is_dir() {
let mut entries = fs::read_dir(&path).await?;
while let Some(entry) = entries.next_entry().await? {
meta_queue.push(entry.path());
}
} else if file_type.is_file() {
size += meta.len();
}
}
Ok(size)
}