Skip to main content

oa/core/
path.rs

1//! Named OA filesystem locations and the `oa::Path` value type.
2//!
3//! # `oa::Path`
4//!
5//! A thin newtype over [`std::path::PathBuf`] that:
6//! - implements `Deref<Target = std::path::Path>` so it works everywhere a
7//!   `&std::path::Path` is expected (all `std::fs` calls, `Filesystem` methods)
8//! - carries the named OA location methods (`asset`, `var`, `data`, `home`,
9//!   `temp`) directly, so call sites read `oa::Path::asset_rel("audio/x.wav")`
10//! - exposes `.join()`, `.parent()`, etc. returning `oa::Path`
11//! - implements common `From`/`Into`/`AsRef`/`Display`
12//!
13//! # Resolution order
14//!
15//! - `asset` → `OA_ASSET` env var → nearest ancestor `sdk/asset` → `./asset`
16//! - `var`   → `OA_VAR` env var   → nearest ancestor `var`       → `./var`
17//! - `data`  → `OA_DATA` env var  → `<var>/data`
18//! - `home`  → `HOME` (Unix) / `USERPROFILE` (Windows)
19//! - `temp`  → `TMPDIR` / `TEMP` / `TMP` → `/tmp` (Unix) / current dir
20
21use std::ffi::OsStr;
22use std::fmt;
23use std::ops::Deref;
24use std::path::{self, PathBuf};
25
26// ─── oa::Path ─────────────────────────────────────────────────────────────────
27
28/// An owned OA path value.
29///
30/// Wraps [`std::path::PathBuf`] and adds the canonical OA named-location
31/// resolvers as associated functions. All `std::fs` calls and
32/// [`crate::Filesystem`] methods accept `&oa::Path` directly through `Deref`.
33///
34/// ```ignore
35/// let wav  = oa::Path::asset_rel("audio/oaNarration.wav");
36/// let out  = oa::Path::var_rel("example/audio/out.wav");
37/// let ckpt = oa::Path::temp().join("model.oam");
38/// ```
39#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
40pub struct Path(PathBuf);
41
42impl Path {
43	// ─── Constructors ─────────────────────────────────────────────────────
44
45	/// Create an empty path.
46	pub fn empty() -> Self {
47		Self(PathBuf::new())
48	}
49
50	/// Wrap an existing [`PathBuf`].
51	pub fn new_from_path_buf(p: PathBuf) -> Self {
52		Self(p)
53	}
54
55	/// Consume this path and return the inner [`PathBuf`].
56	pub fn into_path_buf(self) -> PathBuf {
57		self.0
58	}
59
60	// ─── Path manipulation ────────────────────────────────────────────────
61
62	/// Extend this path with `component`, returning a new `oa::Path`.
63	pub fn join(&self, component: impl AsRef<path::Path>) -> Self {
64		Self(self.0.join(component))
65	}
66
67	/// Return the parent directory path, or `None` if this is a root or
68	/// prefix path.
69	pub fn parent(&self) -> Option<Self> {
70		self.0.parent().map(|p| Self(p.to_owned()))
71	}
72
73	/// Return the final filename component, or `None`.
74	pub fn file_name(&self) -> Option<&OsStr> {
75		self.0.file_name()
76	}
77
78	/// Return the filename without extension, or `None`.
79	pub fn file_stem(&self) -> Option<&OsStr> {
80		self.0.file_stem()
81	}
82
83	/// Return the extension, or `None`.
84	pub fn extension(&self) -> Option<&OsStr> {
85		self.0.extension()
86	}
87
88	/// Return a new path with the extension replaced.
89	pub fn with_extension(&self, ext: impl AsRef<OsStr>) -> Self {
90		Self(self.0.with_extension(ext))
91	}
92
93	/// Return `true` if the path is absolute.
94	pub fn is_absolute(&self) -> bool {
95		self.0.is_absolute()
96	}
97
98	/// Return `true` if the path is relative.
99	pub fn is_relative(&self) -> bool {
100		self.0.is_relative()
101	}
102
103	/// Return `true` if the path points to an existing regular file.
104	pub fn is_file(&self) -> bool {
105		self.0.is_file()
106	}
107
108	/// Return `true` if the path points to an existing directory.
109	pub fn is_dir(&self) -> bool {
110		self.0.is_dir()
111	}
112
113	/// Return `true` if the path exists.
114	pub fn exists(&self) -> bool {
115		self.0.exists()
116	}
117
118	/// Return a displayable representation.
119	pub fn display(&self) -> path::Display<'_> {
120		self.0.display()
121	}
122
123	// ─── Named OA locations ───────────────────────────────────────────────
124
125	/// Root of the OA asset tree.
126	///
127	/// Resolution: `OA_ASSET` env var → nearest ancestor `sdk/asset`,
128	/// `src/asset`, or `asset` dir → `./asset`.
129	pub fn asset() -> Self {
130		if let Ok(v) = std::env::var("OA_ASSET") {
131			return Self(PathBuf::from(v));
132		}
133		if let Some(root) = find_source_root() {
134			for relative in ["sdk/asset", "src/asset", "asset"] {
135				let candidate = root.join(relative);
136				if candidate.is_dir() {
137					return Self(candidate);
138				}
139			}
140		}
141		Self(PathBuf::from("asset"))
142	}
143
144	/// Asset path joined with a relative component.
145	pub fn asset_rel(relative: impl AsRef<path::Path>) -> Self {
146		Self::asset().join(relative)
147	}
148
149	/// Root of the OA variable-data tree (outputs, checkpoints, logs).
150	///
151	/// Resolution: `OA_VAR` env var → nearest ancestor `var` dir → `./var`.
152	pub fn var() -> Self {
153		if let Ok(v) = std::env::var("OA_VAR") {
154			return Self(PathBuf::from(v));
155		}
156		if let Some(root) = find_source_root() {
157			let candidate = root.join("var");
158			if candidate.is_dir() {
159				return Self(candidate);
160			}
161		}
162		Self(PathBuf::from("var"))
163	}
164
165	/// Var path joined with a relative component.
166	pub fn var_rel(relative: impl AsRef<path::Path>) -> Self {
167		Self::var().join(relative)
168	}
169
170	/// Root of the optional dataset tree.
171	///
172	/// Resolution: `OA_DATA` env var → `<var>/data`.
173	///
174	/// Datasets are never downloaded implicitly.
175	pub fn data() -> Self {
176		if let Ok(v) = std::env::var("OA_DATA") {
177			return Self(PathBuf::from(v));
178		}
179		Self::var().join("data")
180	}
181
182	/// Data path joined with a relative component.
183	pub fn data_rel(relative: impl AsRef<path::Path>) -> Self {
184		Self::data().join(relative)
185	}
186
187	/// User home directory.
188	///
189	/// Resolution: `HOME` (Unix) → `USERPROFILE` (Windows) → current dir.
190	pub fn home() -> Self {
191		if let Ok(v) = std::env::var("HOME") {
192			return Self(PathBuf::from(v));
193		}
194		if let Ok(v) = std::env::var("USERPROFILE") {
195			return Self(PathBuf::from(v));
196		}
197		Self(std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")))
198	}
199
200	/// System temporary directory.
201	///
202	/// Resolution: `TMPDIR` → `TEMP` → `TMP` → `/tmp` (Unix) → current dir.
203	pub fn temp() -> Self {
204		for var in ["TMPDIR", "TEMP", "TMP"] {
205			if let Ok(v) = std::env::var(var) {
206				return Self(PathBuf::from(v));
207			}
208		}
209		#[cfg(unix)]
210		return Self(PathBuf::from("/tmp"));
211		#[cfg(not(unix))]
212		Self(std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")))
213	}
214}
215
216// ─── Deref / AsRef / Borrow ───────────────────────────────────────────────────
217
218impl Deref for Path {
219	type Target = path::Path;
220	fn deref(&self) -> &path::Path {
221		&self.0
222	}
223}
224
225impl AsRef<path::Path> for Path {
226	fn as_ref(&self) -> &path::Path {
227		&self.0
228	}
229}
230
231impl std::borrow::Borrow<path::Path> for Path {
232	fn borrow(&self) -> &path::Path {
233		&self.0
234	}
235}
236
237// ─── Conversions ──────────────────────────────────────────────────────────────
238
239impl From<PathBuf> for Path {
240	fn from(p: PathBuf) -> Self {
241		Self(p)
242	}
243}
244
245impl From<Path> for PathBuf {
246	fn from(p: Path) -> PathBuf {
247		p.0
248	}
249}
250
251impl From<&path::Path> for Path {
252	fn from(p: &path::Path) -> Self {
253		Self(p.to_owned())
254	}
255}
256
257impl From<&str> for Path {
258	fn from(s: &str) -> Self {
259		Self(PathBuf::from(s))
260	}
261}
262
263impl From<String> for Path {
264	fn from(s: String) -> Self {
265		Self(PathBuf::from(s))
266	}
267}
268
269impl AsRef<OsStr> for Path {
270	fn as_ref(&self) -> &OsStr {
271		self.0.as_os_str()
272	}
273}
274
275// ─── Formatting ───────────────────────────────────────────────────────────────
276
277impl fmt::Debug for Path {
278	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
279		fmt::Debug::fmt(&self.0, f)
280	}
281}
282
283impl fmt::Display for Path {
284	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
285		fmt::Display::fmt(&self.0.display(), f)
286	}
287}
288
289// ─── find_source_root ─────────────────────────────────────────────────────────
290
291fn find_source_root() -> Option<PathBuf> {
292	let cwd = std::env::current_dir().ok()?;
293	let mut dir: &path::Path = &cwd;
294	loop {
295		if dir.join("sdk/asset").is_dir() || dir.join("Cargo.toml").is_file() {
296			return Some(dir.to_owned());
297		}
298		dir = dir.parent()?;
299	}
300}