summaryrefslogtreecommitdiffstats
path: root/src/modes/display/directory.rs
blob: 0b30a4d8b04b3a006752b6cc58e3ad611409b4af (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
use std::borrow::Borrow;
use std::collections::BTreeSet;
use std::fs::read_dir;
use std::path::Path;
use std::sync::Arc;

use anyhow::{Context, Result};

use crate::app::TabSettings;
use crate::io::git;
use crate::modes::{is_not_hidden, FileInfo, FileKind, FilterKind, SortKind, Users};
use crate::{impl_content, impl_index_to_index, impl_selectable, log_info};

/// Holds the information about file in the current directory.
/// We know about the current path, the files themselves, the selected index,
/// the "display all files including hidden" flag and the key to sort files.
pub struct Directory {
    /// The current path
    pub path: Arc<Path>,
    /// A vector of FileInfo with every file in current path
    pub content: Vec<FileInfo>,
    /// The index of the selected file.
    pub index: usize,
    used_space: u64,
}

impl Directory {
    /// Reads the paths and creates a new `PathContent`.
    /// Files are sorted by filename by default.
    /// Selects the first file if any.
    pub fn new(path: &Path, users: &Users, filter: &FilterKind, show_hidden: bool) -> Result<Self> {
        let path = Arc::from(path);
        let mut content = Self::files(&path, show_hidden, filter, users)?;
        let sort_kind = SortKind::default();
        sort_kind.sort(&mut content);
        let index: usize = 0;
        let used_space = get_used_space(&content);

        Ok(Self {
            path,
            content,
            index,
            used_space,
        })
    }

    pub fn change_directory(
        &mut self,
        path: &Path,
        settings: &TabSettings,
        users: &Users,
    ) -> Result<()> {
        self.content = Self::files(path, settings.show_hidden, &settings.filter, users)?;
        settings.sort_kind.sort(&mut self.content);
        self.index = 0;
        self.used_space = get_used_space(&self.content);
        self.path = Arc::from(path);
        Ok(())
    }

    fn files(
        path: &Path,
        show_hidden: bool,
        filter_kind: &FilterKind,
        users: &Users,
    ) -> Result<Vec<FileInfo>> {
        let mut files: Vec<FileInfo> = Self::create_dot_dotdot(path, users)?;
        if let Some(true_files) = files_collection(path, users, show_hidden, filter_kind, false) {
            files.extend(true_files);
        }
        Ok(files)
    }

    fn create_dot_dotdot(path: &Path, users: &Users) -> Result<Vec<FileInfo>> {
        let current = FileInfo::from_path_with_name(path, ".", users)?;
        let Some(parent) = path.parent() else {
            return Ok(vec![current]);
        };
        let parent = FileInfo::from_path_with_name(parent, "..", users)?;
        Ok(vec![current, parent])
    }

    /// Sort the file with current key.
    pub fn sort(&mut self, sort_kind: &SortKind) {
        sort_kind.sort(&mut self.content)
    }

    /// Calculates the size of the owner column.
    pub fn owner_column_width(&self) -> usize {
        let owner_size_btreeset: BTreeSet<usize> =
            self.iter().map(|file| file.owner.len()).collect();
        *owner_size_btreeset.iter().next_back().unwrap_or(&1)
    }

    /// Calculates the size of the group column.
    pub fn group_column_width(&self) -> usize {
        let group_size_btreeset: BTreeSet<usize> =
            self.iter().map(|file| file.group.len()).collect();
        *group_size_btreeset.iter().next_back().unwrap_or(&1)
    }

    /// Select the file from a given index.
    pub fn select_index(&mut self, index: usize) {
        if index < self.content.len() {
            self.index = index;
        }
    }

    /// Reset the current file content.
    /// Reads and sort the content with current key.
    /// Select the first file if any.
    pub fn reset_files(&mut self, settings: &TabSettings, users: &Users) -> Result<()> {
        self.content = Self::files(&self.path, settings.show_hidden, &settings.filter, users)?;
        self.sort(&SortKind::default());
        self.index = 0;
        Ok(())
    }

    /// Is the selected file a directory ?
    /// It may fails if the current path is empty, aka if nothing is selected.
    pub fn is_selected_dir(&self) -> Result<bool> {
        let fileinfo = self.selected().context("")?;
        match fileinfo.file_kind {
            FileKind::Directory => Ok(true),
            FileKind::SymbolicLink(true) => {
                let dest = std::fs::read_link(&fileinfo.path).unwrap_or_default();
                Ok(dest.is_dir())
            }
            _ => Ok(false),
        }
    }

    /// Human readable string representation of the space used by _files_
    /// in current path.
    /// No recursive exploration of directory.
    pub fn used_space(&self) -> String {
        human_size(self.used_space)
    }

    /// A string representation of the git status of the path.
    pub fn git_string(&self) -> Result<String> {
        git(&self.path)
    }

    /// Returns an iterator of the files (`FileInfo`) in content.
    #[inline]
    pub fn iter(&self) -> std::slice::Iter<'_, FileInfo> {
        self.content.iter()
    }

    /// Returns an enumeration of the files (`FileInfo`) in content.
    #[inline]
    pub fn enumerate(&self) -> Enumerate<std::slice::Iter<'_, FileInfo>> {
        self.iter().enumerate()
    }

    /// Returns the correct index jump target to a flagged files.
    fn find_jump_index(&self, jump_target: &Path) -> Option<usize> {
        self.content
            .iter()
            .position(|file| <Arc<Path> as Borrow<Path>>::borrow(&file.path) == jump_target)
    }

    /// Select the file from its path. Returns its index in content.
    pub fn select_file(&mut self, jump_target: &Path) -> usize {
        let index = self.find_jump_index(jump_target).unwrap_or_default();
        self.select_index(index);
        index
    }

    /// Returns a vector of paths from content
    pub fn paths(&self) -> Vec<&Path> {
        self.content
            .iter()
            .map(|fileinfo| fileinfo.path.borrow())
            .collect()
    }

    /// True iff the selected path is ".." which is the parent dir.
    pub fn is_dotdot_selected(&self) -> bool {
        let Some(selected) = &self.selected() else {
            return false;
        };
        let Some(parent) = self.path.parent() else {
            return false;
        };
        selected.path.as_ref() == parent
    }
}

impl_index_to_index!(FileInfo, Directory);
impl_selectable!(Directory);
impl_content!(FileInfo, Directory);

fn get_used_space(files: &[FileInfo]) -> u64 {
    files
        .iter()
        .filter(|f| !f.is_dir())
        .map(|f| f.true_size)
        .sum()
}

/// Creates an optional vector of fileinfo contained in a file.
/// Files are filtered by filterkind and the display hidden flag.
/// Returns None if there's no file.
pub fn files_collection(
    path: &Path,
    users: &Users,
    show_hidden: bool,
    filter_kind: &FilterKind,
    keep_dir: bool,
) -> Option<Vec<FileInfo>> {
    match read_dir(path) {
        Ok(read_dir) => Some(
            read_dir
                .filter_map(|direntry| direntry.ok())
                .filter(|direntry| show_hidden || is_not_hidden(direntry).unwrap_or(true))
                .filter_map(|direntry| FileInfo::from_direntry(