Skip to main content

lx_cli/
reader.rs

1/// Handles directory traversal and gathering file metadata.
2use crate::file_entry::FileEntry;
3use std::collections::HashMap;
4use std::fs;
5use std::io;
6use std::os::unix::fs::{MetadataExt, PermissionsExt};
7use std::path::{Path, PathBuf};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum MetadataMode {
11    Basic,
12    Full,
13}
14
15#[derive(Debug, Clone)]
16pub struct DiscoveredEntry {
17    pub entry: FileEntry,
18    pub full_path: PathBuf,
19}
20
21#[derive(Default)]
22struct UserGroupCache {
23    users: HashMap<u32, String>,
24    groups: HashMap<u32, String>,
25}
26
27pub fn read_target(
28    target_path: &Path,
29    show_hidden: bool,
30    metadata_mode: MetadataMode,
31) -> io::Result<Vec<FileEntry>> {
32    if target_path.is_dir() {
33        return Ok(
34            read_directory_entries(target_path, show_hidden, metadata_mode)?
35                .into_iter()
36                .map(|entry| entry.entry)
37                .collect(),
38        );
39    }
40
41    let mut cache = UserGroupCache::default();
42    Ok(vec![read_file_entry(
43        target_path,
44        metadata_mode,
45        &mut cache,
46    )?])
47}
48
49pub fn read_directory_entries(
50    target_path: &Path,
51    show_hidden: bool,
52    metadata_mode: MetadataMode,
53) -> io::Result<Vec<DiscoveredEntry>> {
54    let mut entries = Vec::new();
55    let mut cache = UserGroupCache::default();
56
57    for entry in fs::read_dir(target_path)? {
58        let entry = entry?;
59        let file_name = entry.file_name();
60
61        if !show_hidden && is_hidden(&file_name) {
62            continue;
63        }
64
65        let full_path = entry.path();
66        let metadata = entry.metadata()?;
67        let entry = build_file_entry(file_name, &metadata, metadata_mode, &mut cache);
68
69        entries.push(DiscoveredEntry { entry, full_path });
70    }
71
72    Ok(entries)
73}
74
75pub(crate) fn read_entry(target_path: &Path, metadata_mode: MetadataMode) -> io::Result<FileEntry> {
76    let mut cache = UserGroupCache::default();
77    read_file_entry(target_path, metadata_mode, &mut cache)
78}
79
80fn read_file_entry(
81    target_path: &Path,
82    metadata_mode: MetadataMode,
83    cache: &mut UserGroupCache,
84) -> io::Result<FileEntry> {
85    let metadata = fs::metadata(target_path)?;
86    let file_name = target_path
87        .file_name()
88        .unwrap_or(target_path.as_os_str())
89        .to_os_string();
90
91    Ok(build_file_entry(file_name, &metadata, metadata_mode, cache))
92}
93
94fn build_file_entry(
95    path: std::ffi::OsString,
96    metadata: &fs::Metadata,
97    metadata_mode: MetadataMode,
98    cache: &mut UserGroupCache,
99) -> FileEntry {
100    let is_dir = metadata.is_dir();
101    let mode = metadata.permissions().mode();
102    let (owner, group) = match metadata_mode {
103        MetadataMode::Basic => (String::new(), String::new()),
104        MetadataMode::Full => (
105            cache.get_username(metadata.uid()),
106            cache.get_groupname(metadata.gid()),
107        ),
108    };
109
110    FileEntry {
111        is_hidden: is_hidden(&path),
112        path,
113        is_dir,
114        is_executable: !is_dir && (mode & 0o111) != 0,
115        mode,
116        size: metadata.len(),
117        modified: metadata
118            .modified()
119            .unwrap_or(std::time::SystemTime::UNIX_EPOCH),
120        owner,
121        group,
122        nlink: metadata.nlink(),
123    }
124}
125
126pub(crate) fn is_hidden(file_name: &std::ffi::OsStr) -> bool {
127    let bytes = file_name.as_encoded_bytes();
128    bytes.starts_with(b".") && bytes != b"." && bytes != b".."
129}
130
131impl UserGroupCache {
132    fn get_username(&mut self, uid: u32) -> String {
133        if let Some(username) = self.users.get(&uid) {
134            return username.clone();
135        }
136
137        let username = lookup_username(uid);
138        self.users.insert(uid, username.clone());
139        username
140    }
141
142    fn get_groupname(&mut self, gid: u32) -> String {
143        if let Some(groupname) = self.groups.get(&gid) {
144            return groupname.clone();
145        }
146
147        let groupname = lookup_groupname(gid);
148        self.groups.insert(gid, groupname.clone());
149        groupname
150    }
151}
152
153fn lookup_username(uid: u32) -> String {
154    // Try to get username from system, fallback to uid
155    #[cfg(unix)]
156    {
157        use std::ffi::CStr;
158        unsafe {
159            let passwd = libc::getpwuid(uid);
160            if !passwd.is_null() {
161                let name = CStr::from_ptr((*passwd).pw_name);
162                if let Ok(name_str) = name.to_str() {
163                    return name_str.to_string();
164                }
165            }
166        }
167    }
168    uid.to_string()
169}
170
171fn lookup_groupname(gid: u32) -> String {
172    // Try to get group name from system, fallback to gid
173    #[cfg(unix)]
174    {
175        use std::ffi::CStr;
176        unsafe {
177            let group = libc::getgrgid(gid);
178            if !group.is_null() {
179                let name = CStr::from_ptr((*group).gr_name);
180                if let Ok(name_str) = name.to_str() {
181                    return name_str.to_string();
182                }
183            }
184        }
185    }
186    gid.to_string()
187}