Skip to main content

lx_cli/
file_entry.rs

1/// Core data structures (FileEntry and FileType) that represent files and its metadata.
2use crate::config::IconConfig;
3use crate::icon::FileIcon;
4use std::borrow::Cow;
5use std::ffi::OsString;
6use std::path::PathBuf;
7use std::time::SystemTime;
8
9const FILE_TYPE_MASK: u32 = libc::S_IFMT as u32;
10const FILE_TYPE_REGULAR: u32 = libc::S_IFREG as u32;
11const FILE_TYPE_DIRECTORY: u32 = libc::S_IFDIR as u32;
12const FILE_TYPE_SYMLINK: u32 = libc::S_IFLNK as u32;
13const FILE_TYPE_PIPE: u32 = libc::S_IFIFO as u32;
14const FILE_TYPE_SOCKET: u32 = libc::S_IFSOCK as u32;
15const FILE_TYPE_BLOCK_DEVICE: u32 = libc::S_IFBLK as u32;
16const FILE_TYPE_CHARACTER_DEVICE: u32 = libc::S_IFCHR as u32;
17
18#[derive(Debug, Clone)]
19pub struct FileEntry {
20    pub path: OsString,
21    /// Absolute listing path, kept separate from the formatted display name.
22    pub full_path: PathBuf,
23    /// Device and inode used to recognise system folders and configured paths.
24    pub filesystem_identity: (u64, u64),
25    pub is_dir: bool,
26    pub is_executable: bool,
27    pub is_hidden: bool,
28    pub mode: u32,
29    pub size: u64,
30    pub size_incomplete: bool,
31    pub modified: SystemTime,
32    pub owner: String,
33    pub group: String,
34    pub user_id: u32,
35    pub group_id: u32,
36    pub nlink: u64,
37    pub git_status: Option<crate::git::GitStatus>,
38    pub symlink: Option<Symlink>,
39}
40
41#[derive(Debug, Clone)]
42pub struct Symlink {
43    pub target: PathBuf,
44    pub is_broken: bool,
45}
46
47impl FileEntry {
48    fn get_file_icon(&self) -> FileIcon {
49        if self.symlink.is_some() {
50            FileIcon::Symlink
51        } else if self.is_dir {
52            FileIcon::Directory
53        } else if self.is_executable {
54            FileIcon::Executable
55        } else {
56            FileIcon::RegularFile
57        }
58    }
59
60    pub fn get_icon_custom<'a>(&self, config: &'a IconConfig) -> &'a str {
61        let file_icon = self.get_file_icon();
62        if let Some(icon) = file_icon.configured_icon(config) {
63            return icon;
64        }
65        if let Some(icon) = config.paths.get(&self.filesystem_identity) {
66            return icon;
67        }
68        if let Some(rule) = config.patterns.iter().find(|rule| rule.matches(self)) {
69            return &rule.icon;
70        }
71        if config.enabled && self.symlink.is_none() {
72            let name = self
73                .full_path
74                .file_name()
75                .unwrap_or(self.full_path.as_os_str());
76            let icon = if self.is_dir {
77                crate::icon::system_directory_icon(self.filesystem_identity)
78                    .or_else(|| crate::icon::directory_name_icon(name))
79            } else {
80                crate::icon::file_name_icon(name)
81            };
82            if let Some(icon) = icon {
83                return icon;
84            }
85        }
86        file_icon.icon(config)
87    }
88
89    pub(crate) fn style_role(&self) -> &'static str {
90        if let Some(link) = &self.symlink {
91            return if link.is_broken {
92                "filekinds.broken_symlink"
93            } else {
94                "filekinds.symlink"
95            };
96        }
97
98        match self.mode & FILE_TYPE_MASK {
99            FILE_TYPE_DIRECTORY => "filekinds.directory",
100            FILE_TYPE_REGULAR if self.is_executable => "filekinds.executable",
101            FILE_TYPE_REGULAR => "filekinds.regular",
102            FILE_TYPE_SYMLINK => "filekinds.symlink",
103            FILE_TYPE_PIPE => "filekinds.pipe",
104            FILE_TYPE_SOCKET => "filekinds.socket",
105            FILE_TYPE_BLOCK_DEVICE => "filekinds.block_device",
106            FILE_TYPE_CHARACTER_DEVICE => "filekinds.character_device",
107            _ => "filekinds.special",
108        }
109    }
110
111    pub fn get_file_type(&self) -> FileType {
112        if self.symlink.is_some() {
113            FileType::Symlink
114        } else if self.is_dir {
115            FileType::Directory
116        } else if self.is_executable {
117            FileType::Executable
118        } else {
119            FileType::RegularFile
120        }
121    }
122
123    pub fn display_name(&self) -> Cow<'_, str> {
124        let name = self.path.to_string_lossy();
125        match &self.symlink {
126            Some(link) => format!(
127                "{name} -> {}{}",
128                link.target.display(),
129                if link.is_broken { " [broken]" } else { "" }
130            )
131            .into(),
132            None => name,
133        }
134    }
135
136    pub fn format_permissions(&self) -> String {
137        self.permission_chars().iter().collect()
138    }
139
140    /// The `ls -l` permission string as characters, without allocating.
141    pub fn permission_chars(&self) -> [char; 10] {
142        let mode = self.mode;
143        let flag = |bit: u32, set: char| if mode & bit != 0 { set } else { '-' };
144        let execute = |bit: u32, special: u32, both: char, special_only: char| match (
145            mode & bit != 0,
146            mode & special != 0,
147        ) {
148            (true, true) => both,
149            (false, true) => special_only,
150            (true, false) => 'x',
151            (false, false) => '-',
152        };
153        [
154            self.file_type_marker(),
155            flag(0o400, 'r'),
156            flag(0o200, 'w'),
157            execute(0o100, u32::from(libc::S_ISUID), 's', 'S'),
158            flag(0o040, 'r'),
159            flag(0o020, 'w'),
160            execute(0o010, u32::from(libc::S_ISGID), 's', 'S'),
161            flag(0o004, 'r'),
162            flag(0o002, 'w'),
163            execute(0o001, u32::from(libc::S_ISVTX), 't', 'T'),
164        ]
165    }
166
167    fn file_type_marker(&self) -> char {
168        if self.symlink.is_some() {
169            return 'l';
170        }
171
172        match self.mode & FILE_TYPE_MASK {
173            FILE_TYPE_REGULAR => '-',
174            FILE_TYPE_DIRECTORY => 'd',
175            FILE_TYPE_SYMLINK => 'l',
176            FILE_TYPE_PIPE => 'p',
177            FILE_TYPE_SOCKET => 's',
178            FILE_TYPE_BLOCK_DEVICE => 'b',
179            FILE_TYPE_CHARACTER_DEVICE => 'c',
180            _ => '?',
181        }
182    }
183
184    pub fn format_size(&self) -> FormattedSize {
185        let (number, unit) = if self.size < 1024 {
186            (self.size.to_string(), SizeUnit::Bytes)
187        } else {
188            let mut value = self.size as f64 / 1024.0;
189            let mut unit = SizeUnit::Kilobytes;
190            // Pick the unit after rounding so 1048575 bytes reads 1.0M, not 1024.0K.
191            while (value * 10.0).round() / 10.0 >= 1024.0 && unit != SizeUnit::Terabytes {
192                value /= 1024.0;
193                unit = unit.next();
194            }
195            (format!("{value:.1}"), unit)
196        };
197        FormattedSize {
198            number,
199            unit,
200            incomplete: self.size_incomplete,
201        }
202    }
203}
204
205#[derive(Debug, Clone, Copy, PartialEq, Eq)]
206pub enum SizeUnit {
207    Bytes,
208    Kilobytes,
209    Megabytes,
210    Gigabytes,
211    Terabytes,
212}
213
214impl SizeUnit {
215    fn next(self) -> Self {
216        match self {
217            Self::Bytes => Self::Kilobytes,
218            Self::Kilobytes => Self::Megabytes,
219            Self::Megabytes => Self::Gigabytes,
220            Self::Gigabytes | Self::Terabytes => Self::Terabytes,
221        }
222    }
223
224    pub fn suffix(self) -> &'static str {
225        match self {
226            Self::Bytes => "B",
227            Self::Kilobytes => "K",
228            Self::Megabytes => "M",
229            Self::Gigabytes => "G",
230            Self::Terabytes => "T",
231        }
232    }
233
234    /// Theme roles for the number and the unit suffix.
235    pub fn roles(self) -> (&'static str, &'static str) {
236        match self {
237            Self::Bytes => ("size.bytes.number", "size.bytes.unit"),
238            Self::Kilobytes => ("size.kilobytes.number", "size.kilobytes.unit"),
239            Self::Megabytes => ("size.megabytes.number", "size.megabytes.unit"),
240            Self::Gigabytes => ("size.gigabytes.number", "size.gigabytes.unit"),
241            Self::Terabytes => ("size.terabytes.number", "size.terabytes.unit"),
242        }
243    }
244}
245
246/// A human-readable size, kept in parts so renderers can style each one.
247#[derive(Debug, Clone, PartialEq, Eq)]
248pub struct FormattedSize {
249    pub number: String,
250    pub unit: SizeUnit,
251    /// The size is a lower bound because some contents could not be read.
252    pub incomplete: bool,
253}
254
255impl std::fmt::Display for FormattedSize {
256    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
257        write!(formatter, "{}{}", self.number, self.unit.suffix())?;
258        if self.incomplete {
259            formatter.write_str("?")?;
260        }
261        Ok(())
262    }
263}
264
265#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
266pub enum FileType {
267    Directory,
268    Executable,
269    Symlink,
270    RegularFile,
271}
272
273#[cfg(test)]
274mod tests {
275    use super::*;
276
277    fn entry_with_size(size: u64) -> FileEntry {
278        FileEntry {
279            path: OsString::from("file"),
280            full_path: PathBuf::from("/file"),
281            filesystem_identity: (0, 0),
282            is_dir: false,
283            is_executable: false,
284            is_hidden: false,
285            mode: FILE_TYPE_REGULAR | 0o644,
286            size,
287            size_incomplete: false,
288            modified: SystemTime::UNIX_EPOCH,
289            owner: String::new(),
290            group: String::new(),
291            user_id: 0,
292            group_id: 0,
293            nlink: 1,
294            git_status: None,
295            symlink: None,
296        }
297    }
298
299    #[test]
300    fn sizes_pick_their_unit_after_rounding() {
301        const KIB: u64 = 1024;
302        for (size, expected) in [
303            (0, "0B"),
304            (1023, "1023B"),
305            (KIB, "1.0K"),
306            (KIB * KIB - 1, "1.0M"),
307            (KIB * KIB, "1.0M"),
308            (KIB * KIB * KIB - 1, "1.0G"),
309            (KIB.pow(4) - 1, "1.0T"),
310            (KIB.pow(4) * 3 / 2, "1.5T"),
311            (KIB.pow(5) * 2, "2048.0T"),
312        ] {
313            assert_eq!(entry_with_size(size).format_size().to_string(), expected);
314        }
315        let mut incomplete = entry_with_size(KIB * 3 / 2);
316        incomplete.size_incomplete = true;
317        let formatted = incomplete.format_size();
318        assert_eq!(formatted.number, "1.5");
319        assert_eq!(formatted.unit, SizeUnit::Kilobytes);
320        assert_eq!(formatted.to_string(), "1.5K?");
321    }
322}