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` dir →
128	/// `./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			let candidate = root.join("sdk/asset");
135			if candidate.is_dir() {
136				return Self(candidate);
137			}
138		}
139		Self(PathBuf::from("asset"))
140	}
141
142	/// Asset path joined with a relative component.
143	pub fn asset_rel(relative: impl AsRef<path::Path>) -> Self {
144		Self::asset().join(relative)
145	}
146
147	/// Root of the OA variable-data tree (outputs, checkpoints, logs).
148	///
149	/// Resolution: `OA_VAR` env var → nearest ancestor `var` dir → `./var`.
150	pub fn var() -> Self {
151		if let Ok(v) = std::env::var("OA_VAR") {
152			return Self(PathBuf::from(v));
153		}
154		if let Some(root) = find_source_root() {
155			let candidate = root.join("var");
156			if candidate.is_dir() {
157				return Self(candidate);
158			}
159		}
160		Self(PathBuf::from("var"))
161	}
162
163	/// Var path joined with a relative component.
164	pub fn var_rel(relative: impl AsRef<path::Path>) -> Self {
165		Self::var().join(relative)
166	}
167
168	/// Root of the optional dataset tree.
169	///
170	/// Resolution: `OA_DATA` env var → `<var>/data`.
171	///
172	/// Datasets are never downloaded implicitly.
173	pub fn data() -> Self {
174		if let Ok(v) = std::env::var("OA_DATA") {
175			return Self(PathBuf::from(v));
176		}
177		Self::var().join("data")
178	}
179
180	/// Data path joined with a relative component.
181	pub fn data_rel(relative: impl AsRef<path::Path>) -> Self {
182		Self::data().join(relative)
183	}
184
185	/// User home directory.
186	///
187	/// Resolution: `HOME` (Unix) → `USERPROFILE` (Windows) → current dir.
188	pub fn home() -> Self {
189		if let Ok(v) = std::env::var("HOME") {
190			return Self(PathBuf::from(v));
191		}
192		if let Ok(v) = std::env::var("USERPROFILE") {
193			return Self(PathBuf::from(v));
194		}
195		Self(std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")))
196	}
197
198	/// System temporary directory.
199	///
200	/// Resolution: `TMPDIR` → `TEMP` → `TMP` → `/tmp` (Unix) → current dir.
201	pub fn temp() -> Self {
202		for var in ["TMPDIR", "TEMP", "TMP"] {
203			if let Ok(v) = std::env::var(var) {
204				return Self(PathBuf::from(v));
205			}
206		}
207		#[cfg(unix)]
208		return Self(PathBuf::from("/tmp"));
209		#[cfg(not(unix))]
210		Self(std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")))
211	}
212}
213
214// ─── Deref / AsRef / Borrow ───────────────────────────────────────────────────
215
216impl Deref for Path {
217	type Target = path::Path;
218	fn deref(&self) -> &path::Path {
219		&self.0
220	}
221}
222
223impl AsRef<path::Path> for Path {
224	fn as_ref(&self) -> &path::Path {
225		&self.0
226	}
227}
228
229impl std::borrow::Borrow<path::Path> for Path {
230	fn borrow(&self) -> &path::Path {
231		&self.0
232	}
233}
234
235// ─── Conversions ──────────────────────────────────────────────────────────────
236
237impl From<PathBuf> for Path {
238	fn from(p: PathBuf) -> Self {
239		Self(p)
240	}
241}
242
243impl From<Path> for PathBuf {
244	fn from(p: Path) -> PathBuf {
245		p.0
246	}
247}
248
249impl From<&path::Path> for Path {
250	fn from(p: &path::Path) -> Self {
251		Self(p.to_owned())
252	}
253}
254
255impl From<&str> for Path {
256	fn from(s: &str) -> Self {
257		Self(PathBuf::from(s))
258	}
259}
260
261impl From<String> for Path {
262	fn from(s: String) -> Self {
263		Self(PathBuf::from(s))
264	}
265}
266
267impl AsRef<OsStr> for Path {
268	fn as_ref(&self) -> &OsStr {
269		self.0.as_os_str()
270	}
271}
272
273// ─── Formatting ───────────────────────────────────────────────────────────────
274
275impl fmt::Debug for Path {
276	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
277		fmt::Debug::fmt(&self.0, f)
278	}
279}
280
281impl fmt::Display for Path {
282	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
283		fmt::Display::fmt(&self.0.display(), f)
284	}
285}
286
287// ─── find_source_root ─────────────────────────────────────────────────────────
288
289fn find_source_root() -> Option<PathBuf> {
290	let cwd = std::env::current_dir().ok()?;
291	let mut dir: &path::Path = &cwd;
292	loop {
293		if dir.join("sdk/asset").is_dir() || dir.join("Cargo.toml").is_file() {
294			return Some(dir.to_owned());
295		}
296		dir = dir.parent()?;
297	}
298}