strict_path/path/virtual_path.rs
1// Content copied from original src/path/virtual_path.rs
2use crate::error::StrictPathError;
3use crate::path::strict_path::StrictPath;
4use crate::validator::path_history::{Canonicalized, PathHistory};
5use crate::PathBoundary;
6use crate::Result;
7use std::ffi::OsStr;
8use std::fmt;
9use std::hash::{Hash, Hasher};
10use std::path::{Path, PathBuf};
11
12/// SUMMARY:
13/// Hold a user‑facing path clamped to a virtual root (`"/"`) over a `PathBoundary`.
14///
15/// DETAILS:
16/// `virtualpath_display()` shows rooted, forward‑slashed paths (e.g., `"/a/b.txt"`).
17/// Use virtual manipulation methods to compose paths while preserving clamping, then convert to
18/// `StrictPath` with `unvirtual()` for system‑facing I/O.
19#[derive(Clone)]
20pub struct VirtualPath<Marker = ()> {
21 inner: StrictPath<Marker>,
22 virtual_path: PathBuf,
23}
24
25#[inline]
26fn clamp<Marker, H>(
27 restriction: &PathBoundary<Marker>,
28 anchored: PathHistory<(H, Canonicalized)>,
29) -> crate::Result<crate::path::strict_path::StrictPath<Marker>> {
30 restriction.strict_join(anchored.into_inner())
31}
32
33impl<Marker> VirtualPath<Marker> {
34 /// SUMMARY:
35 /// Create the virtual root (`"/"`) for the given filesystem root.
36 pub fn with_root<P: AsRef<Path>>(root: P) -> Result<Self> {
37 let vroot = crate::validator::virtual_root::VirtualRoot::try_new(root)?;
38 vroot.into_virtualpath()
39 }
40
41 /// SUMMARY:
42 /// Create the virtual root, creating the filesystem root if missing.
43 pub fn with_root_create<P: AsRef<Path>>(root: P) -> Result<Self> {
44 let vroot = crate::validator::virtual_root::VirtualRoot::try_new_create(root)?;
45 vroot.into_virtualpath()
46 }
47 #[inline]
48 pub(crate) fn new(strict_path: StrictPath<Marker>) -> Self {
49 fn compute_virtual<Marker>(
50 system_path: &std::path::Path,
51 restriction: &crate::PathBoundary<Marker>,
52 ) -> std::path::PathBuf {
53 use std::ffi::OsString;
54 use std::path::Component;
55
56 #[cfg(windows)]
57 fn strip_verbatim(p: &std::path::Path) -> std::path::PathBuf {
58 let s = p.as_os_str().to_string_lossy();
59 if let Some(trimmed) = s.strip_prefix("\\\\?\\") {
60 return std::path::PathBuf::from(trimmed);
61 }
62 if let Some(trimmed) = s.strip_prefix("\\\\.\\") {
63 return std::path::PathBuf::from(trimmed);
64 }
65 std::path::PathBuf::from(s.to_string())
66 }
67
68 #[cfg(not(windows))]
69 fn strip_verbatim(p: &std::path::Path) -> std::path::PathBuf {
70 p.to_path_buf()
71 }
72
73 let system_norm = strip_verbatim(system_path);
74 let jail_norm = strip_verbatim(restriction.path());
75
76 if let Ok(stripped) = system_norm.strip_prefix(&jail_norm) {
77 let mut cleaned = std::path::PathBuf::new();
78 for comp in stripped.components() {
79 if let Component::Normal(name) = comp {
80 let s = name.to_string_lossy();
81 let cleaned_s = s.replace(['\n', ';'], "_");
82 if cleaned_s == s {
83 cleaned.push(name);
84 } else {
85 cleaned.push(OsString::from(cleaned_s));
86 }
87 }
88 }
89 return cleaned;
90 }
91
92 let mut strictpath_comps: Vec<_> = system_norm
93 .components()
94 .filter(|c| !matches!(c, Component::Prefix(_) | Component::RootDir))
95 .collect();
96 let mut boundary_comps: Vec<_> = jail_norm
97 .components()
98 .filter(|c| !matches!(c, Component::Prefix(_) | Component::RootDir))
99 .collect();
100
101 #[cfg(windows)]
102 fn comp_eq(a: &Component, b: &Component) -> bool {
103 match (a, b) {
104 (Component::Normal(x), Component::Normal(y)) => {
105 x.to_string_lossy().to_ascii_lowercase()
106 == y.to_string_lossy().to_ascii_lowercase()
107 }
108 _ => false,
109 }
110 }
111
112 #[cfg(not(windows))]
113 fn comp_eq(a: &Component, b: &Component) -> bool {
114 a == b
115 }
116
117 while !strictpath_comps.is_empty()
118 && !boundary_comps.is_empty()
119 && comp_eq(&strictpath_comps[0], &boundary_comps[0])
120 {
121 strictpath_comps.remove(0);
122 boundary_comps.remove(0);
123 }
124
125 let mut vb = std::path::PathBuf::new();
126 for c in strictpath_comps {
127 if let Component::Normal(name) = c {
128 let s = name.to_string_lossy();
129 let cleaned = s.replace(['\n', ';'], "_");
130 if cleaned == s {
131 vb.push(name);
132 } else {
133 vb.push(OsString::from(cleaned));
134 }
135 }
136 }
137 vb
138 }
139
140 let virtual_path = compute_virtual(strict_path.path(), strict_path.boundary());
141
142 Self {
143 inner: strict_path,
144 virtual_path,
145 }
146 }
147
148 /// SUMMARY:
149 /// Convert this `VirtualPath` back into a system‑facing `StrictPath`.
150 #[inline]
151 pub fn unvirtual(self) -> StrictPath<Marker> {
152 self.inner
153 }
154
155 /// SUMMARY:
156 /// Change the compile-time marker while keeping the virtual and strict views in sync.
157 ///
158 /// WHEN TO USE:
159 /// - After authenticating/authorizing a user and granting them access to a virtual path
160 /// - When escalating or downgrading permissions (e.g., ReadOnly → ReadWrite)
161 /// - When reinterpreting a path's domain (e.g., TempStorage → UserUploads)
162 ///
163 /// WHEN NOT TO USE:
164 /// - When converting between path types - conversions preserve markers automatically
165 /// - When the current marker already matches your needs - no transformation needed
166 /// - When you haven't verified authorization - NEVER change markers without checking permissions
167 ///
168 /// PARAMETERS:
169 /// - `_none_`
170 ///
171 /// RETURNS:
172 /// - `VirtualPath<NewMarker>`: Same clamped path encoded with the new marker.
173 ///
174 /// ERRORS:
175 /// - `_none_`
176 ///
177 /// SECURITY:
178 /// This method performs no permission checks. Only elevate markers after verifying real
179 /// authorization out-of-band.
180 ///
181 /// EXAMPLE:
182 /// ```rust
183 /// # use strict_path::VirtualPath;
184 /// # struct GuestAccess;
185 /// # struct UserAccess;
186 /// # let root_dir = std::env::temp_dir().join("virtual-change-marker-example");
187 /// # std::fs::create_dir_all(&root_dir)?;
188 /// # let guest_root: VirtualPath<GuestAccess> = VirtualPath::with_root(&root_dir)?;
189 /// // Simulated authorization: verify user credentials before granting access
190 /// fn grant_user_access(user_token: &str, path: VirtualPath<GuestAccess>) -> Option<VirtualPath<UserAccess>> {
191 /// if user_token == "valid-token-12345" {
192 /// Some(path.change_marker()) // ✅ Only after token validation
193 /// } else {
194 /// None // ❌ Invalid token
195 /// }
196 /// }
197 ///
198 /// let guest_path: VirtualPath<GuestAccess> = guest_root.virtual_join("docs/readme.md")?;
199 /// let user_path = grant_user_access("valid-token-12345", guest_path).expect("authorized");
200 /// assert_eq!(user_path.virtualpath_display().to_string(), "/docs/readme.md");
201 /// # std::fs::remove_dir_all(&root_dir)?;
202 /// # Ok::<_, Box<dyn std::error::Error>>(())
203 /// ```
204 ///
205 /// **Type Safety Guarantee:**
206 ///
207 /// The following code **fails to compile** because you cannot pass a path with one marker
208 /// type to a function expecting a different marker type. This compile-time check enforces
209 /// that permission changes are explicit and cannot be bypassed accidentally.
210 ///
211 /// ```compile_fail
212 /// # use strict_path::VirtualPath;
213 /// # struct GuestAccess;
214 /// # struct EditorAccess;
215 /// # let root_dir = std::env::temp_dir().join("virtual-change-marker-deny");
216 /// # std::fs::create_dir_all(&root_dir).unwrap();
217 /// # let guest_root: VirtualPath<GuestAccess> = VirtualPath::with_root(&root_dir).unwrap();
218 /// fn require_editor(_: VirtualPath<EditorAccess>) {}
219 /// let guest_file = guest_root.virtual_join("docs/manual.txt").unwrap();
220 /// // ❌ Compile error: expected `VirtualPath<EditorAccess>`, found `VirtualPath<GuestAccess>`
221 /// require_editor(guest_file);
222 /// ```
223 #[inline]
224 pub fn change_marker<NewMarker>(self) -> VirtualPath<NewMarker> {
225 let VirtualPath {
226 inner,
227 virtual_path,
228 } = self;
229
230 VirtualPath {
231 inner: inner.change_marker(),
232 virtual_path,
233 }
234 }
235
236 /// SUMMARY:
237 /// Consume and return the `VirtualRoot` for its boundary (no directory creation).
238 ///
239 /// RETURNS:
240 /// - `Result<VirtualRoot<Marker>>`: Virtual root anchored at the strict path's directory.
241 ///
242 /// ERRORS:
243 /// - `StrictPathError::InvalidRestriction`: Propagated from `try_into_boundary` when the
244 /// strict path does not exist or is not a directory.
245 #[inline]
246 pub fn try_into_root(self) -> Result<crate::validator::virtual_root::VirtualRoot<Marker>> {
247 Ok(self.inner.try_into_boundary()?.virtualize())
248 }
249
250 /// SUMMARY:
251 /// Consume and return a `VirtualRoot`, creating the underlying directory if missing.
252 ///
253 /// RETURNS:
254 /// - `Result<VirtualRoot<Marker>>`: Virtual root anchored at the strict path's directory
255 /// (created if necessary).
256 ///
257 /// ERRORS:
258 /// - `StrictPathError::InvalidRestriction`: Propagated from `try_into_boundary` or directory
259 /// creation failures wrapped in `InvalidRestriction`.
260 #[inline]
261 pub fn try_into_root_create(
262 self,
263 ) -> Result<crate::validator::virtual_root::VirtualRoot<Marker>> {
264 let strict_path = self.inner;
265 let boundary = strict_path.try_into_boundary_create()?;
266 Ok(boundary.virtualize())
267 }
268
269 /// SUMMARY:
270 /// Borrow the underlying system‑facing `StrictPath` (no allocation).
271 #[inline]
272 pub fn as_unvirtual(&self) -> &StrictPath<Marker> {
273 &self.inner
274 }
275
276 /// SUMMARY:
277 /// Return the underlying system path as `&OsStr` for unavoidable third-party `AsRef<Path>` interop.
278 #[inline]
279 pub fn interop_path(&self) -> &OsStr {
280 self.inner.interop_path()
281 }
282
283 /// SUMMARY:
284 /// Join a virtual path segment (virtual semantics) and re‑validate within the same restriction.
285 ///
286 /// DETAILS:
287 /// Applies virtual path clamping: absolute paths are interpreted relative to the virtual root,
288 /// and traversal attempts are clamped to prevent escaping the boundary. This method maintains
289 /// the security guarantee that all `VirtualPath` instances stay within their virtual root.
290 ///
291 /// PARAMETERS:
292 /// - `path` (`impl AsRef<Path>`): Path segment to join. Absolute paths are clamped to virtual root.
293 ///
294 /// RETURNS:
295 /// - `Result<VirtualPath<Marker>>`: New virtual path within the same restriction.
296 ///
297 /// EXAMPLE:
298 /// ```rust
299 /// # use strict_path::VirtualRoot;
300 /// # let td = tempfile::tempdir().unwrap();
301 /// let vroot: VirtualRoot = VirtualRoot::try_new_create(td.path())?;
302 /// let base = vroot.virtual_join("data")?;
303 ///
304 /// // Absolute paths are clamped to virtual root
305 /// let abs = base.virtual_join("/etc/config")?;
306 /// assert_eq!(abs.virtualpath_display().to_string(), "/etc/config");
307 /// # Ok::<(), Box<dyn std::error::Error>>(())
308 /// ```
309 #[inline]
310 pub fn virtual_join<P: AsRef<Path>>(&self, path: P) -> Result<Self> {
311 // Compose candidate in virtual space (do not pre-normalize lexically to preserve symlink semantics)
312 let candidate = self.virtual_path.join(path.as_ref());
313 let anchored = crate::validator::path_history::PathHistory::new(candidate)
314 .canonicalize_anchored(self.inner.boundary())?;
315 let boundary_path = clamp(self.inner.boundary(), anchored)?;
316 Ok(VirtualPath::new(boundary_path))
317 }
318
319 // No local clamping helpers; virtual flows should route through
320 // PathHistory::virtualize_to_jail + PathBoundary::strict_join to avoid drift.
321
322 /// SUMMARY:
323 /// Return the parent virtual path, or `None` at the virtual root.
324 pub fn virtualpath_parent(&self) -> Result<Option<Self>> {
325 match self.virtual_path.parent() {
326 Some(parent_virtual_path) => {
327 let anchored = crate::validator::path_history::PathHistory::new(
328 parent_virtual_path.to_path_buf(),
329 )
330 .canonicalize_anchored(self.inner.boundary())?;
331 let validated_path = clamp(self.inner.boundary(), anchored)?;
332 Ok(Some(VirtualPath::new(validated_path)))
333 }
334 None => Ok(None),
335 }
336 }
337
338 /// SUMMARY:
339 /// Return a new virtual path with file name changed, preserving clamping.
340 #[inline]
341 pub fn virtualpath_with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> Result<Self> {
342 let candidate = self.virtual_path.with_file_name(file_name);
343 let anchored = crate::validator::path_history::PathHistory::new(candidate)
344 .canonicalize_anchored(self.inner.boundary())?;
345 let validated_path = clamp(self.inner.boundary(), anchored)?;
346 Ok(VirtualPath::new(validated_path))
347 }
348
349 /// SUMMARY:
350 /// Return a new virtual path with the extension changed, preserving clamping.
351 pub fn virtualpath_with_extension<S: AsRef<OsStr>>(&self, extension: S) -> Result<Self> {
352 if self.virtual_path.file_name().is_none() {
353 return Err(StrictPathError::path_escapes_boundary(
354 self.virtual_path.clone(),
355 self.inner.boundary().path().to_path_buf(),
356 ));
357 }
358
359 let candidate = self.virtual_path.with_extension(extension);
360 let anchored = crate::validator::path_history::PathHistory::new(candidate)
361 .canonicalize_anchored(self.inner.boundary())?;
362 let validated_path = clamp(self.inner.boundary(), anchored)?;
363 Ok(VirtualPath::new(validated_path))
364 }
365
366 /// SUMMARY:
367 /// Return the file name component of the virtual path, if any.
368 #[inline]
369 pub fn virtualpath_file_name(&self) -> Option<&OsStr> {
370 self.virtual_path.file_name()
371 }
372
373 /// SUMMARY:
374 /// Return the file stem of the virtual path, if any.
375 #[inline]
376 pub fn virtualpath_file_stem(&self) -> Option<&OsStr> {
377 self.virtual_path.file_stem()
378 }
379
380 /// SUMMARY:
381 /// Return the extension of the virtual path, if any.
382 #[inline]
383 pub fn virtualpath_extension(&self) -> Option<&OsStr> {
384 self.virtual_path.extension()
385 }
386
387 /// SUMMARY:
388 /// Return `true` if the virtual path starts with the given prefix (virtual semantics).
389 #[inline]
390 pub fn virtualpath_starts_with<P: AsRef<Path>>(&self, p: P) -> bool {
391 self.virtual_path.starts_with(p)
392 }
393
394 /// SUMMARY:
395 /// Return `true` if the virtual path ends with the given suffix (virtual semantics).
396 #[inline]
397 pub fn virtualpath_ends_with<P: AsRef<Path>>(&self, p: P) -> bool {
398 self.virtual_path.ends_with(p)
399 }
400
401 /// SUMMARY:
402 /// Return a Display wrapper that shows a rooted virtual path (e.g., `"/a/b.txt").
403 #[inline]
404 pub fn virtualpath_display(&self) -> VirtualPathDisplay<'_, Marker> {
405 VirtualPathDisplay(self)
406 }
407
408 /// SUMMARY:
409 /// Return `true` if the underlying system path exists.
410 #[inline]
411 pub fn exists(&self) -> bool {
412 self.inner.exists()
413 }
414
415 /// SUMMARY:
416 /// Return `true` if the underlying system path is a file.
417 #[inline]
418 pub fn is_file(&self) -> bool {
419 self.inner.is_file()
420 }
421
422 /// SUMMARY:
423 /// Return `true` if the underlying system path is a directory.
424 #[inline]
425 pub fn is_dir(&self) -> bool {
426 self.inner.is_dir()
427 }
428
429 /// SUMMARY:
430 /// Return metadata for the underlying system path.
431 #[inline]
432 pub fn metadata(&self) -> std::io::Result<std::fs::Metadata> {
433 self.inner.metadata()
434 }
435
436 /// SUMMARY:
437 /// Read the file contents as `String` from the underlying system path.
438 #[inline]
439 pub fn read_to_string(&self) -> std::io::Result<String> {
440 self.inner.read_to_string()
441 }
442
443 /// Reads the file contents as raw bytes from the underlying system path.
444 #[deprecated(since = "0.1.0-alpha.5", note = "Use read() instead")]
445 #[inline]
446 pub fn read_bytes(&self) -> std::io::Result<Vec<u8>> {
447 self.inner.read()
448 }
449
450 /// Writes raw bytes to the underlying system path.
451 #[deprecated(since = "0.1.0-alpha.5", note = "Use write(...) instead")]
452 #[inline]
453 pub fn write_bytes(&self, data: &[u8]) -> std::io::Result<()> {
454 self.inner.write(data)
455 }
456
457 /// Writes a UTF-8 string to the underlying system path.
458 #[deprecated(since = "0.1.0-alpha.5", note = "Use write(...) instead")]
459 #[inline]
460 pub fn write_string(&self, data: &str) -> std::io::Result<()> {
461 self.inner.write(data)
462 }
463
464 /// SUMMARY:
465 /// Read raw bytes from the underlying system path (replacement for `read_bytes`).
466 #[inline]
467 pub fn read(&self) -> std::io::Result<Vec<u8>> {
468 self.inner.read()
469 }
470
471 /// SUMMARY:
472 /// Read directory entries (discovery). Re‑join names with `virtual_join(...)` to preserve clamping.
473 pub fn read_dir(&self) -> std::io::Result<std::fs::ReadDir> {
474 self.inner.read_dir()
475 }
476
477 /// SUMMARY:
478 /// Write bytes to the underlying system path. Accepts `&str`, `String`, `&[u8]`, `Vec<u8]`, etc.
479 #[inline]
480 pub fn write<C: AsRef<[u8]>>(&self, contents: C) -> std::io::Result<()> {
481 self.inner.write(contents)
482 }
483
484 /// SUMMARY:
485 /// Create or truncate the file at this virtual path and return a writable handle.
486 ///
487 /// PARAMETERS:
488 /// - _none_
489 ///
490 /// RETURNS:
491 /// - `std::fs::File`: Writable handle scoped to the same virtual root restriction.
492 ///
493 /// ERRORS:
494 /// - `std::io::Error`: Propagates operating-system errors when the parent directory is missing or file creation fails.
495 ///
496 /// EXAMPLE:
497 /// ```rust
498 /// # use strict_path::VirtualRoot;
499 /// # use std::io::Write;
500 /// # let root = std::env::temp_dir().join("strict-path-virtual-create-file");
501 /// # std::fs::create_dir_all(&root)?;
502 /// # let vroot: VirtualRoot = VirtualRoot::try_new(&root)?;
503 /// let report = vroot.virtual_join("reports/summary.txt")?;
504 /// report.create_parent_dir_all()?;
505 /// let mut file = report.create_file()?;
506 /// file.write_all(b"summary")?;
507 /// # std::fs::remove_dir_all(&root)?;
508 /// # Ok::<_, Box<dyn std::error::Error>>(())
509 /// ```
510 #[inline]
511 pub fn create_file(&self) -> std::io::Result<std::fs::File> {
512 self.inner.create_file()
513 }
514
515 /// SUMMARY:
516 /// Open the file at this virtual path in read-only mode.
517 ///
518 /// PARAMETERS:
519 /// - _none_
520 ///
521 /// RETURNS:
522 /// - `std::fs::File`: Read-only handle scoped to the same virtual root restriction.
523 ///
524 /// ERRORS:
525 /// - `std::io::Error`: Propagates operating-system errors when the file is missing or inaccessible.
526 ///
527 /// EXAMPLE:
528 /// ```rust
529 /// # use strict_path::VirtualRoot;
530 /// # use std::io::{Read, Write};
531 /// # let root = std::env::temp_dir().join("strict-path-virtual-open-file");
532 /// # std::fs::create_dir_all(&root)?;
533 /// # let vroot: VirtualRoot = VirtualRoot::try_new(&root)?;
534 /// let report = vroot.virtual_join("reports/summary.txt")?;
535 /// report.create_parent_dir_all()?;
536 /// report.write("summary")?;
537 /// let mut file = report.open_file()?;
538 /// let mut contents = String::new();
539 /// file.read_to_string(&mut contents)?;
540 /// assert_eq!(contents, "summary");
541 /// # std::fs::remove_dir_all(&root)?;
542 /// # Ok::<_, Box<dyn std::error::Error>>(())
543 /// ```
544 #[inline]
545 pub fn open_file(&self) -> std::io::Result<std::fs::File> {
546 self.inner.open_file()
547 }
548
549 /// SUMMARY:
550 /// Create all directories in the underlying system path if missing.
551 #[inline]
552 pub fn create_dir_all(&self) -> std::io::Result<()> {
553 self.inner.create_dir_all()
554 }
555
556 /// SUMMARY:
557 /// Create the directory at this virtual location (non‑recursive). Fails if parent missing.
558 #[inline]
559 pub fn create_dir(&self) -> std::io::Result<()> {
560 self.inner.create_dir()
561 }
562
563 /// SUMMARY:
564 /// Create only the immediate parent of this virtual path (non‑recursive). `Ok(())` at virtual root.
565 #[inline]
566 pub fn create_parent_dir(&self) -> std::io::Result<()> {
567 match self.virtualpath_parent() {
568 Ok(Some(parent)) => parent.create_dir(),
569 Ok(None) => Ok(()),
570 Err(crate::StrictPathError::PathEscapesBoundary { .. }) => Ok(()),
571 Err(e) => Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
572 }
573 }
574
575 /// SUMMARY:
576 /// Recursively create all missing directories up to the immediate parent. `Ok(())` at virtual root.
577 #[inline]
578 pub fn create_parent_dir_all(&self) -> std::io::Result<()> {
579 match self.virtualpath_parent() {
580 Ok(Some(parent)) => parent.create_dir_all(),
581 Ok(None) => Ok(()),
582 Err(crate::StrictPathError::PathEscapesBoundary { .. }) => Ok(()),
583 Err(e) => Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
584 }
585 }
586
587 /// SUMMARY:
588 /// Remove the file at the underlying system path.
589 #[inline]
590 pub fn remove_file(&self) -> std::io::Result<()> {
591 self.inner.remove_file()
592 }
593
594 /// SUMMARY:
595 /// Remove the directory at the underlying system path.
596 #[inline]
597 pub fn remove_dir(&self) -> std::io::Result<()> {
598 self.inner.remove_dir()
599 }
600
601 /// SUMMARY:
602 /// Recursively remove the directory and its contents at the underlying system path.
603 #[inline]
604 pub fn remove_dir_all(&self) -> std::io::Result<()> {
605 self.inner.remove_dir_all()
606 }
607
608 /// SUMMARY:
609 /// Create a symlink at `link_path` pointing to this virtual path (same virtual root required).
610 ///
611 /// DETAILS:
612 /// Both `self` (target) and `link_path` must be `VirtualPath` instances created via `virtual_join()`,
613 /// which ensures all paths are clamped to the virtual root. Absolute paths like `"/etc/config"`
614 /// passed to `virtual_join()` are automatically clamped to `vroot/etc/config`, ensuring symlinks
615 /// cannot escape the virtual root boundary.
616 ///
617 /// EXAMPLE:
618 /// ```rust
619 /// # use strict_path::VirtualRoot;
620 /// # let td = tempfile::tempdir().unwrap();
621 /// let vroot: VirtualRoot = VirtualRoot::try_new_create(td.path())?;
622 ///
623 /// // Create target - absolute path "/etc/config" is clamped to vroot/etc/config
624 /// let target = vroot.virtual_join("/etc/config/app.conf")?;
625 /// target.create_parent_dir_all()?;
626 /// target.write(b"config data")?;
627 ///
628 /// // Create symlink - absolute path "/var/app/link" is clamped to vroot/var/app/link
629 /// let link = vroot.virtual_join("/var/app/link.conf")?;
630 /// link.create_parent_dir_all()?;
631 ///
632 /// // On Windows, symlink creation may fail without privileges - gracefully handle
633 /// if let Err(e) = target.virtual_symlink(&link) {
634 /// // Windows ERROR_PRIVILEGE_NOT_HELD (1314) is expected without admin/dev mode
635 /// #[cfg(windows)]
636 /// if e.raw_os_error() == Some(1314) { return Ok(()); }
637 /// return Err(e.into());
638 /// }
639 ///
640 /// assert_eq!(link.read_to_string()?, "config data");
641 /// # Ok::<(), Box<dyn std::error::Error>>(())
642 /// ```
643 pub fn virtual_symlink(&self, link_path: &Self) -> std::io::Result<()> {
644 if self.inner.boundary().path() != link_path.inner.boundary().path() {
645 let err = StrictPathError::path_escapes_boundary(
646 link_path.inner.path().to_path_buf(),
647 self.inner.boundary().path().to_path_buf(),
648 );
649 return Err(std::io::Error::new(std::io::ErrorKind::Other, err));
650 }
651
652 self.inner.strict_symlink(&link_path.inner)
653 }
654
655 /// SUMMARY:
656 /// Create a hard link at `link_path` pointing to this virtual path (same virtual root required).
657 ///
658 /// DETAILS:
659 /// Both `self` (target) and `link_path` must be `VirtualPath` instances created via `virtual_join()`,
660 /// which ensures all paths are clamped to the virtual root. Absolute paths like `"/etc/data"`
661 /// passed to `virtual_join()` are automatically clamped to `vroot/etc/data`, ensuring hard links
662 /// cannot escape the virtual root boundary.
663 ///
664 /// EXAMPLE:
665 /// ```rust
666 /// # use strict_path::VirtualRoot;
667 /// # let td = tempfile::tempdir().unwrap();
668 /// let vroot: VirtualRoot = VirtualRoot::try_new_create(td.path())?;
669 ///
670 /// // Create target - absolute path clamped to virtual root
671 /// let target = vroot.virtual_join("/shared/data.dat")?;
672 /// target.create_parent_dir_all()?;
673 /// target.write(b"shared data")?;
674 ///
675 /// // Create hard link - also clamped to virtual root
676 /// let link = vroot.virtual_join("/backup/data.dat")?;
677 /// link.create_parent_dir_all()?;
678 /// target.virtual_hard_link(&link)?;
679 ///
680 /// // Modify through link, verify through target (hard link behavior)
681 /// link.write(b"modified")?;
682 /// assert_eq!(target.read_to_string()?, "modified");
683 /// # Ok::<(), Box<dyn std::error::Error>>(())
684 /// ```
685 pub fn virtual_hard_link(&self, link_path: &Self) -> std::io::Result<()> {
686 if self.inner.boundary().path() != link_path.inner.boundary().path() {
687 let err = StrictPathError::path_escapes_boundary(
688 link_path.inner.path().to_path_buf(),
689 self.inner.boundary().path().to_path_buf(),
690 );
691 return Err(std::io::Error::new(std::io::ErrorKind::Other, err));
692 }
693
694 self.inner.strict_hard_link(&link_path.inner)
695 }
696
697 /// SUMMARY:
698 /// Rename/move within the same virtual root. Relative destinations are siblings; absolute are clamped to root.
699 ///
700 /// DETAILS:
701 /// Accepts `impl AsRef<Path>` for the destination. Absolute paths (starting with `"/"`) are
702 /// automatically clamped to the virtual root via internal `virtual_join()` call, ensuring the
703 /// destination cannot escape the virtual boundary. Relative paths are resolved as siblings.
704 /// Parent directories are not created automatically.
705 ///
706 /// PARAMETERS:
707 /// - `dest` (`impl AsRef<Path>`): Destination path. Absolute paths like `"/archive/file.txt"`
708 /// are clamped to `vroot/archive/file.txt`.
709 ///
710 /// EXAMPLE:
711 /// ```rust
712 /// # use strict_path::VirtualRoot;
713 /// # let td = tempfile::tempdir().unwrap();
714 /// let vroot: VirtualRoot = VirtualRoot::try_new_create(td.path())?;
715 ///
716 /// let source = vroot.virtual_join("temp/file.txt")?;
717 /// source.create_parent_dir_all()?;
718 /// source.write(b"content")?;
719 ///
720 /// // Absolute destination path is clamped to virtual root
721 /// let dest_dir = vroot.virtual_join("/archive")?;
722 /// dest_dir.create_dir_all()?;
723 /// source.virtual_rename("/archive/file.txt")?;
724 ///
725 /// let renamed = vroot.virtual_join("/archive/file.txt")?;
726 /// assert_eq!(renamed.read_to_string()?, "content");
727 /// # Ok::<(), Box<dyn std::error::Error>>(())
728 /// ```
729 pub fn virtual_rename<P: AsRef<Path>>(&self, dest: P) -> std::io::Result<()> {
730 let dest_ref = dest.as_ref();
731 let dest_v = if dest_ref.is_absolute() {
732 match self.virtual_join(dest_ref) {
733 Ok(p) => p,
734 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
735 }
736 } else {
737 // Resolve as sibling under the current virtual parent (or root if at "/")
738 let parent = match self.virtualpath_parent() {
739 Ok(Some(p)) => p,
740 Ok(None) => match self
741 .inner
742 .boundary()
743 .clone()
744 .virtualize()
745 .into_virtualpath()
746 {
747 Ok(root) => root,
748 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
749 },
750 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
751 };
752 match parent.virtual_join(dest_ref) {
753 Ok(p) => p,
754 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
755 }
756 };
757
758 // Perform the actual rename via StrictPath
759 self.inner.strict_rename(dest_v.inner.path())
760 }
761
762 /// SUMMARY:
763 /// Copy within the same virtual root. Relative destinations are siblings; absolute are clamped to root.
764 ///
765 /// DETAILS:
766 /// Accepts `impl AsRef<Path>` for the destination. Absolute paths (starting with `"/"`) are
767 /// automatically clamped to the virtual root via internal `virtual_join()` call, ensuring the
768 /// destination cannot escape the virtual boundary. Relative paths are resolved as siblings.
769 /// Parent directories are not created automatically. Returns the number of bytes copied.
770 ///
771 /// PARAMETERS:
772 /// - `dest` (`impl AsRef<Path>`): Destination path. Absolute paths like `"/backup/file.txt"`
773 /// are clamped to `vroot/backup/file.txt`.
774 ///
775 /// RETURNS:
776 /// - `u64`: Number of bytes copied.
777 ///
778 /// EXAMPLE:
779 /// ```rust
780 /// # use strict_path::VirtualRoot;
781 /// # let td = tempfile::tempdir().unwrap();
782 /// let vroot: VirtualRoot = VirtualRoot::try_new_create(td.path())?;
783 ///
784 /// let source = vroot.virtual_join("data/source.txt")?;
785 /// source.create_parent_dir_all()?;
786 /// source.write(b"data to copy")?;
787 ///
788 /// // Absolute destination path is clamped to virtual root
789 /// let dest_dir = vroot.virtual_join("/backup")?;
790 /// dest_dir.create_dir_all()?;
791 /// let bytes = source.virtual_copy("/backup/copy.txt")?;
792 ///
793 /// let copied = vroot.virtual_join("/backup/copy.txt")?;
794 /// assert_eq!(copied.read_to_string()?, "data to copy");
795 /// assert_eq!(bytes, 12);
796 /// # Ok::<(), Box<dyn std::error::Error>>(())
797 /// ```
798 pub fn virtual_copy<P: AsRef<Path>>(&self, dest: P) -> std::io::Result<u64> {
799 let dest_ref = dest.as_ref();
800 let dest_v = if dest_ref.is_absolute() {
801 match self.virtual_join(dest_ref) {
802 Ok(p) => p,
803 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
804 }
805 } else {
806 // Resolve as sibling under the current virtual parent (or root if at "/")
807 let parent = match self.virtualpath_parent() {
808 Ok(Some(p)) => p,
809 Ok(None) => match self
810 .inner
811 .boundary()
812 .clone()
813 .virtualize()
814 .into_virtualpath()
815 {
816 Ok(root) => root,
817 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
818 },
819 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
820 };
821 match parent.virtual_join(dest_ref) {
822 Ok(p) => p,
823 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
824 }
825 };
826
827 // Perform the actual copy via StrictPath
828 std::fs::copy(self.inner.path(), dest_v.inner.path())
829 }
830}
831
832pub struct VirtualPathDisplay<'a, Marker>(&'a VirtualPath<Marker>);
833
834impl<'a, Marker> fmt::Display for VirtualPathDisplay<'a, Marker> {
835 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
836 // Ensure leading slash and normalize to forward slashes for display
837 let s_lossy = self.0.virtual_path.to_string_lossy();
838 let s_norm: std::borrow::Cow<'_, str> = {
839 #[cfg(windows)]
840 {
841 std::borrow::Cow::Owned(s_lossy.replace('\\', "/"))
842 }
843 #[cfg(not(windows))]
844 {
845 std::borrow::Cow::Borrowed(&s_lossy)
846 }
847 };
848 if s_norm.starts_with('/') {
849 write!(f, "{s_norm}")
850 } else {
851 write!(f, "/{s_norm}")
852 }
853 }
854}
855
856impl<Marker> fmt::Debug for VirtualPath<Marker> {
857 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
858 f.debug_struct("VirtualPath")
859 .field("system_path", &self.inner.path())
860 .field("virtual", &format!("{}", self.virtualpath_display()))
861 .field("boundary", &self.inner.boundary().path())
862 .field("marker", &std::any::type_name::<Marker>())
863 .finish()
864 }
865}
866
867impl<Marker> PartialEq for VirtualPath<Marker> {
868 #[inline]
869 fn eq(&self, other: &Self) -> bool {
870 self.inner.path() == other.inner.path()
871 }
872}
873
874impl<Marker> Eq for VirtualPath<Marker> {}
875
876impl<Marker> Hash for VirtualPath<Marker> {
877 #[inline]
878 fn hash<H: Hasher>(&self, state: &mut H) {
879 self.inner.path().hash(state);
880 }
881}
882
883impl<Marker> PartialEq<crate::path::strict_path::StrictPath<Marker>> for VirtualPath<Marker> {
884 #[inline]
885 fn eq(&self, other: &crate::path::strict_path::StrictPath<Marker>) -> bool {
886 self.inner.path() == other.path()
887 }
888}
889
890impl<T: AsRef<Path>, Marker> PartialEq<T> for VirtualPath<Marker> {
891 #[inline]
892 fn eq(&self, other: &T) -> bool {
893 // Compare virtual paths - the user-facing representation
894 // If you want system path comparison, use as_unvirtual()
895 let virtual_str = format!("{}", self.virtualpath_display());
896 let other_str = other.as_ref().to_string_lossy();
897
898 // Normalize both to forward slashes and ensure leading slash
899 let normalized_virtual = virtual_str.as_str();
900
901 #[cfg(windows)]
902 let other_normalized = other_str.replace('\\', "/");
903 #[cfg(not(windows))]
904 let other_normalized = other_str.to_string();
905
906 let normalized_other = if other_normalized.starts_with('/') {
907 other_normalized
908 } else {
909 format!("/{}", other_normalized)
910 };
911
912 normalized_virtual == normalized_other
913 }
914}
915
916impl<T: AsRef<Path>, Marker> PartialOrd<T> for VirtualPath<Marker> {
917 #[inline]
918 fn partial_cmp(&self, other: &T) -> Option<std::cmp::Ordering> {
919 // Compare virtual paths - the user-facing representation
920 let virtual_str = format!("{}", self.virtualpath_display());
921 let other_str = other.as_ref().to_string_lossy();
922
923 // Normalize both to forward slashes and ensure leading slash
924 let normalized_virtual = virtual_str.as_str();
925
926 #[cfg(windows)]
927 let other_normalized = other_str.replace('\\', "/");
928 #[cfg(not(windows))]
929 let other_normalized = other_str.to_string();
930
931 let normalized_other = if other_normalized.starts_with('/') {
932 other_normalized
933 } else {
934 format!("/{}", other_normalized)
935 };
936
937 Some(normalized_virtual.cmp(&normalized_other))
938 }
939}
940
941impl<Marker> PartialOrd for VirtualPath<Marker> {
942 #[inline]
943 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
944 Some(self.cmp(other))
945 }
946}
947
948impl<Marker> Ord for VirtualPath<Marker> {
949 #[inline]
950 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
951 self.inner.path().cmp(other.inner.path())
952 }
953}
954
955#[cfg(feature = "serde")]
956impl<Marker> serde::Serialize for VirtualPath<Marker> {
957 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
958 where
959 S: serde::Serializer,
960 {
961 serializer.serialize_str(&format!("{}", self.virtualpath_display()))
962 }
963}