1use crate::validator::path_history::{BoundaryChecked, Canonicalized, PathHistory, Raw};
3use crate::{Result, StrictPathError};
4use std::cmp::Ordering;
5use std::ffi::OsStr;
6use std::fmt;
7use std::hash::{Hash, Hasher};
8use std::marker::PhantomData;
9use std::path::{Path, PathBuf};
10use std::sync::Arc;
11
12#[derive(Clone)]
29pub struct StrictPath<Marker = ()> {
30 path: PathHistory<((Raw, Canonicalized), BoundaryChecked)>,
31 boundary: Arc<crate::PathBoundary<Marker>>,
32 _marker: PhantomData<Marker>,
33}
34
35impl<Marker> StrictPath<Marker> {
36 pub fn with_boundary<P: AsRef<Path>>(root: P) -> Result<Self> {
41 let boundary = crate::PathBoundary::try_new(root)?;
42 boundary.strict_join("")
43 }
44
45 pub fn with_boundary_create<P: AsRef<Path>>(root: P) -> Result<Self> {
49 let boundary = crate::PathBoundary::try_new_create(root)?;
50 boundary.strict_join("")
51 }
52 pub(crate) fn new(
53 boundary: Arc<crate::PathBoundary<Marker>>,
54 validated_path: PathHistory<((Raw, Canonicalized), BoundaryChecked)>,
55 ) -> Self {
56 Self {
57 path: validated_path,
58 boundary,
59 _marker: PhantomData,
60 }
61 }
62
63 #[inline]
64 pub(crate) fn boundary(&self) -> &crate::PathBoundary<Marker> {
65 &self.boundary
66 }
67
68 #[inline]
69 pub(crate) fn path(&self) -> &Path {
70 &self.path
71 }
72
73 #[inline]
76 pub fn strictpath_to_string_lossy(&self) -> std::borrow::Cow<'_, str> {
77 self.path.to_string_lossy()
78 }
79
80 #[inline]
84 pub fn strictpath_to_str(&self) -> Option<&str> {
85 self.path.to_str()
86 }
87
88 #[inline]
92 pub fn interop_path(&self) -> &OsStr {
93 self.path.as_os_str()
94 }
95
96 #[inline]
98 pub fn strictpath_display(&self) -> std::path::Display<'_> {
99 self.path.display()
100 }
101
102 #[inline]
106 pub fn unstrict(self) -> PathBuf {
107 self.path.into_inner()
108 }
109
110 #[inline]
112 pub fn virtualize(self) -> crate::path::virtual_path::VirtualPath<Marker> {
113 crate::path::virtual_path::VirtualPath::new(self)
114 }
115
116 #[inline]
121 pub fn try_into_boundary(self) -> crate::PathBoundary<Marker> {
122 self.boundary.as_ref().clone()
124 }
125
126 #[inline]
132 pub fn try_into_boundary_create(self) -> crate::PathBoundary<Marker> {
133 let boundary = self.boundary.as_ref().clone();
134 if !boundary.exists() {
135 let _ = std::fs::create_dir_all(boundary.as_ref());
137 }
138 boundary
139 }
140
141 #[inline]
146 pub fn strict_join<P: AsRef<Path>>(&self, path: P) -> Result<Self> {
147 let new_systempath = self.path.join(path);
148 self.boundary.strict_join(new_systempath)
149 }
150
151 pub fn strictpath_parent(&self) -> Result<Option<Self>> {
153 match self.path.parent() {
154 Some(p) => match self.boundary.strict_join(p) {
155 Ok(p) => Ok(Some(p)),
156 Err(e) => Err(e),
157 },
158 None => Ok(None),
159 }
160 }
161
162 #[inline]
164 pub fn strictpath_with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> Result<Self> {
165 let new_systempath = self.path.with_file_name(file_name);
166 self.boundary.strict_join(new_systempath)
167 }
168
169 pub fn strictpath_with_extension<S: AsRef<OsStr>>(&self, extension: S) -> Result<Self> {
171 let system_path = &self.path;
172 if system_path.file_name().is_none() {
173 return Err(StrictPathError::path_escapes_boundary(
174 self.path.to_path_buf(),
175 self.boundary.path().to_path_buf(),
176 ));
177 }
178 let new_systempath = system_path.with_extension(extension);
179 self.boundary.strict_join(new_systempath)
180 }
181
182 #[inline]
184 pub fn strictpath_file_name(&self) -> Option<&OsStr> {
185 self.path.file_name()
186 }
187
188 #[inline]
190 pub fn strictpath_file_stem(&self) -> Option<&OsStr> {
191 self.path.file_stem()
192 }
193
194 #[inline]
196 pub fn strictpath_extension(&self) -> Option<&OsStr> {
197 self.path.extension()
198 }
199
200 #[inline]
202 pub fn strictpath_starts_with<P: AsRef<Path>>(&self, p: P) -> bool {
203 self.path.starts_with(p.as_ref())
204 }
205
206 #[inline]
208 pub fn strictpath_ends_with<P: AsRef<Path>>(&self, p: P) -> bool {
209 self.path.ends_with(p.as_ref())
210 }
211
212 pub fn exists(&self) -> bool {
214 self.path.exists()
215 }
216
217 pub fn is_file(&self) -> bool {
219 self.path.is_file()
220 }
221
222 pub fn is_dir(&self) -> bool {
224 self.path.is_dir()
225 }
226
227 pub fn metadata(&self) -> std::io::Result<std::fs::Metadata> {
229 std::fs::metadata(&self.path)
230 }
231
232 pub fn read_dir(&self) -> std::io::Result<std::fs::ReadDir> {
238 std::fs::read_dir(&self.path)
239 }
240
241 pub fn read_to_string(&self) -> std::io::Result<String> {
243 std::fs::read_to_string(&self.path)
244 }
245
246 #[deprecated(since = "0.1.0-alpha.5", note = "Use read() instead")]
248 pub fn read_bytes(&self) -> std::io::Result<Vec<u8>> {
249 std::fs::read(&self.path)
250 }
251
252 #[deprecated(since = "0.1.0-alpha.5", note = "Use write(...) instead")]
254 pub fn write_bytes(&self, data: &[u8]) -> std::io::Result<()> {
255 std::fs::write(&self.path, data)
256 }
257
258 #[deprecated(since = "0.1.0-alpha.5", note = "Use write(...) instead")]
260 pub fn write_string(&self, data: &str) -> std::io::Result<()> {
261 std::fs::write(&self.path, data)
262 }
263
264 #[inline]
266 pub fn read(&self) -> std::io::Result<Vec<u8>> {
267 std::fs::read(&self.path)
268 }
269
270 #[inline]
273 pub fn write<C: AsRef<[u8]>>(&self, contents: C) -> std::io::Result<()> {
274 std::fs::write(&self.path, contents)
275 }
276
277 pub fn create_dir_all(&self) -> std::io::Result<()> {
279 std::fs::create_dir_all(&self.path)
280 }
281
282 pub fn create_dir(&self) -> std::io::Result<()> {
287 std::fs::create_dir(&self.path)
288 }
289
290 pub fn create_parent_dir(&self) -> std::io::Result<()> {
295 match self.strictpath_parent() {
296 Ok(Some(parent)) => parent.create_dir(),
297 Ok(None) => Ok(()),
298 Err(StrictPathError::PathEscapesBoundary { .. }) => Ok(()),
299 Err(e) => Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
300 }
301 }
302
303 pub fn create_parent_dir_all(&self) -> std::io::Result<()> {
307 match self.strictpath_parent() {
308 Ok(Some(parent)) => parent.create_dir_all(),
309 Ok(None) => Ok(()),
310 Err(StrictPathError::PathEscapesBoundary { .. }) => Ok(()),
311 Err(e) => Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
312 }
313 }
314
315 pub fn strict_rename<P: AsRef<Path>>(&self, dest: P) -> std::io::Result<Self> {
322 let dest_ref = dest.as_ref();
323
324 let dest_path = if dest_ref.is_absolute() {
326 match self.boundary.strict_join(dest_ref) {
327 Ok(p) => p,
328 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
329 }
330 } else {
331 let parent = match self.strictpath_parent() {
332 Ok(Some(p)) => p,
333 Ok(None) => match self.boundary.strict_join("") {
334 Ok(root) => root,
335 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
336 },
337 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
338 };
339 match parent.strict_join(dest_ref) {
340 Ok(p) => p,
341 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
342 }
343 };
344
345 std::fs::rename(self.path(), dest_path.path())?;
346 Ok(dest_path)
347 }
348
349 pub fn strict_copy<P: AsRef<Path>>(&self, dest: P) -> std::io::Result<Self> {
360 let dest_ref = dest.as_ref();
361
362 let dest_path = if dest_ref.is_absolute() {
364 match self.boundary.strict_join(dest_ref) {
365 Ok(p) => p,
366 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
367 }
368 } else {
369 let parent = match self.strictpath_parent() {
370 Ok(Some(p)) => p,
371 Ok(None) => match self.boundary.strict_join("") {
372 Ok(root) => root,
373 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
374 },
375 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
376 };
377 match parent.strict_join(dest_ref) {
378 Ok(p) => p,
379 Err(e) => return Err(std::io::Error::new(std::io::ErrorKind::Other, e)),
380 }
381 };
382
383 std::fs::copy(self.path(), dest_path.path())?;
384 Ok(dest_path)
385 }
386
387 pub fn remove_file(&self) -> std::io::Result<()> {
389 std::fs::remove_file(&self.path)
390 }
391
392 pub fn remove_dir(&self) -> std::io::Result<()> {
394 std::fs::remove_dir(&self.path)
395 }
396
397 pub fn remove_dir_all(&self) -> std::io::Result<()> {
399 std::fs::remove_dir_all(&self.path)
400 }
401}
402
403#[cfg(feature = "serde")]
404impl<Marker> serde::Serialize for StrictPath<Marker> {
405 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
406 where
407 S: serde::Serializer,
408 {
409 serializer.serialize_str(self.strictpath_to_string_lossy().as_ref())
410 }
411}
412
413impl<Marker> fmt::Debug for StrictPath<Marker> {
414 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
415 f.debug_struct("StrictPath")
416 .field("path", &self.path)
417 .field("boundary", &self.boundary.path())
418 .field("marker", &std::any::type_name::<Marker>())
419 .finish()
420 }
421}
422
423impl<Marker> PartialEq for StrictPath<Marker> {
424 #[inline]
425 fn eq(&self, other: &Self) -> bool {
426 self.path.as_ref() == other.path.as_ref()
427 }
428}
429
430impl<Marker> Eq for StrictPath<Marker> {}
431
432impl<Marker> Hash for StrictPath<Marker> {
433 #[inline]
434 fn hash<H: Hasher>(&self, state: &mut H) {
435 self.path.hash(state);
436 }
437}
438
439impl<Marker> PartialOrd for StrictPath<Marker> {
440 #[inline]
441 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
442 Some(self.cmp(other))
443 }
444}
445
446impl<Marker> Ord for StrictPath<Marker> {
447 #[inline]
448 fn cmp(&self, other: &Self) -> Ordering {
449 self.path.cmp(&other.path)
450 }
451}
452
453impl<T: AsRef<Path>, Marker> PartialEq<T> for StrictPath<Marker> {
454 fn eq(&self, other: &T) -> bool {
455 self.path.as_ref() == other.as_ref()
456 }
457}
458
459impl<T: AsRef<Path>, Marker> PartialOrd<T> for StrictPath<Marker> {
460 fn partial_cmp(&self, other: &T) -> Option<Ordering> {
461 Some(self.path.as_ref().cmp(other.as_ref()))
462 }
463}
464
465impl<Marker> PartialEq<crate::path::virtual_path::VirtualPath<Marker>> for StrictPath<Marker> {
466 #[inline]
467 fn eq(&self, other: &crate::path::virtual_path::VirtualPath<Marker>) -> bool {
468 self.path.as_ref() == other.interop_path()
469 }
470}