-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathrelative.rs
More file actions
461 lines (397 loc) · 13.7 KB
/
relative.rs
File metadata and controls
461 lines (397 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! Provides `RelativePath(Buf)`, a relative path type with additional guarantees to make it portable.
//!
//! ## Why not use crate `relative-path`
//! `relative-path::RelativePath` allows backslashes in its components, which is valid in unix systems but not portable to Windows.
use std::{
borrow::Borrow,
fmt::Display,
ops::Deref,
path::{Component, Path},
};
use bincode::{Decode, Encode, de::Decoder, error::DecodeError};
use diff::Diff;
use ref_cast::{RefCastCustom, ref_cast_custom};
use serde::{Deserialize, Serialize};
use vite_str::Str;
/// A relative path with additional guarantees to make it portable:
///
/// - It is valid utf-8
/// - It uses slashes `/` as separators, not backslashes `\`
/// - There's no backslash `\` in components (this is valid in unix systems but not portable to Windows)
#[derive(RefCastCustom, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct RelativePath(str);
impl AsRef<Self> for RelativePath {
fn as_ref(&self) -> &Self {
self
}
}
impl AsRef<Path> for RelativePath {
fn as_ref(&self) -> &Path {
self.as_path()
}
}
impl RelativePath {
#[ref_cast_custom]
unsafe fn assume_portable(path: &str) -> &Self;
#[must_use]
pub const fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn as_path(&self) -> &Path {
Path::new(self.as_str())
}
#[must_use]
pub fn to_relative_path_buf(&self) -> RelativePathBuf {
RelativePathBuf(self.0.into())
}
/// Creates an owned [`RelativePathBuf`] with `rel_path` adjoined to `self`.
pub fn join<P: AsRef<Self>>(&self, rel_path: P) -> RelativePathBuf {
let mut relative_path_buf = self.to_relative_path_buf();
relative_path_buf.push(rel_path);
relative_path_buf
}
/// Lexically normalizes the path by resolving `..` components without
/// accessing the filesystem. (`.` components are already stripped by
/// [`RelativePathBuf::new`].)
///
/// **Symlink limitation**: Because this is purely lexical, it can produce
/// incorrect results when symlinks are involved. For example, if
/// `a/link` is a symlink to `x/y`, then cleaning `a/link/../c`
/// yields `a/c` instead of the correct `x/c`. Use
/// [`std::fs::canonicalize`] when you need symlink-correct resolution.
///
/// # Panics
///
/// Panics if the cleaned path is no longer a valid relative path, which
/// should never happen in practice.
#[must_use]
pub fn clean(&self) -> RelativePathBuf {
use path_clean::PathClean as _;
let cleaned = self.as_path().clean();
RelativePathBuf::new(cleaned).expect("cleaning a relative path preserves relativity")
}
/// Returns a path that, when joined onto `base`, yields `self`.
///
/// If `base` is not a prefix of `self`, returns [`None`].
///
/// # Panics
///
/// Panics if the stripped path contains non-UTF-8 characters, which should not happen for valid `RelativePath` instances.
pub fn strip_prefix<P: AsRef<Self>>(&self, base: P) -> Option<&Self> {
let stripped_path = Path::new(self.as_str()).strip_prefix(base.as_ref().as_path()).ok()?;
// SAFETY: The stripped result of a portable RelativePath is still portable:
// it remains valid UTF-8 and contains no backslash separators.
Some(unsafe { Self::assume_portable(stripped_path.to_str().unwrap()) })
}
}
/// A owned relative path buf with the same guarantees as `RelativePath`
#[derive(
Debug, Encode, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize, Default,
)]
#[expect(
clippy::unsafe_derive_deserialize,
reason = "unsafe in Decode impl validates portability invariants"
)]
pub struct RelativePathBuf(Str);
impl AsRef<Path> for RelativePathBuf {
fn as_ref(&self) -> &Path {
self.as_path()
}
}
impl Display for RelativePathBuf {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Display::fmt(&self.0, f)
}
}
impl PartialEq<RelativePath> for RelativePathBuf {
fn eq(&self, other: &RelativePath) -> bool {
self.as_relative_path().eq(other)
}
}
impl PartialEq<&RelativePath> for RelativePathBuf {
fn eq(&self, other: &&RelativePath) -> bool {
self.as_relative_path().eq(other)
}
}
impl Diff for RelativePathBuf {
type Repr = Option<Str>;
fn diff(&self, other: &Self) -> Self::Repr {
self.0.diff(&other.0)
}
fn apply(&mut self, diff: &Self::Repr) {
self.0.apply(diff);
}
fn identity() -> Self {
Self(Str::identity())
}
}
impl RelativePathBuf {
#[must_use]
pub fn empty() -> Self {
Self("".into())
}
/// Extends `self` with `path`.
///
/// Unlike [`std::path::PathBuf::push`], `self` and `path` are both always relative,
/// so `self` can only be appended, not replaced
pub fn push<P: AsRef<RelativePath>>(&mut self, rel_path: P) {
let rel_path_str = rel_path.as_ref().as_str();
if rel_path_str.is_empty() {
return;
}
if !self.as_str().is_empty() {
self.0.push('/');
}
self.0.push_str(rel_path_str);
}
/// Creates a new `RelativePathBuf` from a `Path`.
///
/// This function normalizes the path by:
/// - Removing `.` components
/// - Replacing backslash `\` separators with slashes `/` (on Windows)
///
/// # Errors
/// Returns an error if the path is not relative or contains invalid data that makes it non-portable.
pub fn new<P: AsRef<Path>>(path: P) -> Result<Self, FromPathError> {
let path = path.as_ref();
let mut path_str = Str::with_capacity(path.as_os_str().len());
for component in path.components() {
match component {
Component::Prefix(_) | Component::RootDir => {
return Err(FromPathError::NonRelative);
}
Component::CurDir => {
// normalize dots
continue;
}
Component::ParentDir => {
path_str.push_str("..");
}
Component::Normal(os_str) => {
let Some(component) = os_str.to_str() else {
return Err(InvalidPathDataError::NonUtf8.into());
};
if component.contains('\\') {
return Err(InvalidPathDataError::BackslashInComponent.into());
}
path_str.push_str(component);
}
}
path_str.push('/');
}
path_str.pop(); // remove last pushed '/'
Ok(Self(path_str))
}
#[must_use]
pub fn as_relative_path(&self) -> &RelativePath {
// SAFETY: RelativePathBuf's constructors (new, Decode) validate portability
// invariants, so the inner string is guaranteed to be a valid portable path.
unsafe { RelativePath::assume_portable(&self.0) }
}
}
impl<Context> Decode<Context> for RelativePathBuf {
fn decode<D: Decoder<Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
let path_str = Str::decode(decoder)?;
Self::new(path_str.as_str()).map_err(|err| {
#[expect(
clippy::disallowed_macros,
reason = "bincode::error::DecodeError requires std format!"
)]
let msg = format!("{err}: {path_str}");
DecodeError::OtherString(msg)
})
}
}
bincode::impl_borrow_decode!(RelativePathBuf);
impl TryFrom<&Path> for RelativePathBuf {
type Error = FromPathError;
fn try_from(path: &Path) -> Result<Self, Self::Error> {
Self::new(path)
}
}
impl TryFrom<&str> for RelativePathBuf {
type Error = FromPathError;
fn try_from(path: &str) -> Result<Self, Self::Error> {
let path = Path::new(path);
Self::try_from(path)
}
}
impl AsRef<RelativePath> for RelativePathBuf {
fn as_ref(&self) -> &RelativePath {
self.as_relative_path()
}
}
impl Deref for RelativePathBuf {
type Target = RelativePath;
fn deref(&self) -> &Self::Target {
self.as_relative_path()
}
}
impl Borrow<RelativePath> for RelativePathBuf {
fn borrow(&self) -> &RelativePath {
self.as_relative_path()
}
}
impl ToOwned for RelativePath {
type Owned = RelativePathBuf;
fn to_owned(&self) -> Self::Owned {
self.to_relative_path_buf()
}
}
/// Error when converting a path containing invalid data to `RelativePathbuf`
#[derive(thiserror::Error, Debug)]
pub enum InvalidPathDataError {
/// One of the components contains non-utf8 data.
#[error("path is not portable because contains non-utf8 data")]
NonUtf8,
/// One of the components contains backslashes `\`.
///
/// This is valid in unix systems but not portable to Windows
#[error("path is not portable because it contains backslash ('\\') in its components")]
BackslashInComponent,
}
/// Error when converting a `Path` to `RelativePathbuf`
#[derive(thiserror::Error, Debug)]
pub enum FromPathError {
#[error("path is not relative")]
NonRelative,
#[error("{0}")]
InvalidPathData(#[from] InvalidPathDataError),
}
#[cfg(feature = "ts-rs")]
mod ts_impl {
use ts_rs::TS;
use super::RelativePathBuf;
#[expect(clippy::disallowed_types, reason = "ts_rs::TS trait requires returning std String")]
impl TS for RelativePathBuf {
type OptionInnerType = Self;
type WithoutGenerics = Self;
fn name() -> String {
"string".to_owned()
}
fn inline() -> String {
"string".to_owned()
}
fn inline_flattened() -> String {
panic!("RelativePathBuf cannot be flattened")
}
fn decl() -> String {
panic!("RelativePathBuf is a primitive type")
}
fn decl_concrete() -> String {
panic!("RelativePathBuf is a primitive type")
}
}
}
#[cfg(test)]
mod tests {
#[cfg(windows)]
use std::os::windows::ffi::OsStringExt as _;
use assert2::let_assert;
use super::*;
#[test]
fn non_relative() {
let_assert!(
Err(FromPathError::NonRelative) =
RelativePathBuf::new(if cfg!(windows) { "C:\\Users" } else { "/home" })
);
}
#[cfg(unix)]
#[test]
fn non_utf8() {
use std::{ffi::OsStr, os::unix::ffi::OsStrExt as _};
let non_utf8_os_str = OsStr::from_bytes(&[0xC0]);
let_assert!(
Err(FromPathError::InvalidPathData(InvalidPathDataError::NonUtf8)) =
RelativePathBuf::new(non_utf8_os_str),
);
}
#[cfg(windows)]
#[test]
fn non_utf8() {
use std::ffi::OsString;
// ill-formed UTF-16: X<high surrogate>Y
let non_utf8_path = OsString::from_wide(&[0x0058, 0xD800, 0x0059]);
let_assert!(
Err(FromPathError::InvalidPathData(InvalidPathDataError::NonUtf8)) =
RelativePathBuf::new(non_utf8_path),
);
}
#[cfg(unix)]
#[test]
fn backslash_in_component() {
let_assert!(
Err(FromPathError::InvalidPathData(InvalidPathDataError::BackslashInComponent)) =
RelativePathBuf::new("foo\\bar")
);
}
#[cfg(windows)]
#[test]
fn backslash_in_component() {
let_assert!(Ok(path) = RelativePathBuf::new("foo\\bar"));
assert_eq!(path.as_str(), "foo/bar");
}
#[cfg(windows)]
#[test]
fn replace_backslash_separators() {
let rel_path = RelativePathBuf::new("foo\\bar").unwrap();
assert_eq!(rel_path.as_str(), "foo/bar");
}
#[test]
fn normalize_dots() {
let rel_path = RelativePathBuf::new("./foo/./bar/.").unwrap();
assert_eq!(rel_path.as_str(), "foo/bar");
}
#[test]
fn normalize_trailing_slashes() {
let rel_path = RelativePathBuf::new("foo/bar//").unwrap();
assert_eq!(rel_path.as_str(), "foo/bar");
}
#[test]
fn preserve_double_dots() {
let rel_path = RelativePathBuf::new("../foo/../bar/..").unwrap();
assert_eq!(rel_path.as_str(), "../foo/../bar/..");
}
#[test]
fn push() {
let mut rel_path = RelativePathBuf::new("foo/bar").unwrap();
rel_path.push(RelativePathBuf::new("baz").unwrap());
assert_eq!(rel_path.as_str(), "foo/bar/baz");
}
#[test]
fn push_empty() {
let mut rel_path = RelativePathBuf::new("foo/bar").unwrap();
rel_path.push(RelativePathBuf::new("").unwrap());
assert_eq!(rel_path.as_str(), "foo/bar");
}
#[test]
fn join() {
let rel_path = RelativePathBuf::new("foo/bar").unwrap();
let joined_path = rel_path.as_relative_path().join(RelativePathBuf::new("baz").unwrap());
assert_eq!(joined_path.as_str(), "foo/bar/baz");
}
#[test]
fn join_empty() {
let rel_path = RelativePathBuf::new("").unwrap();
let joined_path = rel_path.as_relative_path().join(RelativePathBuf::new("baz").unwrap());
assert_eq!(joined_path.as_str(), "baz");
}
#[test]
fn strip_prefix() {
let rel_path = RelativePathBuf::new("foo/bar/baz").unwrap();
let prefix = RelativePathBuf::new("foo").unwrap();
let stripped_path = rel_path.strip_prefix(prefix).unwrap();
assert_eq!(stripped_path.as_str(), "bar/baz");
}
#[test]
fn encode_decode() {
let rel_path = RelativePathBuf::new("foo/bar").unwrap();
let config = bincode::config::standard();
let encoded = bincode::encode_to_vec(&rel_path, config).unwrap();
let (decoded, _) =
bincode::decode_from_slice::<RelativePathBuf, _>(&encoded, config).unwrap();
assert_eq!(rel_path, decoded);
}
}