fm84 0.41.0

A synthwave dual-pane TUI file manager
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
//! What a directory's listing is made of: each entry's row, the attributes and
//! owner shown for it, and the git branch and user@host shown above.

use super::*;

/// Permission bits as `ls -l` writes them. The mode comes from the metadata the
/// listing already holds, so this costs no extra syscall.
#[cfg(unix)]
fn format_attributes(metadata: &fs::Metadata, is_dir: bool, is_symlink: bool) -> String {
    use std::os::unix::fs::PermissionsExt;

    let kind = if is_symlink {
        'l'
    } else if is_dir {
        'd'
    } else {
        '-'
    };
    let mut text = String::with_capacity(10);
    text.push(kind);
    text.push_str(&mode_string(metadata.permissions().mode()));
    text
}

/// The nine permission bits as `ls -l` writes them, `rwxr-xr-x`. Each
/// triplet's execute slot doubles as the setuid/setgid/sticky flag, which
/// would otherwise be invisible. On any system: an archive keeps them too.
pub fn mode_string(mode: u32) -> String {
    let triplet = |shift: u32, special: u32, on: char| {
        let bits = mode >> shift;
        let execute = bits & 0o1 != 0;
        [
            if bits & 0o4 != 0 { 'r' } else { '-' },
            if bits & 0o2 != 0 { 'w' } else { '-' },
            match (mode & special != 0, execute) {
                (true, true) => on,
                (true, false) => on.to_ascii_uppercase(),
                (false, true) => 'x',
                (false, false) => '-',
            },
        ]
    };

    let mut text = String::with_capacity(9);
    text.extend(triplet(6, 0o4000, 's'));
    text.extend(triplet(3, 0o2000, 's'));
    text.extend(triplet(0, 0o1000, 't'));
    text
}

#[cfg(windows)]
fn format_attributes(metadata: &fs::Metadata, _is_dir: bool, is_symlink: bool) -> String {
    use std::os::windows::fs::MetadataExt;

    const READONLY: u32 = 0x0000_0001;
    const HIDDEN: u32 = 0x0000_0002;
    const SYSTEM: u32 = 0x0000_0004;
    const DIRECTORY: u32 = 0x0000_0010;
    const ARCHIVE: u32 = 0x0000_0020;

    let flags = metadata.file_attributes();
    let flag = |bit: u32, on: char| if flags & bit != 0 { on } else { '-' };
    let kind = if is_symlink { 'l' } else { flag(DIRECTORY, 'd') };

    [kind, flag(ARCHIVE, 'a'), flag(READONLY, 'r'), flag(HIDDEN, 'h'), flag(SYSTEM, 's')].iter().collect()
}

#[cfg(not(any(unix, windows)))]
fn format_attributes(_metadata: &fs::Metadata, _is_dir: bool, _is_symlink: bool) -> String {
    String::new()
}

/// Hidden the way the platform means it: a leading dot, or on Windows the
/// hidden attribute, which is what Explorer goes by.
#[cfg(windows)]
pub fn is_hidden(_name: &str, metadata: Option<&fs::Metadata>) -> bool {
    use std::os::windows::fs::MetadataExt;
    const HIDDEN: u32 = 0x0000_0002;
    metadata.is_some_and(|metadata| metadata.file_attributes() & HIDDEN != 0)
}

#[cfg(not(windows))]
pub fn is_hidden(name: &str, _metadata: Option<&fs::Metadata>) -> bool {
    name.starts_with('.')
}

/// The `..` row a listing starts with, anywhere but the root.
fn parent_row() -> Item {
    Item {
        name_os: OsString::from(".."),
        name_full: "..".to_string(),
        name: "..".to_string(),
        extension: String::new(),
        is_dir: true,
        is_symlink: false,
        size: String::new(),
        size_bytes: 0,
        modified_at: None,
        attributes: String::new(),
    }
}

/// A row for an entry, from what is known of it.
fn row(name_os: OsString, is_dir: bool, is_symlink: bool, size_bytes: u64, modified_at: Option<std::time::SystemTime>, attributes: String) -> Item {
    let name_full = name_os.to_string_lossy().into_owned();
    // Lossy like the name above, and for the same reason: a name that is
    // not valid UTF-8 still has to be shown as something. to_str() gave
    // None for those, which left the column blank.
    let as_path = Path::new(&name_os);
    let name = if is_dir { name_full.clone() } else { as_path.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default() };
    let extension = if is_dir { String::new() } else { as_path.extension().map(|e| e.to_string_lossy().into_owned()).unwrap_or_default() };
    let size_bytes = if is_dir { 0 } else { size_bytes };
    let size = if is_dir { "<DIR>".to_string() } else { format_size(size_bytes) };
    Item {
        name_os,
        name_full,
        name,
        extension,
        is_dir,
        is_symlink,
        size,
        size_bytes,
        modified_at,
        attributes,
    }
}

/// A row for a file found under the directory listed, named by its path
/// from there - `sub/notes.txt` - so that it is shown, sorted and found by
/// that, and every operation reaches it through `path_in` as any other.
fn flat_row(name_os: OsString, is_symlink: bool, size_bytes: u64, modified_at: Option<std::time::SystemTime>, attributes: String) -> Item {
    let mut item = row(name_os, false, is_symlink, size_bytes, modified_at, attributes);
    if let Some(dir) = Path::new(&item.name_os).parent().filter(|dir| !dir.as_os_str().is_empty()) {
        item.name = format!("{}{}{}", dir.to_string_lossy(), std::path::MAIN_SEPARATOR, item.name);
    }
    item
}

/// Ctrl+B: every file under `path`, however deep, in one list - `..` first,
/// the rest sorted as F11 says, so sorting by size finds what takes the
/// space. Directories are walked, not listed, and a link to one is not
/// followed; what is hidden is left out, and what is inside it, unless F11
/// shows hidden files. A directory that cannot be read is passed over, and
/// nothing in a filesystem the kernel makes up is gone into.
///
/// No more than FLAT_MAX files, the second value saying so when there were
/// more. `cancel`, set once nobody wants the listing, stops the walk.
pub fn load_flat_rows(path: &Path, options: &Options, cancel: &AtomicBool) -> Result<(Vec<Item>, bool), Error> {
    let mut children = Vec::new();
    if path.parent().is_some() {
        children.push(parent_row());
    }
    let mut truncated = false;
    let mut stack: Vec<(PathBuf, PathBuf, Option<u64>)> = vec![(path.to_path_buf(), PathBuf::new(), None)];
    let mut top = true;
    'walk: while let Some((dir, relative, parent_device)) = stack.pop() {
        let device = device_of(&dir);
        if !top && device != parent_device && is_pseudo_filesystem(&dir) {
            continue;
        }
        // Only the directory itself has to be readable.
        let entries = match read_dir(&dir) {
            Ok(entries) => entries,
            Err(e) if top => return Err(e),
            Err(_) => continue,
        };
        top = false;
        for entry in entries {
            if cancel.load(Ordering::Relaxed) {
                return Err(Error::new(ErrorKind::Interrupted, "stopped"));
            }
            let Ok(entry) = entry else { continue };
            let Ok(file_type) = entry.file_type() else { continue };
            let name = entry.file_name();
            let is_symlink = file_type.is_symlink();
            let metadata = if is_symlink { fs::metadata(entry.path()).or_else(|_| entry.metadata()).ok() } else { entry.metadata().ok() };
            if !options.show_hidden && is_hidden(&name.to_string_lossy(), metadata.as_ref()) {
                continue;
            }
            if file_type.is_dir() {
                stack.push((entry.path(), relative.join(&name), device));
                continue;
            }
            // A link to a directory is neither listed nor gone into.
            if metadata.as_ref().is_some_and(|metadata| metadata.is_dir()) {
                continue;
            }
            if children.len() >= crate::constants::FLAT_MAX + usize::from(path.parent().is_some()) {
                truncated = true;
                break 'walk;
            }
            let size_bytes = metadata.as_ref().map(|m| m.len()).unwrap_or(0);
            let modified_at = metadata.as_ref().and_then(|m| m.modified().ok());
            let attributes = metadata.as_ref().map(|metadata| format_attributes(metadata, false, is_symlink)).unwrap_or_default();
            children.push(flat_row(relative.join(&name).into_os_string(), is_symlink, size_bytes, modified_at, attributes));
        }
    }
    let sort_start = usize::from(path.parent().is_some());
    children[sort_start..].sort_by(|a, b| compare_rows(a, b, options));
    Ok((children, truncated))
}

/// Ctrl+B inside an archive: every file under `inner`, from the index.
pub fn archive_flat_rows(index: &crate::archive::Index, inner: &Path, options: &Options) -> Vec<Item> {
    use crate::archive::EntryKind;
    let hidden = |path: &Path| path.components().any(|part| part.as_os_str().as_encoded_bytes().starts_with(b"."));
    let mut children = vec![parent_row()];
    for at in index.subtree(inner) {
        let entry = index.entry(at);
        let Ok(relative) = entry.path.strip_prefix(inner) else { continue };
        if entry.kind == EntryKind::Dir || relative.as_os_str().is_empty() || (!options.show_hidden && hidden(relative)) {
            continue;
        }
        let kind = if entry.kind == EntryKind::Link { 'l' } else { '-' };
        let attributes = entry.mode.map(|mode| format!("{kind}{}", mode_string(mode))).unwrap_or_default();
        children.push(flat_row(relative.as_os_str().to_os_string(), entry.kind == EntryKind::Link, entry.size, entry.modified, attributes));
    }
    children[1..].sort_by(|a, b| compare_rows(a, b, options));
    children
}

/// The rows for the directory at `inner` in an archive, as a directory on the
/// disk lists: `..` first, which from the archive's root leads out of it, and
/// the rest sorted as F11 says. Its own files are hidden as a dot hides them.
pub fn archive_rows(index: &crate::archive::Index, inner: &Path, options: &Options) -> Vec<Item> {
    use crate::archive::EntryKind;
    let mut children = vec![parent_row()];
    for entry in index.children(inner) {
        let name_os = entry.name().to_os_string();
        if !options.show_hidden && name_os.as_encoded_bytes().starts_with(b".") {
            continue;
        }
        let is_dir = entry.kind == EntryKind::Dir;
        let is_symlink = entry.kind == EntryKind::Link;
        let kind = match entry.kind {
            EntryKind::Dir => 'd',
            EntryKind::Link => 'l',
            _ => '-',
        };
        let attributes = entry.mode.map(|mode| format!("{kind}{}", mode_string(mode))).unwrap_or_default();
        children.push(row(name_os, is_dir, is_symlink, entry.size, entry.modified, attributes));
    }
    children[1..].sort_by(|a, b| compare_rows(a, b, options));
    children
}

pub fn load_directory_rows(path: &Path, options: &Options) -> Result<Vec<Item>, Error> {
    let entries: Vec<_> = read_dir(path)?.filter_map(|entry| entry.ok()).collect();

    let has_parent = path.parent().is_some();
    let mut children = Vec::with_capacity(entries.len() + usize::from(has_parent));

    // Don't add ".." on root folder.
    if has_parent {
        children.push(parent_row());
    }

    // One metadata() call per entry (one stat syscall), two for a symlink
    for entry in &entries {
        let entry_path = entry.path();
        // file_type() comes from readdir's d_type - no syscall on Linux.
        let is_symlink = entry.file_type().map(|file_type| file_type.is_symlink()).unwrap_or(false);
        // DirEntry::metadata() describes the link itself, which would list a link
        // to a directory as a file: sorted among the files, sized in bytes and
        // impossible to enter. Follow it, and fall back to the link when the
        // target is missing so a broken link still lists as an ordinary entry.
        let metadata = if is_symlink { fs::metadata(&entry_path).or_else(|_| entry.metadata()).ok() } else { entry.metadata().ok() };
        let is_dir = metadata.as_ref().map(|m| m.is_dir()).unwrap_or(false);
        let name_os = entry.file_name();
        if !options.show_hidden && is_hidden(&name_os.to_string_lossy(), metadata.as_ref()) {
            continue;
        }
        let size_bytes = metadata.as_ref().map(|m| m.len()).unwrap_or(0);
        // Written out when drawn, in whichever format F11 names - and a
        // relative date has to be, or it would go stale between reloads.
        let modified_at = metadata.as_ref().and_then(|m| m.modified().ok());
        let attributes = metadata.as_ref().map(|metadata| format_attributes(metadata, is_dir, is_symlink)).unwrap_or_default();
        children.push(row(name_os, is_dir, is_symlink, size_bytes, modified_at, attributes));
    }

    // Sort items on already-computed fields (no stat syscalls during sort)
    let sort_start = usize::from(has_parent);
    children[sort_start..].sort_by(|a, b| compare_rows(a, b, options));

    Ok(children)
}

/// Directories before files whichever way the rest runs, unless F11 mixes
/// them in, then the chosen key, with the name settling ties so equal sizes or
/// dates still list steadily.
fn compare_rows(a: &Item, b: &Item, options: &Options) -> std::cmp::Ordering {
    use std::cmp::Ordering;

    if options.dirs_first {
        match (a.is_dir, b.is_dir) {
            (true, false) => return Ordering::Less,
            (false, true) => return Ordering::Greater,
            _ => {}
        }
    }

    let text = |a: &str, b: &str| if options.case_sensitive { a.cmp(b) } else { a.to_lowercase().cmp(&b.to_lowercase()) };
    let name = || text(&a.name_full, &b.name_full);
    let order = match options.sort_key {
        SortKey::Name => name(),
        SortKey::Extension => text(&a.extension, &b.extension).then_with(name),
        SortKey::Size => a.size_bytes.cmp(&b.size_bytes).then_with(name),
        SortKey::Modified => a.modified_at.cmp(&b.modified_at).then_with(name),
    };
    if options.sort_descending { order.reverse() } else { order }
}

/// The branch checked out in the repository `dir` is in, or the start of
/// the commit when none is. Read from the files, as a prompt does, rather
/// than by running git: up from `dir` to the first `.git`, a directory or,
/// in a worktree or submodule, a file naming one. None outside a repository.
pub fn git_branch(dir: &Path) -> Option<String> {
    for ancestor in dir.ancestors() {
        let dot_git = ancestor.join(".git");
        let Ok(metadata) = fs::metadata(&dot_git) else {
            continue;
        };
        let git_dir = if metadata.is_dir() {
            dot_git
        } else {
            let text = fs::read_to_string(&dot_git).ok()?;
            ancestor.join(text.trim().strip_prefix("gitdir:")?.trim())
        };
        let head = fs::read_to_string(git_dir.join("HEAD")).ok()?;
        let head = head.trim();
        return Some(match head.strip_prefix("ref:") {
            Some(reference) => {
                let reference = reference.trim();
                reference.strip_prefix("refs/heads/").unwrap_or(reference).to_string()
            }
            None => head.chars().take(7).collect(),
        });
    }
    None
}

/// Who fm84 runs as and on what machine, `colt@laserbeak`, and whether that
/// is root - worth seeing before a delete.
#[cfg(unix)]
pub fn user_at_host() -> (String, bool) {
    // SAFETY: geteuid cannot fail, and gethostname writes at most the length
    // it is given into a buffer of ours, NUL-terminated when it fits.
    let uid = unsafe { libc::geteuid() };
    let mut buffer = [0 as libc::c_char; 256];
    let host = if unsafe { libc::gethostname(buffer.as_mut_ptr(), buffer.len() - 1) } == 0 {
        // SAFETY: the last byte was never written, so the string ends by it.
        unsafe { std::ffi::CStr::from_ptr(buffer.as_ptr()) }.to_string_lossy().into_owned()
    } else {
        String::new()
    };
    // A domain on the end says nothing a glance needs.
    let host = host.split('.').next().unwrap_or_default().to_string();
    (format!("{}@{}", user_name(uid), host), uid == 0)
}

#[cfg(not(unix))]
pub fn user_at_host() -> (String, bool) {
    let variable = |name: &str| std::env::var(name).unwrap_or_default();
    (format!("{}@{}", variable("USERNAME"), variable("COMPUTERNAME")), false)
}

/// Bytes a copy of `path` writes. Every hard link is a file of its own to a
/// copy, so each is counted, unlike the size walk_dir_size shows.
pub fn calculate_dir_size(path: &Path) -> Result<u64, Error> {
    SizeWalk {
        cancel: &AtomicBool::new(false),
        found: &mut |_| {},
        linked: None,
    }
    .dir(path, None)
    .map(Option::unwrap_or_default)
}

/// An entry of an archive, as the archive keeps it. A directory's size is
/// what is in it, which the index knows without a walk.
fn describe_in_archive(path: &Path) -> Option<Description> {
    use crate::archive::EntryKind;
    let (index, at) = crate::archive::entry_at(path)?;
    let entry = index.entry(at);
    let kind = match entry.kind {
        EntryKind::Dir => 'd',
        EntryKind::Link => 'l',
        _ => '-',
    };
    Some(Description {
        size_bytes: Some(if entry.kind == EntryKind::Dir { index.size_of(&entry.path) } else { entry.size }),
        modified: entry.modified,
        owner: entry.owner.clone().unwrap_or_default(),
        // The one thing that stops it coming out, said where it is looked at.
        attributes: [entry.mode.map(|mode| format!("{kind}{}", mode_string(mode))), entry.encrypted.then(|| "encrypted".to_string())]
            .into_iter()
            .flatten()
            .collect::<Vec<_>>()
            .join(" "),
        link: entry.link.as_ref().map(|target| target.display().to_string()),
    })
}

/// Bytes in the files under `path`, links not followed. `found` is told each
/// file's size as it is reached, so a long walk can show how far it has got,
/// and `cancel` stops it between entries, which gives None.
///
/// Only `path` itself has to be readable. Anything inside that is not - a
/// directory locked to its owner, a file gone mid-walk - counts as nothing,
/// the way du carries on past what it cannot read rather than giving up.
///
/// As du counts, too: a file with several hard links once, however many of
/// them the walk passes, and nothing in a filesystem the kernel makes up -
/// /proc alone claims a file the size of all memory, and /sys thousands of
/// pages - so sizing / gives the disk's own size.
pub fn walk_dir_size(path: &Path, cancel: &AtomicBool, found: &mut dyn FnMut(u64)) -> Result<Option<u64>, Error> {
    // A directory inside an archive, whose index has the size already.
    if path.symlink_metadata().is_err()
        && let Some((index, at)) = crate::archive::entry_at(path)
    {
        let size = index.size_of(&index.entry(at).path);
        found(size);
        return Ok(Some(size));
    }
    SizeWalk {
        cancel,
        found,
        linked: Some(std::collections::HashSet::new()),
    }
    .dir(path, None)
}

struct SizeWalk<'a> {
    cancel: &'a AtomicBool,
    found: &'a mut dyn FnMut(u64),
    /// The hard-linked files met so far, by device and inode, when each is
    /// to be counted once. None counts every link.
    linked: Option<std::collections::HashSet<(u64, u64)>>,
}

impl SizeWalk<'_> {
    /// `parent_device` is the device of the directory `path` is in, None at
    /// the top. Only where the walk steps onto another device is it asked
    /// what the filesystem there is, so a walk within one costs nothing more.
    fn dir(&mut self, path: &Path, parent_device: Option<u64>) -> Result<Option<u64>, Error> {
        let device = device_of(path);
        if (parent_device.is_none() || device != parent_device) && is_pseudo_filesystem(path) {
            return Ok(Some(0));
        }
        let mut total = 0u64;
        for entry in read_dir(path)? {
            if self.cancel.load(Ordering::Relaxed) {
                return Ok(None);
            }
            let Ok(entry) = entry else { continue };
            // file_type() uses readdir's d_type on Linux - no extra stat syscall
            let Ok(file_type) = entry.file_type() else { continue };
            if file_type.is_dir() {
                match self.dir(&entry.path(), device) {
                    Ok(Some(size)) => total += size,
                    Ok(None) => return Ok(None),
                    Err(_) => {}
                }
            } else if let Ok(metadata) = entry.metadata()
                && self.first_sight(&metadata)
            {
                total += metadata.len();
                (self.found)(metadata.len());
            }
        }
        Ok(Some(total))
    }

    /// False for a file already counted under another of its names.
    #[cfg(unix)]
    fn first_sight(&mut self, metadata: &fs::Metadata) -> bool {
        use std::os::unix::fs::MetadataExt;
        match &mut self.linked {
            Some(linked) if metadata.nlink() > 1 => linked.insert((metadata.dev(), metadata.ino())),
            _ => true,
        }
    }

    #[cfg(not(unix))]
    fn first_sight(&mut self, _metadata: &fs::Metadata) -> bool {
        true
    }
}

#[cfg(unix)]
fn device_of(path: &Path) -> Option<u64> {
    use std::os::unix::fs::MetadataExt;
    path.symlink_metadata().ok().map(|metadata| metadata.dev())
}

#[cfg(not(unix))]
fn device_of(_path: &Path) -> Option<u64> {
    None
}

/// True for a filesystem the kernel makes up as it is read - procfs, sysfs
/// and their kin - whose sizes are no bytes on any disk.
#[cfg(target_os = "linux")]
fn is_pseudo_filesystem(path: &Path) -> bool {
    use std::os::unix::ffi::OsStrExt;
    const PSEUDO: [u32; 15] = [
        0x9fa0,      // proc
        0x6265_6572, // sysfs
        0x6462_6720, // debugfs
        0x7472_6163, // tracefs
        0x7363_6673, // securityfs
        0x0027_e0eb, // cgroup
        0x6367_7270, // cgroup2
        0xcafe_4a11, // bpf
        0x6165_676c, // pstore
        0xde5e_81e4, // efivarfs
        0x6265_6570, // configfs
        0x1cd1,      // devpts
        0x6573_5543, // fusectl
        0x4249_4e4d, // binfmt_misc
        0x1980_0202, // mqueue
    ];
    let Ok(c_path) = std::ffi::CString::new(path.as_os_str().as_bytes()) else {
        return false;
    };
    // SAFETY: c_path is a valid NUL-terminated string and stats is only read
    // back after statfs reports success.
    let kind = unsafe {
        let mut stats = std::mem::zeroed::<libc::statfs>();
        if libc::statfs(c_path.as_ptr(), &mut stats) != 0 {
            return false;
        }
        // The field's width differs between architectures; every magic
        // number fits in 32 bits.
        stats.f_type as u32
    };
    PSEUDO.contains(&kind)
}

#[cfg(not(target_os = "linux"))]
fn is_pseudo_filesystem(_path: &Path) -> bool {
    false
}

/// The parts of an entry the columns have no room for: its exact size, the
/// second on its timestamp, who owns it, and where it points if it is a link.
pub struct Description {
    pub size_bytes: Option<u64>,
    pub modified: Option<std::time::SystemTime>,
    pub owner: String,
    pub attributes: String,
    /// Where a symlink points. Listed but never shown until now, and it is the
    /// one thing about a link worth knowing.
    pub link: Option<String>,
}

/// Look one entry up. Costs a stat, a readlink for a link, and the owner's
/// name - which is why it is done when the cursor moves rather than on the way
/// to drawing a frame, and on a thread of its own, where a dead mount holds
/// up nothing.
pub fn describe(path: &Path, is_dir: bool) -> Option<Description> {
    let Ok(metadata) = fs::symlink_metadata(path) else {
        return describe_in_archive(path);
    };
    let is_symlink = metadata.file_type().is_symlink();
    // A link's own size is the length of the path it holds, which tells nobody
    // anything; follow it for the figure. A broken one has no figure at all,
    // and saying 31 bytes would be worse than saying nothing.
    let followed = if is_symlink { fs::metadata(path).ok() } else { None };
    let size_bytes = if is_symlink { followed.as_ref().map(|target| target.len()) } else { (!is_dir).then_some(metadata.len()) };

    Some(Description {
        size_bytes,
        modified: metadata.modified().ok(),
        owner: owner_of(&metadata),
        // The link's own bits, as ls -l writes them, not the target's.
        attributes: format_attributes(&metadata, is_dir, is_symlink),
        link: is_symlink.then(|| fs::read_link(path).ok()).flatten().map(|target| target.display().to_string()),
    })
}