Skip to main content

oa/core/
filesystem.rs

1//! Stateless host-filesystem operations.
2//!
3//! [`Filesystem`] is the direct port of `oa::Filesystem` from C++. It has no
4//! state of its own; every method is a free function on [`std::path::Path`].
5//!
6//! # Path type
7//!
8//! The Rust port uses [`std::path::Path`] / [`std::path::PathBuf`] directly.
9//! Those types already normalise `/` and `\` on every platform, so there is no
10//! need to port `oa::Path`'s lexical layer. Call `.join()`, `.parent()`,
11//! `.file_name()`, `.extension()`, and `std::path::absolute()` directly for
12//! path manipulation.
13//!
14//! # Error handling
15//!
16//! All fallible methods return [`crate::Result`]. I/O failures are wrapped
17//! through [`crate::Error`] with [`crate::ErrorKind::Io`] so callers do not
18//! depend on `std::io::Error` directly.
19
20use std::path::{Path, PathBuf};
21use std::time::UNIX_EPOCH;
22
23use crate::{Error, Result};
24
25// ─── helpers ─────────────────────────────────────────────────────────────────
26
27fn io_err(op: &'static str, source: std::io::Error) -> Error {
28	Error::io(op, source)
29}
30
31/// Sort paths lexicographically for deterministic output, matching C++
32/// `sortPaths` which sorts by `genericString()`.
33fn sort_paths(paths: &mut [PathBuf]) {
34	paths.sort_unstable();
35}
36
37// ─── glob ────────────────────────────────────────────────────────────────────
38
39/// Match a filename against a `*` / `?` wildcard pattern.
40///
41/// Direct port of `globMatch` in `filesystem.cpp`. The pattern is matched
42/// against the *filename only*, not the full path.
43fn 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
71// ─── Filesystem ──────────────────────────────────────────────────────────────
72
73/// Stateless host-filesystem operations.
74///
75/// All methods are free functions on `&Path`. There is no instance state.
76///
77/// Matches the surface of `oa::Filesystem` in C++ and its Python bindings so
78/// that cross-language code reads identically:
79///
80/// ```rust,ignore
81/// Filesystem::create_directories(output.parent().unwrap())?;
82/// let text = Filesystem::read_text(&config_path)?;
83/// ```
84pub struct Filesystem;
85
86impl Filesystem {
87	// ─── Existence & Info ─────────────────────────────────────────────────
88
89	/// Return `true` if `path` exists (file, directory, or symlink target).
90	pub fn exists(path: &Path) -> bool {
91		path.exists()
92	}
93
94	/// Return `true` if `path` is a regular file.
95	pub fn is_file(path: &Path) -> bool {
96		path.is_file()
97	}
98
99	/// Return `true` if `path` is a directory.
100	pub fn is_directory(path: &Path) -> bool {
101		path.is_dir()
102	}
103
104	/// Return the byte size of the file at `path`.
105	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	/// Return the last-modified time as seconds since the Unix epoch.
111	///
112	/// Matches `oa::Filesystem::getLastModified` which returns an `i64` Unix
113	/// timestamp.
114	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	// ─── Directory operations ─────────────────────────────────────────────
127
128	/// Create a single directory. Succeeds silently if it already exists.
129	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	/// Create a directory and all missing ancestors. Succeeds silently if the
138	/// full path already exists as a directory.
139	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	/// Remove a file. Succeeds silently if the file does not exist.
144	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	/// Remove a directory.
153	///
154	/// When `recursive` is `false` the directory must be empty. When `true`
155	/// the entire subtree is removed. Succeeds silently if the path does not
156	/// exist.
157	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	/// Copy a file or directory.
169	///
170	/// For a directory, creates the destination directory (non-recursive).
171	/// For a file, reads the source and writes it to the destination, creating
172	/// parent directories as needed.
173	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	/// Move (rename) a path. Creates parent directories of the destination.
188	///
189	/// Note: cannot be named `move` in Rust (reserved keyword).
190	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	// ─── Listing ──────────────────────────────────────────────────────────
200
201	/// List regular files in `dir`, optionally filtered by extension.
202	///
203	/// `extension` is matched against the full extension string including the
204	/// leading `.` (e.g. `".png"`). Pass `""` to return all files.
205	/// Results are sorted lexicographically.
206	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	/// List immediate sub-directories of `dir`. Symlinks are not followed.
235	/// Results are sorted lexicographically.
236	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			// Use symlink_metadata so we do not follow symlinks (matches C++).
247			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	/// List all entries (files and directories) in `dir`.
259	///
260	/// When `recursive` is `true`, descends into sub-directories but does not
261	/// follow symlinks. Results are sorted lexicographically.
262	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	// ─── Text file operations ─────────────────────────────────────────────
276
277	/// Read the entire file as a UTF-8 string.
278	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	/// Write `content` to a file, creating parent directories as needed.
283	/// Truncates any existing content.
284	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	/// Append `content` to a file, creating parent directories as needed.
294	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	/// Read lines, stripping `\r\n` and `\n` line endings. The final line is
312	/// included even if it lacks a trailing newline. Empty files return an
313	/// empty `Vec`.
314	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	// ─── Binary file operations ───────────────────────────────────────────
340
341	/// Read the entire file as raw bytes.
342	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	/// Write `data` to a file, creating parent directories as needed.
347	/// Truncates any existing content.
348	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	// ─── Resolution ───────────────────────────────────────────────────────
358
359	/// Resolve a path to an absolute path against the current working
360	/// directory. Does not require the path to exist.
361	pub fn absolute(path: &Path) -> Result<PathBuf> {
362		std::path::absolute(path).map_err(|e| io_err("absolute", e))
363	}
364
365	// ─── Glob ─────────────────────────────────────────────────────────────
366
367	/// Return the files in `dir` whose filename matches `pattern`.
368	///
369	/// `*` matches any sequence of characters; `?` matches exactly one
370	/// character. Only the filename component is matched, not the full path.
371	/// Results are sorted lexicographically.
372	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
397// ─── list_all recursive helper ───────────────────────────────────────────────
398
399fn 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}