summaryrefslogtreecommitdiffstats
path: root/src/files.rs
blob: 93120d18c7f41cbdc0f59b39e3a294617483c7f0 (plain)
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
use std::cmp::{Ord, Ordering};
use std::error::Error;
use std::ops::Index;
use std::path::{Path, PathBuf};
use std::time::SystemTime;

use lscolors::LsColors;
use mime_detective;
use rayon::prelude::*;

lazy_static! {
    static ref COLORS: LsColors = LsColors::from_env().unwrap();
}

#[derive(PartialEq)]
pub struct Files {
    pub directory: File,
    pub files: Vec<File>,
    pub sort: SortBy,
    pub dirs_first: bool,
}

impl Index<usize> for Files {
    type Output = File;
    fn index(&self, pos: usize) -> &Self::Output {
        &self.files[pos]
    }
}

fn get_kind(file: &std::fs::DirEntry) -> Kind {
    let file = file.file_type().unwrap();
    if file.is_file() {
        return Kind::File;
    }
    if file.is_dir() {
        return Kind::Directory;
    }
    if file.is_symlink() {
        return Kind::Link;
    }
    Kind::Pipe
}

fn get_color(path: &Path, meta: &std::fs::Metadata) -> Option<lscolors::Color> {
    match COLORS.style_for_path_with_metadata(path, Some(&meta)) {
        Some(style) => style.clone().foreground,
        None => None,
    }
}

impl Files {
    pub fn new_from_path(path: &Path) -> Result<Files, Box<dyn Error>> {
        let direntries: Result<Vec<_>, _> = std::fs::read_dir(&path)?.collect();

        let files: Vec<_> = direntries?
            .par_iter()
            .map(|file| {
                //let file = file?;
                let name = file.file_name();
                let name = name.to_string_lossy();
                let kind = get_kind(&file);
                let path = file.path();
                let meta = file.metadata().unwrap();
                let size = meta.len() / 1024;
                let mtime = meta.modified().unwrap();

                let color = get_color(&path, &meta);
                File::new(&name, path, kind, size as usize, mtime, color)
            })
            .collect();

        let mut files = Files {
            directory: File::new_from_path(&path)?,
            files: files,
            sort: SortBy::Name,
            dirs_first: true,
        };

        files.sort();

        if files.files.len() == 0 {
            files.files = vec![File::new_placeholder(&path)?];
        }

        Ok(files)
    }

    pub fn sort(&mut self) {
        match self.sort {
            SortBy::Name => self
                .files
                .sort_by(|a, b| alphanumeric_sort::compare_str(&a.name, &b.name)),
            SortBy::Size => {
                self.files.sort_by(|a, b| {
                    if a.size == b.size {
                        return alphanumeric_sort::compare_str(&b.name, &a.name);
                    }
                    a.size.cmp(&b.size).reverse()
                });
            }
            SortBy::MTime => {
                self.files.sort_by(|a, b| {
                    if a.mtime == b.mtime {
                        return alphanumeric_sort::compare_str(&a.name, &b.name);
                    }
                    a.mtime.cmp(&b.mtime)
                });
            }
        };

        if self.dirs_first {
            self.files.sort_by(|a, b| {
                if a.is_dir() && !b.is_dir() {
                    Ordering::Less
                } else {
                    Ordering::Equal
                }
            });
        }
    }

    pub fn cycle_sort(&mut self) {
        self.sort = match self.sort {
            SortBy::Name => SortBy::Size,
            SortBy::Size => SortBy::MTime,
            SortBy::MTime => SortBy::Name,
        };
    }

    pub fn len(&self) -> usize {
        self.files.len()
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Kind {
    Directory,
    File,
    Link,
    Pipe,
    Placeholder
}

impl std::fmt::Display for SortBy {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        let text = match self {
            SortBy::Name => "name",
            SortBy::Size => "size",
            SortBy::MTime => "mtime",
        };
        write!(formatter, "{}", text)
    }
}

#[derive(Debug, Copy, Clone, PartialEq)]
pub enum SortBy {
    Name,
    Size,
    MTime,
}

#[derive(Debug, PartialEq, Clone)]
pub struct File {
    pub name: String,
    pub path: PathBuf,
    pub size: Option<usize>,
    pub kind: Kind,
    pub mtime: SystemTime,
    pub color: Option<lscolors::Color>,
    // owner: Option<String>,
    // group: Option<String>,
    // flags: Option<String>,
}

impl File {
    pub fn new(
        name: &str,
        path: PathBuf,
        kind: Kind,
        size: usize,
        mtime: SystemTime,
        color: Option<lscolors::Color>,
    ) -> File {
        File {
            name: name.to_string(),
            path: path,
            size: Some(size),
            kind: kind,
            mtime: mtime,
            color: color
            // owner: None,
            // group: None,
            // flags: None,
        }
    }

    pub fn new_from_path(path: &Path) -> Result<File, Box<Error>> {
        let pathbuf = path.to_path_buf();
        let name = path
            .file_name()
            .map(|name| name.to_string_lossy().to_string())
            .unwrap_or("/".to_string());

        let kind = Kind::Directory; //get_kind(&path);
        let meta = &path.metadata().unwrap();
        let size = meta.len() / 1024;
        let mtime = meta.modified().unwrap();
        let color = get_color(&path, meta);
        Ok(File::new(&name, pathbuf, kind, size as usize, mtime, color))
    }

    pub fn new_placeholder(path: &Path) -> Result<File, Box<Error>> {
        let mut file = File::new_from_path(path)?;
        file.name = "<empty>".to_string();
        file.kind = Kind::Placeholder;
        Ok(file)
    }

    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 get_mime(&self) -> Option<String> {
        let detective = mime_detective::MimeDetective::new().ok()?;
        let mime = detective.detect_filepath(&self.path).ok()?;
        Some(mime.type_().as_str().to_string())
    }

    pub fn grand_parent(&self) -> Option<PathBuf> {
        Some(self.path.parent()?.parent()?.to_path_buf())
    }

    pub fn is_dir(&self) -> bool {
        self.kind == Kind::Directory
    }

    pub fn read_dir(&self) -> Result<Files, Box<Error>> {
        match self.kind {
            Kind::Placeholder =>