Skip to main content

ex_cli/fs/
total.rs

1use crate::cli::file::FileKind;
2use crate::cli::recent::RecentKind;
3use crate::config::Config;
4use crate::fs::file::File;
5use chrono::{DateTime, Utc};
6use std::cmp::max;
7
8const EXT_WIDTH: usize = 4; // (minimum width of ".txt")
9
10pub struct Total {
11    pub start_time: RecentKind<DateTime<Utc>>,
12    pub max_size: u64,
13    pub total_size: u64,
14    #[cfg(unix)]
15    pub user_width: usize,
16    #[cfg(unix)]
17    pub group_width: usize,
18    #[cfg(windows)]
19    pub ver_width: usize,
20    pub ext_width: usize,
21    pub num_files: usize,
22    pub num_dirs: usize,
23}
24
25impl Total {
26    pub fn new(start_time: RecentKind<DateTime<Utc>>) -> Self {
27        Self {
28            start_time,
29            max_size: 0,
30            total_size: 0,
31            #[cfg(unix)]
32            user_width: 0,
33            #[cfg(unix)]
34            group_width: 0,
35            #[cfg(windows)]
36            ver_width: 0,
37            ext_width: 0,
38            num_files: 0,
39            num_dirs: 0,
40        }
41    }
42
43    #[allow(unused_variables)]
44    pub fn from_files(
45        start_time: RecentKind<DateTime<Utc>>,
46        config: &Config,
47        files: &Vec<File>,
48    ) -> Self {
49        let mut total = Self::new(start_time);
50        #[cfg(unix)]
51        if config.show_owner() {
52            total.user_width = 1;
53            total.group_width = 1;
54        }
55        for file in files.iter() {
56            total.apply_file(file);
57        }
58        if total.ext_width > 0 {
59            total.ext_width = max(total.ext_width, EXT_WIDTH);
60        }
61        total
62    }
63
64    fn apply_file(&mut self, file: &File) {
65        self.max_size = max(self.max_size, file.file_size);
66        self.total_size += file.file_size;
67        #[cfg(unix)]
68        if let Some(user) = &file.owner_user {
69            self.user_width = max(self.user_width, user.len());
70        }
71        #[cfg(unix)]
72        if let Some(group) = &file.owner_group {
73            self.group_width = max(self.group_width, group.len());
74        }
75        #[cfg(windows)]
76        if let Some(ver) = &file.file_ver {
77            self.ver_width = max(self.ver_width, ver.len());
78        }
79        self.ext_width = max(self.ext_width, file.file_ext.len());
80        if file.file_type == FileKind::Dir {
81            self.num_dirs += 1;
82        } else {
83            self.num_files += 1;
84        }
85    }
86}