Skip to main content

lx_cli/
reader.rs

1/// Handles directory traversal and gathering file metadata.
2use crate::dir_scan::{Stat, scan};
3use crate::file_entry::{FileEntry, Symlink};
4use std::collections::HashMap;
5use std::fs;
6use std::io;
7use std::path::{Path, PathBuf};
8use std::sync::atomic::{AtomicBool, Ordering};
9
10static REPORTED_ERRORS: AtomicBool = AtomicBool::new(false);
11
12/// Reports a problem with one entry on stderr and keeps listing; the exit status
13/// later reflects it, as with `ls`.
14pub(crate) fn report_error(message: std::fmt::Arguments<'_>) {
15    eprintln!("lx: {message}");
16    REPORTED_ERRORS.store(true, Ordering::Relaxed);
17}
18
19/// Whether any entry could not be read during this run.
20pub fn reported_errors() -> bool {
21    REPORTED_ERRORS.load(Ordering::Relaxed)
22}
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum MetadataMode {
26    Basic,
27    Full,
28}
29
30#[derive(Default)]
31struct UserGroupCache {
32    users: HashMap<u32, String>,
33    groups: HashMap<u32, String>,
34}
35
36pub fn read_target(
37    target_path: &Path,
38    show_hidden: bool,
39    metadata_mode: MetadataMode,
40) -> io::Result<Vec<FileEntry>> {
41    if fs::symlink_metadata(target_path)?.is_dir() {
42        return read_directory_entries(target_path, show_hidden, metadata_mode);
43    }
44
45    let mut cache = UserGroupCache::default();
46    Ok(vec![read_file_entry(
47        target_path,
48        metadata_mode,
49        &mut cache,
50    )?])
51}
52
53pub fn read_directory_entries(
54    target_path: &Path,
55    show_hidden: bool,
56    metadata_mode: MetadataMode,
57) -> io::Result<Vec<FileEntry>> {
58    let mut entries = Vec::new();
59    let mut cache = UserGroupCache::default();
60    let target_path = std::path::absolute(target_path)?;
61
62    scan(
63        &target_path,
64        |name| show_hidden || !is_hidden(name),
65        |entry| {
66            let entry = match entry {
67                Ok(entry) => entry,
68                Err(error) => {
69                    report_error(format_args!(
70                        "cannot read directory '{}': {error}",
71                        target_path.display()
72                    ));
73                    return;
74                }
75            };
76            let full_path = target_path.join(&entry.name);
77            match entry.stat {
78                Ok(stat) => entries.push(build_file_entry(
79                    entry.name,
80                    full_path,
81                    &stat,
82                    metadata_mode,
83                    &mut cache,
84                )),
85                Err(error) => report_error(format_args!(
86                    "cannot access '{}': {error}",
87                    full_path.display()
88                )),
89            }
90        },
91    )?;
92
93    Ok(entries)
94}
95
96pub(crate) fn read_entry(target_path: &Path, metadata_mode: MetadataMode) -> io::Result<FileEntry> {
97    let mut cache = UserGroupCache::default();
98    read_file_entry(target_path, metadata_mode, &mut cache)
99}
100
101fn read_file_entry(
102    target_path: &Path,
103    metadata_mode: MetadataMode,
104    cache: &mut UserGroupCache,
105) -> io::Result<FileEntry> {
106    let full_path = std::path::absolute(target_path)?;
107    let stat = Stat::from(&fs::symlink_metadata(&full_path)?);
108    let file_name = target_path
109        .file_name()
110        .unwrap_or(target_path.as_os_str())
111        .to_os_string();
112
113    Ok(build_file_entry(
114        file_name,
115        full_path,
116        &stat,
117        metadata_mode,
118        cache,
119    ))
120}
121
122fn build_file_entry(
123    path: std::ffi::OsString,
124    full_path: PathBuf,
125    stat: &Stat,
126    metadata_mode: MetadataMode,
127    cache: &mut UserGroupCache,
128) -> FileEntry {
129    let symlink = stat.is_symlink().then(|| {
130        let target = fs::read_link(&full_path).unwrap_or_else(|error| {
131            report_error(format_args!(
132                "cannot read symbolic link '{}': {error}",
133                full_path.display()
134            ));
135            PathBuf::new()
136        });
137        // Permission errors cannot tell us whether a target is broken.
138        let is_broken = fs::metadata(&full_path).is_err_and(|error| {
139            matches!(
140                error.raw_os_error(),
141                Some(libc::ENOENT | libc::ENOTDIR | libc::ELOOP)
142            )
143        });
144        Symlink { target, is_broken }
145    });
146    let (owner, group) = match metadata_mode {
147        MetadataMode::Basic => (String::new(), String::new()),
148        MetadataMode::Full => (cache.get_username(stat.uid), cache.get_groupname(stat.gid)),
149    };
150
151    FileEntry {
152        is_hidden: is_hidden(&path),
153        path,
154        full_path,
155        filesystem_identity: (stat.dev, stat.ino),
156        is_dir: stat.is_dir(),
157        is_executable: stat.is_file() && (stat.mode & 0o111) != 0,
158        mode: stat.mode,
159        size: stat.size,
160        size_incomplete: false,
161        modified: stat.modified,
162        owner,
163        group,
164        user_id: stat.uid,
165        group_id: stat.gid,
166        nlink: stat.nlink,
167        git_status: None,
168        symlink,
169    }
170}
171
172pub(crate) fn is_hidden(file_name: &std::ffi::OsStr) -> bool {
173    let bytes = file_name.as_encoded_bytes();
174    bytes.starts_with(b".") && bytes != b"." && bytes != b".."
175}
176
177impl UserGroupCache {
178    fn get_username(&mut self, uid: u32) -> String {
179        if let Some(username) = self.users.get(&uid) {
180            return username.clone();
181        }
182
183        let username = lookup_username(uid);
184        self.users.insert(uid, username.clone());
185        username
186    }
187
188    fn get_groupname(&mut self, gid: u32) -> String {
189        if let Some(groupname) = self.groups.get(&gid) {
190            return groupname.clone();
191        }
192
193        let groupname = lookup_groupname(gid);
194        self.groups.insert(gid, groupname.clone());
195        groupname
196    }
197}
198
199fn lookup_username(uid: u32) -> String {
200    // Try to get username from system, fallback to uid
201    #[cfg(unix)]
202    {
203        use std::ffi::CStr;
204        unsafe {
205            let passwd = libc::getpwuid(uid);
206            if !passwd.is_null() {
207                let name = CStr::from_ptr((*passwd).pw_name);
208                if let Ok(name_str) = name.to_str() {
209                    return name_str.to_string();
210                }
211            }
212        }
213    }
214    uid.to_string()
215}
216
217fn lookup_groupname(gid: u32) -> String {
218    // Try to get group name from system, fallback to gid
219    #[cfg(unix)]
220    {
221        use std::ffi::CStr;
222        unsafe {
223            let group = libc::getgrgid(gid);
224            if !group.is_null() {
225                let name = CStr::from_ptr((*group).gr_name);
226                if let Ok(name_str) = name.to_str() {
227                    return name_str.to_string();
228                }
229            }
230        }
231    }
232    gid.to_string()
233}