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
|
use std::ops::Index;
use std::error::Error;
use std::path::PathBuf;
use std::ffi::OsStr;
pub struct Files(Vec<File>);
impl Index<usize> for Files {
type Output = File;
fn index(&self, pos: usize) -> &Self::Output {
&self.0[pos]
}
}
impl Files {
pub fn new_from_path<S: AsRef<OsStr> + Sized>(path: S)
-> Result<Files, Box<dyn Error>>
where S: std::convert::AsRef<std::path::Path> {
let mut files = Vec::new();
for file in std::fs::read_dir(path)? {
let file = file?;
let name = file.file_name();
let name = name.to_string_lossy();
let path = file.path();
let size = file.metadata()?.len() / 1024;
files.push(File::new(&name, path, size as usize));
}
Ok(Files(files))
}
pub fn iter(&self) -> std::slice::Iter<File> {
self.0.iter()
}
pub fn len(&self) -> usize {
self.0.len()
}
}
#[derive(Debug)]
pub struct File {
pub name: String,
pub path: PathBuf,
pub size: Option<usize>,
// owner: Option<String>,
// group: Option<String>,
// flags: Option<String>,
// ctime: Option<u32>,
// mtime: Option<u32>,
}
impl File {
pub fn new(name: &str, path: PathBuf, size: usize) -> File {
File {
name: name.to_string(),
path: path,
size: Some(size),
// owner: None,
// group: None,
// flags: None,
// ctime: None,
// mtime: None
}
}
pub fn calculate_size(&self) -> (usize, String) {
let mut unit = 0;
let mut size = self.size.unwrap();
while size > 1024 {
size /= 1024;
unit += 1;
}
let unit = match unit {
0 => "",
1 => " KB",
2 => " GB",
3 => " TB",
4 => "wtf are you doing",
_ => ""
}.to_string();
(size, unit)
}
pub fn grand_parent(&self) -> Option<PathBuf> {
Some(self.path.parent()?.parent()?.to_path_buf())
}
pub fn path(&self) -> PathBuf {
self.path.clone()
}
}
|