1use std::path::{Path, PathBuf};
21use std::time::UNIX_EPOCH;
22
23use crate::{Error, Result};
24
25fn io_err(op: &'static str, source: std::io::Error) -> Error {
28 Error::io(op, source)
29}
30
31fn sort_paths(paths: &mut [PathBuf]) {
34 paths.sort_unstable();
35}
36
37fn glob_match(pattern: &[u8], name: &[u8]) -> bool {
44 let mut p = 0usize;
45 let mut n = 0usize;
46 let mut star_p = usize::MAX;
47 let mut star_n = 0usize;
48
49 while n < name.len() {
50 if p < pattern.len() && (pattern[p] == name[n] || pattern[p] == b'?') {
51 p += 1;
52 n += 1;
53 } else if p < pattern.len() && pattern[p] == b'*' {
54 star_p = p;
55 p += 1;
56 star_n = n;
57 } else if star_p != usize::MAX {
58 p = star_p + 1;
59 star_n += 1;
60 n = star_n;
61 } else {
62 return false;
63 }
64 }
65 while p < pattern.len() && pattern[p] == b'*' {
66 p += 1;
67 }
68 p == pattern.len()
69}
70
71pub struct Filesystem;
85
86impl Filesystem {
87 pub fn exists(path: &Path) -> bool {
91 path.exists()
92 }
93
94 pub fn is_file(path: &Path) -> bool {
96 path.is_file()
97 }
98
99 pub fn is_directory(path: &Path) -> bool {
101 path.is_dir()
102 }
103
104 pub fn get_file_size(path: &Path) -> Result<u64> {
106 let meta = std::fs::metadata(path).map_err(|e| io_err("get_file_size", e))?;
107 Ok(meta.len())
108 }
109
110 pub fn get_last_modified(path: &Path) -> Result<i64> {
115 let meta = std::fs::metadata(path).map_err(|e| io_err("get_last_modified", e))?;
116 let modified = meta
117 .modified()
118 .map_err(|e| io_err("get_last_modified", e))?;
119 let secs = modified
120 .duration_since(UNIX_EPOCH)
121 .map(|d| d.as_secs() as i64)
122 .unwrap_or_else(|e| -(e.duration().as_secs() as i64));
123 Ok(secs)
124 }
125
126 pub fn create_directory(path: &Path) -> Result<()> {
130 match std::fs::create_dir(path) {
131 Ok(()) => Ok(()),
132 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists && path.is_dir() => Ok(()),
133 Err(e) => Err(io_err("create_directory", e)),
134 }
135 }
136
137 pub fn create_directories(path: &Path) -> Result<()> {
140 std::fs::create_dir_all(path).map_err(|e| io_err("create_directories", e))
141 }
142
143 pub fn remove_file(path: &Path) -> Result<()> {
145 match std::fs::remove_file(path) {
146 Ok(()) => Ok(()),
147 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
148 Err(e) => Err(io_err("remove_file", e)),
149 }
150 }
151
152 pub fn remove_directory(path: &Path, recursive: bool) -> Result<()> {
158 if !path.exists() {
159 return Ok(());
160 }
161 if recursive {
162 std::fs::remove_dir_all(path).map_err(|e| io_err("remove_directory", e))
163 } else {
164 std::fs::remove_dir(path).map_err(|e| io_err("remove_directory", e))
165 }
166 }
167
168 pub fn copy(from: &Path, to: &Path) -> Result<()> {
174 if from.is_dir() {
175 return Self::create_directories(to);
176 }
177 if let Some(parent) = to.parent()
178 && !parent.as_os_str().is_empty()
179 {
180 Self::create_directories(parent)?;
181 }
182 std::fs::copy(from, to)
183 .map(|_| ())
184 .map_err(|e| io_err("copy", e))
185 }
186
187 pub fn move_path(from: &Path, to: &Path) -> Result<()> {
191 if let Some(parent) = to.parent()
192 && !parent.as_os_str().is_empty()
193 {
194 Self::create_directories(parent)?;
195 }
196 std::fs::rename(from, to).map_err(|e| io_err("move_path", e))
197 }
198
199 pub fn list_files(dir: &Path, extension: &str) -> Result<Vec<PathBuf>> {
207 if !dir.is_dir() {
208 return Err(Error::not_found(format!(
209 "directory does not exist: {}",
210 dir.display()
211 )));
212 }
213 let mut files = Vec::new();
214 for entry in std::fs::read_dir(dir).map_err(|e| io_err("list_files", e))? {
215 let entry = entry.map_err(|e| io_err("list_files", e))?;
216 let path = entry.path();
217 if !path.is_file() {
218 continue;
219 }
220 if extension.is_empty()
221 || path
222 .extension()
223 .and_then(|e| e.to_str())
224 .map(|e| format!(".{e}") == extension)
225 .unwrap_or(false)
226 {
227 files.push(path);
228 }
229 }
230 sort_paths(&mut files);
231 Ok(files)
232 }
233
234 pub fn list_directories(dir: &Path) -> Result<Vec<PathBuf>> {
237 if !dir.is_dir() {
238 return Err(Error::not_found(format!(
239 "directory does not exist: {}",
240 dir.display()
241 )));
242 }
243 let mut dirs = Vec::new();
244 for entry in std::fs::read_dir(dir).map_err(|e| io_err("list_directories", e))? {
245 let entry = entry.map_err(|e| io_err("list_directories", e))?;
246 let meta = entry
248 .metadata()
249 .map_err(|e| io_err("list_directories", e))?;
250 if meta.is_dir() && !meta.is_symlink() {
251 dirs.push(entry.path());
252 }
253 }
254 sort_paths(&mut dirs);
255 Ok(dirs)
256 }
257
258 pub fn list_all(dir: &Path, recursive: bool) -> Result<Vec<PathBuf>> {
263 if !dir.is_dir() {
264 return Err(Error::not_found(format!(
265 "directory does not exist: {}",
266 dir.display()
267 )));
268 }
269 let mut entries = Vec::new();
270 list_all_impl(dir, recursive, &mut entries)?;
271 sort_paths(&mut entries);
272 Ok(entries)
273 }
274
275 pub fn read_text(path: &Path) -> Result<String> {
279 std::fs::read_to_string(path).map_err(|e| io_err("read_text", e))
280 }
281
282 pub fn write_text(path: &Path, content: &str) -> Result<()> {
285 if let Some(parent) = path.parent()
286 && !parent.as_os_str().is_empty()
287 {
288 Self::create_directories(parent)?;
289 }
290 std::fs::write(path, content.as_bytes()).map_err(|e| io_err("write_text", e))
291 }
292
293 pub fn append_text(path: &Path, content: &str) -> Result<()> {
295 if let Some(parent) = path.parent()
296 && !parent.as_os_str().is_empty()
297 {
298 Self::create_directories(parent)?;
299 }
300 use std::io::Write as _;
301 let mut file = std::fs::OpenOptions::new()
302 .create(true)
303 .append(true)
304 .open(path)
305 .map_err(|e| io_err("append_text", e))?;
306 file
307 .write_all(content.as_bytes())
308 .map_err(|e| io_err("append_text", e))
309 }
310
311 pub fn read_lines(path: &Path) -> Result<Vec<String>> {
315 let text = Self::read_text(path)?;
316 if text.is_empty() {
317 return Ok(Vec::new());
318 }
319 let mut lines = Vec::new();
320 let mut begin = 0usize;
321 let bytes = text.as_bytes();
322 for i in 0..bytes.len() {
323 if bytes[i] == b'\n' {
324 let end = if i > begin && bytes[i - 1] == b'\r' {
325 i - 1
326 } else {
327 i
328 };
329 lines.push(text[begin..end].to_owned());
330 begin = i + 1;
331 }
332 }
333 if begin < text.len() {
334 lines.push(text[begin..].to_owned());
335 }
336 Ok(lines)
337 }
338
339 pub fn read_binary(path: &Path) -> Result<Vec<u8>> {
343 std::fs::read(path).map_err(|e| io_err("read_binary", e))
344 }
345
346 pub fn write_binary(path: &Path, data: &[u8]) -> Result<()> {
349 if let Some(parent) = path.parent()
350 && !parent.as_os_str().is_empty()
351 {
352 Self::create_directories(parent)?;
353 }
354 std::fs::write(path, data).map_err(|e| io_err("write_binary", e))
355 }
356
357 pub fn absolute(path: &Path) -> Result<PathBuf> {
362 std::path::absolute(path).map_err(|e| io_err("absolute", e))
363 }
364
365 pub fn glob(dir: &Path, pattern: &str) -> Result<Vec<PathBuf>> {
373 if !dir.is_dir() {
374 return Err(Error::not_found(format!(
375 "directory does not exist: {}",
376 dir.display()
377 )));
378 }
379 let pat = pattern.as_bytes();
380 let mut matches = Vec::new();
381 for entry in std::fs::read_dir(dir).map_err(|e| io_err("glob", e))? {
382 let entry = entry.map_err(|e| io_err("glob", e))?;
383 let path = entry.path();
384 let name = path
385 .file_name()
386 .and_then(|n| n.to_str())
387 .unwrap_or_default();
388 if glob_match(pat, name.as_bytes()) {
389 matches.push(path);
390 }
391 }
392 sort_paths(&mut matches);
393 Ok(matches)
394 }
395}
396
397fn list_all_impl(dir: &Path, recursive: bool, out: &mut Vec<PathBuf>) -> Result<()> {
400 for entry in std::fs::read_dir(dir).map_err(|e| io_err("list_all", e))? {
401 let entry = entry.map_err(|e| io_err("list_all", e))?;
402 let path = entry.path();
403 let meta = entry.metadata().map_err(|e| io_err("list_all", e))?;
404 out.push(path.clone());
405 if recursive && meta.is_dir() && !meta.is_symlink() {
406 list_all_impl(&path, recursive, out)?;
407 }
408 }
409 Ok(())
410}