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 /// // Untrusted input from request/CLI/config/etc.
199 /// let requested_file = "docs/readme.md";
200 /// let guest_path: VirtualPath<GuestAccess> = guest_root.virtual_join(requested_file)?;
201 /// let user_path = grant_user_access("valid-token-12345", guest_path).expect("authorized");
202 /// assert_eq!(user_path.virtualpath_display().to_string(), "/docs/readme.md");
203 /// # std::fs::remove_dir_all(&root_dir)?;
204 /// # Ok::<_, Box<dyn std::error::Error>>(())
205 /// ```
206 ///
207 /// **Type Safety Guarantee:**
208 ///
209 /// The following code **fails to compile** because you cannot pass a path with one marker
210 /// type to a function expecting a different marker type. This compile-time check enforces
211 /// that permission changes are explicit and cannot be bypassed accidentally.
212 ///
213 /// ```compile_fail
214 /// # use strict_path::VirtualPath;
215 /// # struct GuestAccess;
216 /// # struct EditorAccess;
217 /// # let root_dir = std::env::temp_dir().join("virtual-change-marker-deny");
218 /// # std::fs::create_dir_all(&root_dir).unwrap();
219 /// # let guest_root: VirtualPath<GuestAccess> = VirtualPath::with_root(&root_dir).unwrap();
220 /// fn require_editor(_: VirtualPath<EditorAccess>) {}
221 /// let guest_file = guest_root.virtual_join("docs/manual.txt").unwrap();
222 /// // ❌ Compile error: expected `VirtualPath<EditorAccess>`, found `VirtualPath<GuestAccess>`
223 /// require_editor(guest_file);
224 /// ```
225 #[inline]
226 pub fn change_marker<NewMarker>(self) -> VirtualPath<NewMarker> {
227 let VirtualPath {
228 inner,
229 virtual_path,
230 } = self;
231
232 VirtualPath {
233 inner: inner.change_marker(),
234 virtual_path,
235 }
236 }
237
238 /// SUMMARY:
239 /// Consume and return the `VirtualRoot` for its boundary (no directory creation).
240 ///
241 /// RETURNS:
242 /// - `Result<VirtualRoot<Marker>>`: Virtual root anchored at the strict path's directory.
243 ///
244 /// ERRORS:
245 /// - `StrictPathError::InvalidRestriction`: Propagated from `try_into_boundary` when the
246 /// strict path does not exist or is not a directory.
247 #[inline]
248 pub fn try_into_root(self) -> Result<crate::validator::virtual_root::VirtualRoot<Marker>> {
249 Ok(self.inner.try_into_boundary()?.virtualize())
250 }
251
252 /// SUMMARY:
253 /// Consume and return a `VirtualRoot`, creating the underlying directory if missing.
254 ///
255 /// RETURNS:
256 /// - `Result<VirtualRoot<Marker>>`: Virtual root anchored at the strict path's directory
257 /// (created if necessary).
258 ///
259 /// ERRORS:
260 /// - `StrictPathError::InvalidRestriction`: Propagated from `try_into_boundary` or directory
261 /// creation failures wrapped in `InvalidRestriction`.
262 #[inline]
263 pub fn try_into_root_create(
264 self,
265 ) -> Result<crate::validator::virtual_root::VirtualRoot<Marker>> {
266 let strict_path = self.inner;
267 let boundary = strict_path.try_into_boundary_create()?;
268 Ok(boundary.virtualize())
269 }
270
271 /// SUMMARY:
272 /// Borrow the underlying system‑facing `StrictPath` (no allocation).
273 #[inline]
274 pub fn as_unvirtual(&self) -> &StrictPath<Marker> {
275 &self.inner
276 }
277
278 /// SUMMARY:
279 /// Return the underlying system path as `&OsStr` for unavoidable third-party `AsRef<Path>` interop.
280 #[inline]
281 pub fn interop_path(&self) -> &OsStr {
282 self.inner.interop_path()
283 }
284
285 /// SUMMARY:
286 /// Join a virtual path segment (virtual semantics) and re‑validate within the same restriction.
287 ///
288 /// DETAILS:
289 /// Applies virtual path clamping: absolute paths are interpreted relative to the virtual root,
290 /// and traversal attempts are clamped to prevent escaping the boundary. This method maintains
291 /// the security guarantee that all `VirtualPath` instances stay within their virtual root.
292 ///
293 /// PARAMETERS:
294 /// - `path` (`impl AsRef<Path>`): Path segment to join. Absolute paths are clamped to virtual root.
295 ///
296 /// RETURNS:
297 /// - `Result<VirtualPath<Marker>>`: New virtual path within the same restriction.
298 ///
299 /// EXAMPLE:
300 /// ```rust
301 /// # use strict_path::VirtualRoot;
302 /// # let td = tempfile::tempdir().unwrap();
303 /// let vroot: VirtualRoot = VirtualRoot::try_new_create(td.path())?;
304 /// let base = vroot.virtual_join("data")?;
305 ///
306 /// // Absolute paths are clamped to virtual root
307 /// let abs = base.virtual_join("/etc/config")?;
308 /// assert_eq!(abs.virtualpath_display().to_string(), "/etc/config");
309 /// # Ok::<(), Box<dyn std::error::Error>>(())
310 /// ```
311 #[inline]
312 pub fn virtual_join<P: AsRef<Path>>(&self, path: P) -> Result<Self> {
313 // Compose candidate in virtual space (do not pre-normalize lexically to preserve symlink semantics)
314 let candidate = self.virtual_path.join(path.as_ref());
315 let anchored = crate::validator::path_history::PathHistory::new(candidate)
316 .canonicalize_anchored(self.inner.boundary())?;
317 let boundary_path = clamp(self.inner.boundary(), anchored)?;
318 Ok(VirtualPath::new(boundary_path))
319 }
320
321 // No local clamping helpers; virtual flows should route through
322 // PathHistory::virtualize_to_jail + PathBoundary::strict_join to avoid drift.
323
324 /// SUMMARY:
325 /// Return the parent virtual path, or `None` at the virtual root.
326 pub fn virtualpath_parent(&self) -> Result<Option<Self>> {
327 match self.virtual_path.parent() {
328 Some(parent_virtual_path) => {
329 let anchored = crate::validator::path_history::PathHistory::new(
330 parent_virtual_path.to_path_buf(),
331 )
332 .canonicalize_anchored(self.inner.boundary())?;
333 let validated_path = clamp(self.inner.boundary(), anchored)?;
334 Ok(Some(VirtualPath::new(validated_path)))
335 }
336 None => Ok(None),
337 }
338 }
339
340 /// SUMMARY:
341 /// Return a new virtual path with file name changed, preserving clamping.
342 #[inline]
343 pub fn virtualpath_with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> Result<Self> {
344 let candidate = self.virtual_path.with_file_name(file_name);
345 let anchored = crate::validator::path_history::PathHistory::new(candidate)
346 .canonicalize_anchored(self.inner.boundary())?;
347 let validated_path = clamp(self.inner.boundary(), anchored)?;
348 Ok(VirtualPath::new(validated_path))
349 }
350
351 /// SUMMARY:
352 /// Return a new virtual path with the extension changed, preserving clamping.
353 pub fn virtualpath_with_extension<S: AsRef<OsStr>>(&self, extension: S) -> Result<Self> {
354 if self.virtual_path.file_name().is_none() {
355 return Err(StrictPathError::path_escapes_boundary(
356 self.virtual_path.clone(),
357 self.inner.boundary().path().to_path_buf(),
358 ));
359 }
360
361 let candidate = self.virtual_path.with_extension(extension);
362 let anchored = crate::validator::path_history::PathHistory::new(candidate)
363 .canonicalize_anchored(self.inner.boundary())?;
364 let validated_path = clamp(self.inner.boundary(), anchored)?;
365 Ok(VirtualPath::new(validated_path))
366 }
367
368 /// SUMMARY:
369 /// Return the file name component of the virtual path, if any.
370 #[inline]
371 pub fn virtualpath_file_name(&self) -> Option<&OsStr> {
372 self.virtual_path.file_name()
373 }
374
375 /// SUMMARY:
376 /// Return the file stem of the virtual path, if any.
377 #[inline]
378 pub fn virtualpath_file_stem(&self) -> Option<&OsStr> {
379 self.virtual_path.file_stem()
380 }
381
382 /// SUMMARY:
383 /// Return the extension of the virtual path, if any.
384 #[inline]
385 pub fn virtualpath_extension(&self) -> Option<&OsStr> {
386 self.virtual_path.extension()
387 }
388
389 /// SUMMARY:
390 /// Return `true` if the virtual path starts with the given prefix (virtual semantics).
391 #[inline]
392 pub fn virtualpath_starts_with<P: AsRef<Path>>(&self, p: P) -> bool {
393 self.virtual_path.starts_with(p)
394 }
395
396 /// SUMMARY:
397 /// Return `true` if the virtual path ends with the given suffix (virtual semantics).
398 #[inline]
399 pub fn virtualpath_ends_with<P: AsRef<Path>>(&self, p: P) -> bool {
400 self.virtual_path.ends_with(p)
401 }
402
403 /// SUMMARY:
404 /// Return a Display wrapper that shows a rooted virtual path (e.g., `"/a/b.txt").
405 #[inline]
406 pub fn virtualpath_display(&self) -> VirtualPathDisplay<'_, Marker> {
407 VirtualPathDisplay(self)
408 }
409
410 /// SUMMARY:
411 /// Return `true` if the underlying system path exists.
412 #[inline]
413 pub fn exists(&self) -> bool {
414 self.inner.exists()
415 }
416
417 /// SUMMARY:
418 /// Return `true` if the underlying system path is a file.
419 #[inline]
420 pub fn is_file(&self) -> bool {
421 self.inner.is_file()
422 }
423
424 /// SUMMARY:
425 /// Return `true` if the underlying system path is a directory.
426 #[inline]
427 pub fn is_dir(&self) -> bool {
428 self.inner.is_dir()
429 }
430
431 /// SUMMARY:
432 /// Return metadata for the underlying system path.
433 #[inline]
434 pub fn metadata(&self) -> std::io::Result<std::fs::Metadata> {
435 self.inner.metadata()
436 }
437
438 /// SUMMARY:
439 /// Read the file contents as `String` from the underlying system path.
440 #[inline]
441 pub fn read_to_string(&self) -> std::io::Result<String> {
442 self.inner.read_to_string()
443 }
444
445 /// SUMMARY:
446 /// Read raw bytes from the underlying system path.
447 #[inline]
448 pub fn read(&self) -> std::io::Result<Vec<u8>> {
449 self.inner.read()
450 }
451
452 /// SUMMARY:
453 /// Return metadata for the underlying system path without following symlinks.
454 #[inline]
455 pub fn symlink_metadata(&self) -> std::io::Result<std::fs::Metadata> {
456 self.inner.symlink_metadata()
457 }
458
459 /// SUMMARY:
460 /// Read directory entries (discovery). Re‑join names with `virtual_join(...)` to preserve clamping.
461 pub fn read_dir(&self) -> std::io::Result<std::fs::ReadDir> {
462 self.inner.read_dir()
463 }
464
465 /// SUMMARY:
466 /// Write bytes to the underlying system path. Accepts `&str`, `String`, `&[u8]`, `Vec<u8]`, etc.
467 #[inline]
468 pub fn write<C: AsRef<[u8]>>(&self, contents: C) -> std::io::Result<()> {
469 self.inner.write(contents)
470 }
471
472 /// SUMMARY:
473 /// Create or truncate the file at this virtual path and return a writable handle.
474 ///
475 /// PARAMETERS:
476 /// - _none_
477 ///
478 /// RETURNS:
479 /// - `std::fs::File`: Writable handle scoped to the same virtual root restriction.
480 ///
481 /// ERRORS:
482 /// - `std::io::Error`: Propagates operating-system errors when the parent directory is missing or file creation fails.
483 ///
484 /// EXAMPLE:
485 /// ```rust
486 /// # use strict_path::VirtualRoot;
487 /// # use std::io::Write;
488 /// # let root = std::env::temp_dir().join("strict-path-virtual-create-file");
489 /// # std::fs::create_dir_all(&root)?;
490 /// # let vroot: VirtualRoot = VirtualRoot::try_new(&root)?;
491 /// let report = vroot.virtual_join("reports/summary.txt")?;
492 /// report.create_parent_dir_all()?;
493 /// let mut file = report.create_file()?;
494 /// file.write_all(b"summary")?;
495 /// # std::fs::remove_dir_all(&root)?;
496 /// # Ok::<_, Box<dyn std::error::Error>>(())
497 /// ```
498 #[inline]
499 pub fn create_file(&self) -> std::io::Result<std::fs::File> {
500 self.inner.create_file()
501 }
502
503 /// SUMMARY:
504 /// Open the file at this virtual path in read-only mode.
505 ///
506 /// PARAMETERS:
507 /// - _none_
508 ///
509 /// RETURNS:
510 /// - `std::fs::File`: Read-only handle scoped to the same virtual root restriction.
511 ///
512 /// ERRORS:
513 /// - `std::io::Error`: Propagates operating-system errors when the file is missing or inaccessible.
514 ///
515 /// EXAMPLE:
516 /// ```rust
517 /// # use strict_path::VirtualRoot;
518 /// # use std::io::{Read, Write};
519 /// # let root = std::env::temp_dir().join("strict-path-virtual-open-file");
520 /// # std::fs::create_dir_all(&root)?;
521 /// # let vroot: VirtualRoot = VirtualRoot::try_new(&root)?;
522 /// let report = vroot.virtual_join("reports/summary.txt")?;
523 /// report.create_parent_dir_all()?;
524 /// report.write("summary")?;
525 /// let mut file = report.open_file()?;
526 /// let mut contents = String::new();
527 /// file.read_to_string(&mut contents)?;
528 /// assert_eq!(contents, "summary");
529 /// # std::fs::remove_dir_all(&root)?;
530 /// # Ok::<_, Box<dyn std::error::Error>>(())
531 /// ```
532 #[inline]
533 pub fn open_file(&self) -> std::io::Result<std::fs::File> {
534 self.inner.open_file()
535 }
536
537 /// SUMMARY:
538 /// Create all directories in the underlying system path if missing.
539 #[inline]
540 pub fn create_dir_all(&self) -> std::io::Result<()> {
541 self.inner.create_dir_all()
542 }
543
544 /// SUMMARY:
545 /// Create the directory at this virtual location (non‑recursive). Fails if parent missing.
546 #[inline]
547 pub fn create_dir(&self) -> std::io::Result<()> {
548 self.inner.create_dir()
549 }
550
551 /// SUMMARY:
552 /// Create only the immediate parent of this virtual path (non‑recursive). `Ok(())` at virtual root.
553 #[inline]
554 pub fn create_parent_dir(&self) -> std::io::Result<()> {
555 match self.virtualpath_parent() {
556 Ok(Some(parent)) => parent.create_dir(),
557 Ok(None) => Ok(()),
558 Err(crate::StrictPathError::PathEscapesBoundary { .. }) => Ok(()),
559 Err(e) => Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
560 }
561 }
562
563 /// SUMMARY:
564 /// Recursively create all missing directories up to the immediate parent. `Ok(())` at virtual root.
565 #[inline]
566 pub fn create_parent_dir_all(&self) -> std::io::Result<()> {
567 match self.virtualpath_parent() {
568 Ok(Some(parent)) => parent.create_dir_all(),
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 /// Remove the file at the underlying system path.
577 #[inline]
578 pub fn remove_file(&self) -> std::io::Result<()> {
579 self.inner.remove_file()
580 }
581
582 /// SUMMARY:
583 /// Remove the directory at the underlying system path.
584 #[inline]
585 pub fn remove_dir(&self) -> std::io::Result<()> {
586 self.inner.remove_dir()
587 }
588
589 /// SUMMARY:
590 /// Recursively remove the directory and its contents at the underlying system path.
591 #[inline]
592 pub fn remove_dir_all(&self) -> std::io::Result<()> {
593 self.inner.remove_dir_all()
594 }
595
596 /// SUMMARY:
597 /// Create a symlink at `link_path` pointing to this virtual path (same virtual root required).
598 ///
599 /// DETAILS:
600 /// Both `self` (target) and `link_path` must be `VirtualPath` instances created via `virtual_join()`,
601 /// which ensures all paths are clamped to the virtual root. Absolute paths like `"/etc/config"`
602 /// passed to `virtual_join()` are automatically clamped to `vroot/etc/config`, ensuring symlinks
603 /// cannot escape the virtual root boundary.
604 ///
605 /// EXAMPLE:
606 /// ```rust
607 /// # use strict_path::VirtualRoot;
608 /// # let td = tempfile::tempdir().unwrap();
609 /// let vroot: VirtualRoot = VirtualRoot::try_new_create(td.path())?;
610 ///
611 /// // Create target file
612 /// let target = vroot.virtual_join("/etc/config/app.conf")?;
613 /// target.create_parent_dir_all()?;
614 /// target.write(b"config data")?;
615 ///
616 /// // Ensure link parent directory exists (Windows requires this for symlink creation)
617 /// let link = vroot.virtual_join("/links/config.link")?;
618 /// link.create_parent_dir_all()?;
619 ///
620 /// // Create symlink - may fail on Windows without Developer Mode/admin privileges
621 /// if let Err(e) = target.virtual_symlink("/links/config.link") {
622 /// // Skip test if we don't have symlink privileges (Windows ERROR_PRIVILEGE_NOT_HELD = 1314)
623 /// #[cfg(windows)]
624 /// if e.raw_os_error() == Some(1314) { return Ok(()); }
625 /// return Err(e.into());
626 /// }
627 ///
628 /// assert_eq!(link.read_to_string()?, "config data");
629 /// # Ok::<(), Box<dyn std::error::Error>>(())
630 /// ```
631 pub fn virtual_symlink<P: AsRef<Path>>(&self, link_path: P) -> std::io::Result<()> {
632 let link_ref = link_path.as_ref();
633 let validated_link = if link_ref.is_absolute() {
634 match self.virtual_join(link_ref) {
635 Ok(p) => p,
636 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
637 }
638 } else {
639 // Resolve as sibling
640 let parent = match self.virtualpath_parent() {
641 Ok(Some(p)) => p,
642 Ok(None) => match self
643 .inner
644 .boundary()
645 .clone()
646 .virtualize()
647 .into_virtualpath()
648 {
649 Ok(root) => root,
650 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
651 },
652 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
653 };
654 match parent.virtual_join(link_ref) {
655 Ok(p) => p,
656 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
657 }
658 };
659
660 self.inner.strict_symlink(validated_link.inner.path())
661 }
662
663 /// SUMMARY:
664 /// Create a hard link at `link_path` pointing to this virtual path (same virtual root required).
665 ///
666 /// DETAILS:
667 /// Both `self` (target) and `link_path` must be `VirtualPath` instances created via `virtual_join()`,
668 /// which ensures all paths are clamped to the virtual root. Absolute paths like `"/etc/data"`
669 /// passed to `virtual_join()` are automatically clamped to `vroot/etc/data`, ensuring hard links
670 /// cannot escape the virtual root boundary.
671 ///
672 /// EXAMPLE:
673 /// ```rust
674 /// # use strict_path::VirtualRoot;
675 /// # let td = tempfile::tempdir().unwrap();
676 /// let vroot: VirtualRoot = VirtualRoot::try_new_create(td.path())?;
677 ///
678 /// // Create target file
679 /// let target = vroot.virtual_join("/shared/data.dat")?;
680 /// target.create_parent_dir_all()?;
681 /// target.write(b"shared data")?;
682 ///
683 /// // Ensure link parent directory exists (Windows requires this for hard link creation)
684 /// let link = vroot.virtual_join("/backup/data.dat")?;
685 /// link.create_parent_dir_all()?;
686 ///
687 /// // Create hard link
688 /// target.virtual_hard_link("/backup/data.dat")?;
689 ///
690 /// // Read through link path, verify through target (hard link behavior)
691 /// link.write(b"modified")?;
692 /// assert_eq!(target.read_to_string()?, "modified");
693 /// # Ok::<(), Box<dyn std::error::Error>>(())
694 /// ```
695 pub fn virtual_hard_link<P: AsRef<Path>>(&self, link_path: P) -> std::io::Result<()> {
696 let link_ref = link_path.as_ref();
697 let validated_link = if link_ref.is_absolute() {
698 match self.virtual_join(link_ref) {
699 Ok(p) => p,
700 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
701 }
702 } else {
703 // Resolve as sibling
704 let parent = match self.virtualpath_parent() {
705 Ok(Some(p)) => p,
706 Ok(None) => match self
707 .inner
708 .boundary()
709 .clone()
710 .virtualize()
711 .into_virtualpath()
712 {
713 Ok(root) => root,
714 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
715 },
716 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
717 };
718 match parent.virtual_join(link_ref) {
719 Ok(p) => p,
720 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
721 }
722 };
723
724 self.inner.strict_hard_link(validated_link.inner.path())
725 }
726
727 /// SUMMARY:
728 /// Create a Windows NTFS directory junction at `link_path` pointing to this virtual path.
729 ///
730 /// DETAILS:
731 /// - Windows-only and behind the `junctions` feature.
732 /// - Directory-only semantics; both paths must share the same virtual root.
733 #[cfg(all(windows, feature = "junctions"))]
734 pub fn virtual_junction<P: AsRef<Path>>(&self, link_path: P) -> std::io::Result<()> {
735 // Mirror virtual semantics used by symlink/hard-link helpers:
736 // - Absolute paths are interpreted in the VIRTUAL namespace and clamped to this root
737 // - Relative paths are resolved as siblings (or from the virtual root when at root)
738 let link_ref = link_path.as_ref();
739 let validated_link = if link_ref.is_absolute() {
740 match self.virtual_join(link_ref) {
741 Ok(p) => p,
742 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
743 }
744 } else {
745 let parent = match self.virtualpath_parent() {
746 Ok(Some(p)) => p,
747 Ok(None) => match self
748 .inner
749 .boundary()
750 .clone()
751 .virtualize()
752 .into_virtualpath()
753 {
754 Ok(root) => root,
755 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
756 },
757 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
758 };
759 match parent.virtual_join(link_ref) {
760 Ok(p) => p,
761 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
762 }
763 };
764
765 // Delegate to strict helper after validating link location in virtual space
766 self.inner.strict_junction(validated_link.inner.path())
767 }
768
769 /// SUMMARY:
770 /// Rename/move within the same virtual root. Relative destinations are siblings; absolute are clamped to root.
771 ///
772 /// DETAILS:
773 /// Accepts `impl AsRef<Path>` for the destination. Absolute paths (starting with `"/"`) are
774 /// automatically clamped to the virtual root via internal `virtual_join()` call, ensuring the
775 /// destination cannot escape the virtual boundary. Relative paths are resolved as siblings.
776 /// Parent directories are not created automatically.
777 ///
778 /// PARAMETERS:
779 /// - `dest` (`impl AsRef<Path>`): Destination path. Absolute paths like `"/archive/file.txt"`
780 /// are clamped to `vroot/archive/file.txt`.
781 ///
782 /// EXAMPLE:
783 /// ```rust
784 /// # use strict_path::VirtualRoot;
785 /// # let td = tempfile::tempdir().unwrap();
786 /// let vroot: VirtualRoot = VirtualRoot::try_new_create(td.path())?;
787 ///
788 /// let source = vroot.virtual_join("temp/file.txt")?;
789 /// source.create_parent_dir_all()?;
790 /// source.write(b"content")?;
791 ///
792 /// // Absolute destination path is clamped to virtual root
793 /// let dest_dir = vroot.virtual_join("/archive")?;
794 /// dest_dir.create_dir_all()?;
795 /// source.virtual_rename("/archive/file.txt")?;
796 ///
797 /// let renamed = vroot.virtual_join("/archive/file.txt")?;
798 /// assert_eq!(renamed.read_to_string()?, "content");
799 /// # Ok::<(), Box<dyn std::error::Error>>(())
800 /// ```
801 pub fn virtual_rename<P: AsRef<Path>>(&self, dest: P) -> std::io::Result<()> {
802 let dest_ref = dest.as_ref();
803 let dest_v = if dest_ref.is_absolute() {
804 match self.virtual_join(dest_ref) {
805 Ok(p) => p,
806 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
807 }
808 } else {
809 // Resolve as sibling under the current virtual parent (or root if at "/")
810 let parent = match self.virtualpath_parent() {
811 Ok(Some(p)) => p,
812 Ok(None) => match self
813 .inner
814 .boundary()
815 .clone()
816 .virtualize()
817 .into_virtualpath()
818 {
819 Ok(root) => root,
820 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
821 },
822 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
823 };
824 match parent.virtual_join(dest_ref) {
825 Ok(p) => p,
826 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
827 }
828 };
829
830 // Perform the actual rename via StrictPath
831 self.inner.strict_rename(dest_v.inner.path())
832 }
833
834 /// SUMMARY:
835 /// Copy within the same virtual root. Relative destinations are siblings; absolute are clamped to root.
836 ///
837 /// DETAILS:
838 /// Accepts `impl AsRef<Path>` for the destination. Absolute paths (starting with `"/"`) are
839 /// automatically clamped to the virtual root via internal `virtual_join()` call, ensuring the
840 /// destination cannot escape the virtual boundary. Relative paths are resolved as siblings.
841 /// Parent directories are not created automatically. Returns the number of bytes copied.
842 ///
843 /// PARAMETERS:
844 /// - `dest` (`impl AsRef<Path>`): Destination path. Absolute paths like `"/backup/file.txt"`
845 /// are clamped to `vroot/backup/file.txt`.
846 ///
847 /// RETURNS:
848 /// - `u64`: Number of bytes copied.
849 ///
850 /// EXAMPLE:
851 /// ```rust
852 /// # use strict_path::VirtualRoot;
853 /// # let td = tempfile::tempdir().unwrap();
854 /// let vroot: VirtualRoot = VirtualRoot::try_new_create(td.path())?;
855 ///
856 /// let source = vroot.virtual_join("data/source.txt")?;
857 /// source.create_parent_dir_all()?;
858 /// source.write(b"data to copy")?;
859 ///
860 /// // Absolute destination path is clamped to virtual root
861 /// let dest_dir = vroot.virtual_join("/backup")?;
862 /// dest_dir.create_dir_all()?;
863 /// let bytes = source.virtual_copy("/backup/copy.txt")?;
864 ///
865 /// let copied = vroot.virtual_join("/backup/copy.txt")?;
866 /// assert_eq!(copied.read_to_string()?, "data to copy");
867 /// assert_eq!(bytes, 12);
868 /// # Ok::<(), Box<dyn std::error::Error>>(())
869 /// ```
870 pub fn virtual_copy<P: AsRef<Path>>(&self, dest: P) -> std::io::Result<u64> {
871 let dest_ref = dest.as_ref();
872 let dest_v = if dest_ref.is_absolute() {
873 match self.virtual_join(dest_ref) {
874 Ok(p) => p,
875 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
876 }
877 } else {
878 // Resolve as sibling under the current virtual parent (or root if at "/")
879 let parent = match self.virtualpath_parent() {
880 Ok(Some(p)) => p,
881 Ok(None) => match self
882 .inner
883 .boundary()
884 .clone()
885 .virtualize()
886 .into_virtualpath()
887 {
888 Ok(root) => root,
889 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
890 },
891 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
892 };
893 match parent.virtual_join(dest_ref) {
894 Ok(p) => p,
895 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
896 }
897 };
898
899 // Perform the actual copy via StrictPath
900 std::fs::copy(self.inner.path(), dest_v.inner.path())
901 }
902}
903
904pub struct VirtualPathDisplay<'a, Marker>(&'a VirtualPath<Marker>);
905
906impl<'a, Marker> fmt::Display for VirtualPathDisplay<'a, Marker> {
907 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
908 // Ensure leading slash and normalize to forward slashes for display
909 let s_lossy = self.0.virtual_path.to_string_lossy();
910 let s_norm: std::borrow::Cow<'_, str> = {
911 #[cfg(windows)]
912 {
913 std::borrow::Cow::Owned(s_lossy.replace('\\', "/"))
914 }
915 #[cfg(not(windows))]
916 {
917 std::borrow::Cow::Borrowed(&s_lossy)
918 }
919 };
920 if s_norm.starts_with('/') {
921 write!(f, "{s_norm}")
922 } else {
923 write!(f, "/{s_norm}")
924 }
925 }
926}
927
928impl<Marker> fmt::Debug for VirtualPath<Marker> {
929 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
930 f.debug_struct("VirtualPath")
931 .field("system_path", &self.inner.path())
932 .field("virtual", &format!("{}", self.virtualpath_display()))
933 .field("boundary", &self.inner.boundary().path())
934 .field("marker", &std::any::type_name::<Marker>())
935 .finish()
936 }
937}
938
939impl<Marker> PartialEq for VirtualPath<Marker> {
940 #[inline]
941 fn eq(&self, other: &Self) -> bool {
942 self.inner.path() == other.inner.path()
943 }
944}
945
946impl<Marker> Eq for VirtualPath<Marker> {}
947
948impl<Marker> Hash for VirtualPath<Marker> {
949 #[inline]
950 fn hash<H: Hasher>(&self, state: &mut H) {
951 self.inner.path().hash(state);
952 }
953}
954
955impl<Marker> PartialEq<crate::path::strict_path::StrictPath<Marker>> for VirtualPath<Marker> {
956 #[inline]
957 fn eq(&self, other: &crate::path::strict_path::StrictPath<Marker>) -> bool {
958 self.inner.path() == other.path()
959 }
960}
961
962impl<T: AsRef<Path>, Marker> PartialEq<T> for VirtualPath<Marker> {
963 #[inline]
964 fn eq(&self, other: &T) -> bool {
965 // Compare virtual paths - the user-facing representation
966 // If you want system path comparison, use as_unvirtual()
967 let virtual_str = format!("{}", self.virtualpath_display());
968 let other_str = other.as_ref().to_string_lossy();
969
970 // Normalize both to forward slashes and ensure leading slash
971 let normalized_virtual = virtual_str.as_str();
972
973 #[cfg(windows)]
974 let other_normalized = other_str.replace('\\', "/");
975 #[cfg(not(windows))]
976 let other_normalized = other_str.to_string();
977
978 let normalized_other = if other_normalized.starts_with('/') {
979 other_normalized
980 } else {
981 format!("/{}", other_normalized)
982 };
983
984 normalized_virtual == normalized_other
985 }
986}
987
988impl<T: AsRef<Path>, Marker> PartialOrd<T> for VirtualPath<Marker> {
989 #[inline]
990 fn partial_cmp(&self, other: &T) -> Option<std::cmp::Ordering> {
991 // Compare virtual paths - the user-facing representation
992 let virtual_str = format!("{}", self.virtualpath_display());
993 let other_str = other.as_ref().to_string_lossy();
994
995 // Normalize both to forward slashes and ensure leading slash
996 let normalized_virtual = virtual_str.as_str();
997
998 #[cfg(windows)]
999 let other_normalized = other_str.replace('\\', "/");
1000 #[cfg(not(windows))]
1001 let other_normalized = other_str.to_string();
1002
1003 let normalized_other = if other_normalized.starts_with('/') {
1004 other_normalized
1005 } else {
1006 format!("/{}", other_normalized)
1007 };
1008
1009 Some(normalized_virtual.cmp(&normalized_other))
1010 }
1011}
1012
1013impl<Marker> PartialOrd for VirtualPath<Marker> {
1014 #[inline]
1015 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1016 Some(self.cmp(other))
1017 }
1018}
1019
1020impl<Marker> Ord for VirtualPath<Marker> {
1021 #[inline]
1022 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1023 self.inner.path().cmp(other.inner.path())
1024 }
1025}