| 1 |
// hg_path.rs |
| 2 |
// |
| 3 |
// Copyright 2019 Raphaël Gomès <[email protected]> |
| 4 |
// |
| 5 |
// This software may be used and distributed according to the terms of the |
| 6 |
// GNU General Public License version 2 or any later version. |
| 7 |
|
| 8 |
use std::borrow::Borrow; |
| 9 |
use std::borrow::Cow; |
| 10 |
use std::ffi::OsStr; |
| 11 |
use std::ffi::OsString; |
| 12 |
use std::fmt; |
| 13 |
use std::ops::Deref; |
| 14 |
use std::path::Path; |
| 15 |
use std::path::PathBuf; |
| 16 |
|
| 17 |
use crate::errors::HgBacktrace; |
| 18 |
use crate::errors::HgError; |
| 19 |
use crate::utils::strings::SliceExt; |
| 20 |
|
| 21 |
#[derive(Debug)] |
| 22 |
pub struct HgPathError { |
| 23 |
kind: HgPathErrorKind, |
| 24 |
backtrace: HgBacktrace, |
| 25 |
} |
| 26 |
|
| 27 |
impl PartialEq for HgPathError { |
| 28 |
fn eq(&self, other: &Self) -> bool { |
| 29 |
self.kind == other.kind |
| 30 |
} |
| 31 |
} |
| 32 |
|
| 33 |
impl Eq for HgPathError {} |
| 34 |
|
| 35 |
impl From<HgPathErrorKind> for HgPathError { |
| 36 |
fn from(value: HgPathErrorKind) -> Self { |
| 37 |
Self { |
| 38 |
kind: value, |
| 39 |
// Uses of `HgPathErrorKind` should only be here to ease the |
| 40 |
// ergonomics, not an actual error type to use in a signature, |
| 41 |
// so we expect this capture to happen where/when we want it to. |
| 42 |
backtrace: HgBacktrace::capture(), |
| 43 |
} |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
#[derive(Debug, Eq, PartialEq)] |
| 48 |
pub enum HgPathErrorKind { |
| 49 |
/// Bytes from the invalid `HgPath` |
| 50 |
LeadingSlash(Vec<u8>), |
| 51 |
ConsecutiveSlashes { |
| 52 |
bytes: Vec<u8>, |
| 53 |
second_slash_index: usize, |
| 54 |
}, |
| 55 |
ContainsNullByte { |
| 56 |
bytes: Vec<u8>, |
| 57 |
null_byte_index: usize, |
| 58 |
}, |
| 59 |
/// Bytes |
| 60 |
DecodeError(Vec<u8>), |
| 61 |
/// The rest come from audit errors |
| 62 |
EndsWithSlash(HgPathBuf), |
| 63 |
ContainsIllegalComponent(HgPathBuf), |
| 64 |
/// Path is inside the `.hg` folder |
| 65 |
InsideDotHg(HgPathBuf), |
| 66 |
IsInsideNestedRepo { |
| 67 |
path: HgPathBuf, |
| 68 |
nested_repo: HgPathBuf, |
| 69 |
}, |
| 70 |
TraversesSymbolicLink { |
| 71 |
path: HgPathBuf, |
| 72 |
symlink: HgPathBuf, |
| 73 |
}, |
| 74 |
NotFsCompliant(HgPathBuf), |
| 75 |
/// `path` is the smallest invalid path |
| 76 |
NotUnderRoot { |
| 77 |
path: PathBuf, |
| 78 |
root: PathBuf, |
| 79 |
}, |
| 80 |
} |
| 81 |
|
| 82 |
impl From<HgPathError> for HgError { |
| 83 |
fn from(value: HgPathError) -> Self { |
| 84 |
HgError::Path(value) |
| 85 |
} |
| 86 |
} |
| 87 |
|
| 88 |
impl fmt::Display for HgPathError { |
| 89 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 90 |
f.write_str(&self.backtrace.to_string())?; |
| 91 |
|
| 92 |
match &self.kind { |
| 93 |
HgPathErrorKind::LeadingSlash(bytes) => { |
| 94 |
write!(f, "Invalid HgPath '{:?}': has a leading slash.", bytes) |
| 95 |
} |
| 96 |
HgPathErrorKind::ConsecutiveSlashes { |
| 97 |
bytes, |
| 98 |
second_slash_index: pos, |
| 99 |
} => write!( |
| 100 |
f, |
| 101 |
"Invalid HgPath '{:?}': consecutive slashes at pos {}.", |
| 102 |
bytes, pos |
| 103 |
), |
| 104 |
HgPathErrorKind::ContainsNullByte { |
| 105 |
bytes, |
| 106 |
null_byte_index: pos, |
| 107 |
} => write!( |
| 108 |
f, |
| 109 |
"Invalid HgPath '{:?}': contains null byte at pos {}.", |
| 110 |
bytes, pos |
| 111 |
), |
| 112 |
HgPathErrorKind::DecodeError(bytes) => { |
| 113 |
write!(f, "Invalid HgPath '{:?}': could not be decoded.", bytes) |
| 114 |
} |
| 115 |
HgPathErrorKind::EndsWithSlash(path) => { |
| 116 |
write!(f, "path '{}': ends with a slash", path) |
| 117 |
} |
| 118 |
HgPathErrorKind::ContainsIllegalComponent(path) => { |
| 119 |
write!(f, "path contains illegal component: {}", path) |
| 120 |
} |
| 121 |
HgPathErrorKind::InsideDotHg(path) => { |
| 122 |
write!(f, "path '{}' is inside the '.hg' folder", path) |
| 123 |
} |
| 124 |
HgPathErrorKind::IsInsideNestedRepo { |
| 125 |
path, |
| 126 |
nested_repo: nested, |
| 127 |
} => { |
| 128 |
write!(f, "path '{}' is inside nested repo '{}'", path, nested) |
| 129 |
} |
| 130 |
HgPathErrorKind::TraversesSymbolicLink { path, symlink } => { |
| 131 |
write!( |
| 132 |
f, |
| 133 |
"path '{}' traverses symbolic link '{}'", |
| 134 |
path, symlink |
| 135 |
) |
| 136 |
} |
| 137 |
HgPathErrorKind::NotFsCompliant(path) => write!( |
| 138 |
f, |
| 139 |
"path '{}' cannot be turned into a \ |
| 140 |
filesystem path", |
| 141 |
path |
| 142 |
), |
| 143 |
HgPathErrorKind::NotUnderRoot { path, root } => write!( |
| 144 |
f, |
| 145 |
"path '{}' not under root {}", |
| 146 |
path.display(), |
| 147 |
root.display() |
| 148 |
), |
| 149 |
} |
| 150 |
} |
| 151 |
} |
| 152 |
|
| 153 |
/// This is a repository-relative path (or canonical path): |
| 154 |
/// - no null characters |
| 155 |
/// - `/` separates directories |
| 156 |
/// - no consecutive slashes |
| 157 |
/// - no leading slash, |
| 158 |
/// - no `.` nor `..` of special meaning |
| 159 |
/// - stored in repository and shared across platforms |
| 160 |
/// |
| 161 |
/// Note: there is no guarantee of any `HgPath` being well-formed at any point |
| 162 |
/// in its lifetime for performance reasons and to ease ergonomics. It is |
| 163 |
/// however checked using the `check_state` method before any file-system |
| 164 |
/// operation. |
| 165 |
/// |
| 166 |
/// This allows us to be encoding-transparent as much as possible, until really |
| 167 |
/// needed; `HgPath` can be transformed into a platform-specific path (`OsStr` |
| 168 |
/// or `Path`) whenever more complex operations are needed: |
| 169 |
/// On Unix, it's just byte-to-byte conversion. On Windows, it has to be |
| 170 |
/// decoded from MBCS to WTF-8. If WindowsUTF8Plan is implemented, the source |
| 171 |
/// character encoding will be determined on a per-repository basis. |
| 172 |
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash)] |
| 173 |
#[repr(transparent)] |
| 174 |
pub struct HgPath { |
| 175 |
inner: [u8], |
| 176 |
} |
| 177 |
|
| 178 |
impl HgPath { |
| 179 |
pub fn new<S: AsRef<[u8]> + ?Sized>(s: &S) -> &Self { |
| 180 |
unsafe { &*(s.as_ref() as *const [u8] as *const Self) } |
| 181 |
} |
| 182 |
pub fn is_empty(&self) -> bool { |
| 183 |
self.inner.is_empty() |
| 184 |
} |
| 185 |
pub fn len(&self) -> usize { |
| 186 |
self.inner.len() |
| 187 |
} |
| 188 |
fn to_hg_path_buf(&self) -> HgPathBuf { |
| 189 |
HgPathBuf { inner: self.inner.to_owned() } |
| 190 |
} |
| 191 |
pub fn bytes(&self) -> std::slice::Iter<u8> { |
| 192 |
self.inner.iter() |
| 193 |
} |
| 194 |
pub fn to_ascii_uppercase(&self) -> HgPathBuf { |
| 195 |
HgPathBuf::from(self.inner.to_ascii_uppercase()) |
| 196 |
} |
| 197 |
pub fn to_ascii_lowercase(&self) -> HgPathBuf { |
| 198 |
HgPathBuf::from(self.inner.to_ascii_lowercase()) |
| 199 |
} |
| 200 |
pub fn as_bytes(&self) -> &[u8] { |
| 201 |
&self.inner |
| 202 |
} |
| 203 |
pub fn contains(&self, other: u8) -> bool { |
| 204 |
self.inner.contains(&other) |
| 205 |
} |
| 206 |
pub fn starts_with(&self, needle: impl AsRef<Self>) -> bool { |
| 207 |
self.inner.starts_with(needle.as_ref().as_bytes()) |
| 208 |
} |
| 209 |
pub fn trim_trailing_slash(&self) -> &Self { |
| 210 |
Self::new(if self.inner.last() == Some(&b'/') { |
| 211 |
&self.inner[..self.inner.len() - 1] |
| 212 |
} else { |
| 213 |
&self.inner[..] |
| 214 |
}) |
| 215 |
} |
| 216 |
/// Returns a tuple of slices `(base, filename)` resulting from the split |
| 217 |
/// at the rightmost `/`, if any. |
| 218 |
/// |
| 219 |
/// # Examples: |
| 220 |
/// |
| 221 |
/// ``` |
| 222 |
/// use hg::utils::hg_path::HgPath; |
| 223 |
/// |
| 224 |
/// let path = HgPath::new(b"cool/hg/path").split_filename(); |
| 225 |
/// assert_eq!(path, (HgPath::new(b"cool/hg"), HgPath::new(b"path"))); |
| 226 |
/// |
| 227 |
/// let path = HgPath::new(b"pathwithoutsep").split_filename(); |
| 228 |
/// assert_eq!(path, (HgPath::new(b""), HgPath::new(b"pathwithoutsep"))); |
| 229 |
/// ``` |
| 230 |
pub fn split_filename(&self) -> (&Self, &Self) { |
| 231 |
match &self.inner.iter().rposition(|c| *c == b'/') { |
| 232 |
None => (HgPath::new(""), self), |
| 233 |
Some(size) => ( |
| 234 |
HgPath::new(&self.inner[..*size]), |
| 235 |
HgPath::new(&self.inner[*size + 1..]), |
| 236 |
), |
| 237 |
} |
| 238 |
} |
| 239 |
|
| 240 |
pub fn join(&self, path: &HgPath) -> HgPathBuf { |
| 241 |
let mut buf = self.to_owned(); |
| 242 |
buf.push(path); |
| 243 |
buf |
| 244 |
} |
| 245 |
|
| 246 |
pub fn components(&self) -> impl Iterator<Item = &HgPath> { |
| 247 |
self.inner.split(|&byte| byte == b'/').map(HgPath::new) |
| 248 |
} |
| 249 |
|
| 250 |
/// Returns the first (that is "root-most") slash-separated component of |
| 251 |
/// the path, and the rest after the first slash if there is one. |
| 252 |
pub fn split_first_component(&self) -> (&HgPath, Option<&HgPath>) { |
| 253 |
match self.inner.split_2(b'/') { |
| 254 |
Some((a, b)) => (HgPath::new(a), Some(HgPath::new(b))), |
| 255 |
None => (self, None), |
| 256 |
} |
| 257 |
} |
| 258 |
|
| 259 |
pub fn parent(&self) -> &Self { |
| 260 |
let inner = self.as_bytes(); |
| 261 |
HgPath::new(match inner.iter().rposition(|b| *b == b'/') { |
| 262 |
Some(pos) => &inner[..pos], |
| 263 |
None => &[], |
| 264 |
}) |
| 265 |
} |
| 266 |
/// Given a base directory, returns the slice of `self` relative to the |
| 267 |
/// base directory. If `base` is not a directory (does not end with a |
| 268 |
/// `b'/'`), returns `None`. |
| 269 |
pub fn relative_to(&self, base: impl AsRef<Self>) -> Option<&Self> { |
| 270 |
let base = base.as_ref(); |
| 271 |
if base.is_empty() { |
| 272 |
return Some(self); |
| 273 |
} |
| 274 |
let is_dir = base.as_bytes().ends_with(b"/"); |
| 275 |
if is_dir && self.starts_with(base) { |
| 276 |
Some(Self::new(&self.inner[base.len()..])) |
| 277 |
} else { |
| 278 |
None |
| 279 |
} |
| 280 |
} |
| 281 |
|
| 282 |
#[cfg(windows)] |
| 283 |
/// Copied from the Python stdlib's `os.path.splitdrive` implementation. |
| 284 |
/// |
| 285 |
/// Split a pathname into drive/UNC sharepoint and relative path |
| 286 |
/// specifiers. Returns a 2-tuple (drive_or_unc, path); either part may |
| 287 |
/// be empty. |
| 288 |
/// |
| 289 |
/// If you assign |
| 290 |
/// result = split_drive(p) |
| 291 |
/// It is always true that: |
| 292 |
/// result[0] + result[1] == p |
| 293 |
/// |
| 294 |
/// If the path contained a drive letter, drive_or_unc will contain |
| 295 |
/// everything up to and including the colon. |
| 296 |
/// e.g. split_drive("c:/dir") returns ("c:", "/dir") |
| 297 |
/// |
| 298 |
/// If the path contained a UNC path, the drive_or_unc will contain the |
| 299 |
/// host name and share up to but not including the fourth directory |
| 300 |
/// separator character. |
| 301 |
/// e.g. split_drive("//host/computer/dir") returns ("//host/computer", |
| 302 |
/// "/dir") |
| 303 |
/// |
| 304 |
/// Paths cannot contain both a drive letter and a UNC path. |
| 305 |
pub fn split_drive<'a>(&self) -> (&HgPath, &HgPath) { |
| 306 |
let bytes = self.as_bytes(); |
| 307 |
let is_sep = |b| std::path::is_separator(b as char); |
| 308 |
|
| 309 |
if self.len() < 2 { |
| 310 |
(HgPath::new(b""), &self) |
| 311 |
} else if is_sep(bytes[0]) |
| 312 |
&& is_sep(bytes[1]) |
| 313 |
&& (self.len() == 2 || !is_sep(bytes[2])) |
| 314 |
{ |
| 315 |
// Is a UNC path: |
| 316 |
// vvvvvvvvvvvvvvvvvvvv drive letter or UNC path |
| 317 |
// \\machine\mountpoint\directory\etc\... |
| 318 |
// directory ^^^^^^^^^^^^^^^ |
| 319 |
|
| 320 |
let machine_end_index = bytes[2..].iter().position(|b| is_sep(*b)); |
| 321 |
let mountpoint_start_index = if let Some(i) = machine_end_index { |
| 322 |
i + 2 |
| 323 |
} else { |
| 324 |
return (HgPath::new(b""), &self); |
| 325 |
}; |
| 326 |
|
| 327 |
match bytes[mountpoint_start_index + 1..] |
| 328 |
.iter() |
| 329 |
.position(|b| is_sep(*b)) |
| 330 |
{ |
| 331 |
// A UNC path can't have two slashes in a row |
| 332 |
// (after the initial two) |
| 333 |
Some(0) => (HgPath::new(b""), &self), |
| 334 |
Some(i) => { |
| 335 |
let (a, b) = bytes.split_at(mountpoint_start_index + 1 + i); |
| 336 |
(HgPath::new(a), HgPath::new(b)) |
| 337 |
} |
| 338 |
None => (&self, HgPath::new(b"")), |
| 339 |
} |
| 340 |
} else if bytes[1] == b':' { |
| 341 |
// Drive path c:\directory |
| 342 |
let (a, b) = bytes.split_at(2); |
| 343 |
(HgPath::new(a), HgPath::new(b)) |
| 344 |
} else { |
| 345 |
(HgPath::new(b""), &self) |
| 346 |
} |
| 347 |
} |
| 348 |
|
| 349 |
#[cfg(unix)] |
| 350 |
/// Split a pathname into drive and path. On Posix, drive is always empty. |
| 351 |
pub fn split_drive(&self) -> (&HgPath, &HgPath) { |
| 352 |
(HgPath::new(b""), self) |
| 353 |
} |
| 354 |
|
| 355 |
/// Checks for errors in the path, short-circuiting at the first one. |
| 356 |
/// This generates fine-grained errors useful for debugging. |
| 357 |
/// To simply check if the path is valid during tests, use `is_valid`. |
| 358 |
pub fn check_state(&self) -> Result<(), HgPathErrorKind> { |
| 359 |
if self.is_empty() { |
| 360 |
return Ok(()); |
| 361 |
} |
| 362 |
let bytes = self.as_bytes(); |
| 363 |
let mut previous_byte = None; |
| 364 |
|
| 365 |
if bytes[0] == b'/' { |
| 366 |
return Err(HgPathErrorKind::LeadingSlash(bytes.to_vec())); |
| 367 |
} |
| 368 |
for (index, byte) in bytes.iter().enumerate() { |
| 369 |
match byte { |
| 370 |
0 => { |
| 371 |
return Err(HgPathErrorKind::ContainsNullByte { |
| 372 |
bytes: bytes.to_vec(), |
| 373 |
null_byte_index: index, |
| 374 |
}) |
| 375 |
} |
| 376 |
b'/' => { |
| 377 |
if previous_byte.is_some() && previous_byte == Some(b'/') { |
| 378 |
return Err(HgPathErrorKind::ConsecutiveSlashes { |
| 379 |
bytes: bytes.to_vec(), |
| 380 |
second_slash_index: index, |
| 381 |
}); |
| 382 |
} |
| 383 |
} |
| 384 |
_ => (), |
| 385 |
}; |
| 386 |
previous_byte = Some(*byte); |
| 387 |
} |
| 388 |
Ok(()) |
| 389 |
} |
| 390 |
|
| 391 |
#[cfg(test)] |
| 392 |
/// Only usable during tests to force developers to handle invalid states |
| 393 |
fn is_valid(&self) -> bool { |
| 394 |
self.check_state().is_ok() |
| 395 |
} |
| 396 |
} |
| 397 |
|
| 398 |
impl fmt::Debug for HgPath { |
| 399 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 400 |
write!(f, "HgPath({:?})", String::from_utf8_lossy(&self.inner)) |
| 401 |
} |
| 402 |
} |
| 403 |
|
| 404 |
impl fmt::Display for HgPath { |
| 405 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 406 |
write!(f, "{}", String::from_utf8_lossy(&self.inner)) |
| 407 |
} |
| 408 |
} |
| 409 |
|
| 410 |
#[derive( |
| 411 |
Default, Eq, Ord, Clone, PartialEq, PartialOrd, Hash, derive_more::From, |
| 412 |
)] |
| 413 |
pub struct HgPathBuf { |
| 414 |
inner: Vec<u8>, |
| 415 |
} |
| 416 |
|
| 417 |
impl HgPathBuf { |
| 418 |
pub fn new() -> Self { |
| 419 |
Default::default() |
| 420 |
} |
| 421 |
|
| 422 |
pub fn push<T: ?Sized + AsRef<HgPath>>(&mut self, other: &T) { |
| 423 |
if !self.inner.is_empty() && self.inner.last() != Some(&b'/') { |
| 424 |
self.inner.push(b'/'); |
| 425 |
} |
| 426 |
self.inner.extend(other.as_ref().bytes()) |
| 427 |
} |
| 428 |
|
| 429 |
pub fn push_byte(&mut self, byte: u8) { |
| 430 |
self.inner.push(byte); |
| 431 |
} |
| 432 |
pub fn from_bytes(s: &[u8]) -> HgPathBuf { |
| 433 |
HgPath::new(s).to_owned() |
| 434 |
} |
| 435 |
pub fn into_vec(self) -> Vec<u8> { |
| 436 |
self.inner |
| 437 |
} |
| 438 |
} |
| 439 |
|
| 440 |
impl fmt::Debug for HgPathBuf { |
| 441 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 442 |
write!(f, "HgPathBuf({:?})", String::from_utf8_lossy(&self.inner)) |
| 443 |
} |
| 444 |
} |
| 445 |
|
| 446 |
impl fmt::Display for HgPathBuf { |
| 447 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 448 |
write!(f, "{}", String::from_utf8_lossy(&self.inner)) |
| 449 |
} |
| 450 |
} |
| 451 |
|
| 452 |
impl Deref for HgPathBuf { |
| 453 |
type Target = HgPath; |
| 454 |
|
| 455 |
#[inline] |
| 456 |
fn deref(&self) -> &HgPath { |
| 457 |
HgPath::new(&self.inner) |
| 458 |
} |
| 459 |
} |
| 460 |
|
| 461 |
impl<T: ?Sized + AsRef<HgPath>> From<&T> for HgPathBuf { |
| 462 |
fn from(s: &T) -> HgPathBuf { |
| 463 |
s.as_ref().to_owned() |
| 464 |
} |
| 465 |
} |
| 466 |
|
| 467 |
impl From<HgPathBuf> for Vec<u8> { |
| 468 |
fn from(val: HgPathBuf) -> Self { |
| 469 |
val.inner |
| 470 |
} |
| 471 |
} |
| 472 |
|
| 473 |
impl Borrow<HgPath> for HgPathBuf { |
| 474 |
fn borrow(&self) -> &HgPath { |
| 475 |
HgPath::new(self.as_bytes()) |
| 476 |
} |
| 477 |
} |
| 478 |
|
| 479 |
impl ToOwned for HgPath { |
| 480 |
type Owned = HgPathBuf; |
| 481 |
|
| 482 |
fn to_owned(&self) -> HgPathBuf { |
| 483 |
self.to_hg_path_buf() |
| 484 |
} |
| 485 |
} |
| 486 |
|
| 487 |
impl AsRef<HgPath> for HgPath { |
| 488 |
fn as_ref(&self) -> &HgPath { |
| 489 |
self |
| 490 |
} |
| 491 |
} |
| 492 |
|
| 493 |
impl AsRef<HgPath> for HgPathBuf { |
| 494 |
fn as_ref(&self) -> &HgPath { |
| 495 |
self |
| 496 |
} |
| 497 |
} |
| 498 |
|
| 499 |
impl Extend<u8> for HgPathBuf { |
| 500 |
fn extend<T: IntoIterator<Item = u8>>(&mut self, iter: T) { |
| 501 |
self.inner.extend(iter); |
| 502 |
} |
| 503 |
} |
| 504 |
|
| 505 |
/// Create a new [`OsString`] from types referenceable as [`HgPath`]. |
| 506 |
/// |
| 507 |
/// TODO: Once <https://www.mercurial-scm.org/wiki/WindowsUTF8Plan> is |
| 508 |
/// implemented, these conversion utils will have to work differently depending |
| 509 |
/// on the repository encoding: either `UTF-8` or `MBCS`. |
| 510 |
pub fn hg_path_to_os_string<P: AsRef<HgPath>>( |
| 511 |
hg_path: P, |
| 512 |
) -> Result<OsString, HgPathErrorKind> { |
| 513 |
hg_path.as_ref().check_state()?; |
| 514 |
let os_str; |
| 515 |
#[cfg(unix)] |
| 516 |
{ |
| 517 |
use std::os::unix::ffi::OsStrExt; |
| 518 |
os_str = std::ffi::OsStr::from_bytes(hg_path.as_ref().as_bytes()); |
| 519 |
} |
| 520 |
// TODO Handle other platforms |
| 521 |
// TODO: convert from WTF8 to Windows MBCS (ANSI encoding). |
| 522 |
Ok(os_str.to_os_string()) |
| 523 |
} |
| 524 |
|
| 525 |
/// Create a new [`PathBuf`] from types referenceable as [`HgPath`]. |
| 526 |
pub fn hg_path_to_path_buf<P: AsRef<HgPath>>( |
| 527 |
hg_path: P, |
| 528 |
) -> Result<PathBuf, HgPathError> { |
| 529 |
Ok(Path::new(&hg_path_to_os_string(hg_path)?).to_path_buf()) |
| 530 |
} |
| 531 |
|
| 532 |
/// Create a new [`HgPathBuf`] from types referenceable as [`OsStr`]. |
| 533 |
pub fn os_string_to_hg_path_buf<S: AsRef<OsStr>>( |
| 534 |
os_string: S, |
| 535 |
) -> Result<HgPathBuf, HgPathError> { |
| 536 |
let buf; |
| 537 |
#[cfg(unix)] |
| 538 |
{ |
| 539 |
use std::os::unix::ffi::OsStrExt; |
| 540 |
buf = HgPathBuf::from_bytes(os_string.as_ref().as_bytes()); |
| 541 |
} |
| 542 |
// TODO Handle other platforms |
| 543 |
// TODO: convert from WTF8 to Windows MBCS (ANSI encoding). |
| 544 |
|
| 545 |
buf.check_state()?; |
| 546 |
Ok(buf) |
| 547 |
} |
| 548 |
|
| 549 |
/// Create a new [`HgPathBuf`] from types referenceable as [`Path`]. |
| 550 |
pub fn path_to_hg_path_buf<P: AsRef<Path>>( |
| 551 |
path: P, |
| 552 |
) -> Result<HgPathBuf, HgPathError> { |
| 553 |
let buf; |
| 554 |
let os_str = path.as_ref().as_os_str(); |
| 555 |
#[cfg(unix)] |
| 556 |
{ |
| 557 |
use std::os::unix::ffi::OsStrExt; |
| 558 |
buf = HgPathBuf::from_bytes(os_str.as_bytes()); |
| 559 |
} |
| 560 |
// TODO Handle other platforms |
| 561 |
// TODO: convert from WTF8 to Windows MBCS (ANSI encoding). |
| 562 |
|
| 563 |
buf.check_state()?; |
| 564 |
Ok(buf) |
| 565 |
} |
| 566 |
|
| 567 |
impl TryFrom<PathBuf> for HgPathBuf { |
| 568 |
type Error = HgPathError; |
| 569 |
fn try_from(path: PathBuf) -> Result<Self, Self::Error> { |
| 570 |
path_to_hg_path_buf(path) |
| 571 |
} |
| 572 |
} |
| 573 |
|
| 574 |
impl From<HgPathBuf> for Cow<'_, HgPath> { |
| 575 |
fn from(path: HgPathBuf) -> Self { |
| 576 |
Cow::Owned(path) |
| 577 |
} |
| 578 |
} |
| 579 |
|
| 580 |
impl<'a> From<&'a HgPath> for Cow<'a, HgPath> { |
| 581 |
fn from(path: &'a HgPath) -> Self { |
| 582 |
Cow::Borrowed(path) |
| 583 |
} |
| 584 |
} |
| 585 |
|
| 586 |
impl<'a> From<&'a HgPathBuf> for Cow<'a, HgPath> { |
| 587 |
fn from(path: &'a HgPathBuf) -> Self { |
| 588 |
Cow::Borrowed(&**path) |
| 589 |
} |
| 590 |
} |
| 591 |
|
| 592 |
#[cfg(test)] |
| 593 |
mod tests { |
| 594 |
use pretty_assertions::assert_eq; |
| 595 |
|
| 596 |
use super::*; |
| 597 |
|
| 598 |
#[test] |
| 599 |
fn test_path_states() { |
| 600 |
assert_eq!( |
| 601 |
Err(HgPathErrorKind::LeadingSlash(b"/".to_vec())), |
| 602 |
HgPath::new(b"/").check_state() |
| 603 |
); |
| 604 |
assert_eq!( |
| 605 |
Err(HgPathErrorKind::ConsecutiveSlashes { |
| 606 |
bytes: b"a/b//c".to_vec(), |
| 607 |
second_slash_index: 4 |
| 608 |
}), |
| 609 |
HgPath::new(b"a/b//c").check_state() |
| 610 |
); |
| 611 |
assert_eq!( |
| 612 |
Err(HgPathErrorKind::ContainsNullByte { |
| 613 |
bytes: b"a/b/\0c".to_vec(), |
| 614 |
null_byte_index: 4 |
| 615 |
}), |
| 616 |
HgPath::new(b"a/b/\0c").check_state() |
| 617 |
); |
| 618 |
// TODO test HgPathError::DecodeError for the Windows implementation. |
| 619 |
assert_eq!(true, HgPath::new(b"").is_valid()); |
| 620 |
assert_eq!(true, HgPath::new(b"a/b/c").is_valid()); |
| 621 |
// Backslashes in paths are not significant, but allowed |
| 622 |
assert_eq!(true, HgPath::new(br"a\b/c").is_valid()); |
| 623 |
// Dots in paths are not significant, but allowed |
| 624 |
assert_eq!(true, HgPath::new(b"a/b/../c/").is_valid()); |
| 625 |
assert_eq!(true, HgPath::new(b"./a/b/../c/").is_valid()); |
| 626 |
} |
| 627 |
|
| 628 |
#[test] |
| 629 |
fn test_iter() { |
| 630 |
let path = HgPath::new(b"a"); |
| 631 |
let mut iter = path.bytes(); |
| 632 |
assert_eq!(Some(&b'a'), iter.next()); |
| 633 |
assert_eq!(None, iter.next_back()); |
| 634 |
assert_eq!(None, iter.next()); |
| 635 |
|
| 636 |
let path = HgPath::new(b"a"); |
| 637 |
let mut iter = path.bytes(); |
| 638 |
assert_eq!(Some(&b'a'), iter.next_back()); |
| 639 |
assert_eq!(None, iter.next_back()); |
| 640 |
assert_eq!(None, iter.next()); |
| 641 |
|
| 642 |
let path = HgPath::new(b"abc"); |
| 643 |
let mut iter = path.bytes(); |
| 644 |
assert_eq!(Some(&b'a'), iter.next()); |
| 645 |
assert_eq!(Some(&b'c'), iter.next_back()); |
| 646 |
assert_eq!(Some(&b'b'), iter.next_back()); |
| 647 |
assert_eq!(None, iter.next_back()); |
| 648 |
assert_eq!(None, iter.next()); |
| 649 |
|
| 650 |
let path = HgPath::new(b"abc"); |
| 651 |
let mut iter = path.bytes(); |
| 652 |
assert_eq!(Some(&b'a'), iter.next()); |
| 653 |
assert_eq!(Some(&b'b'), iter.next()); |
| 654 |
assert_eq!(Some(&b'c'), iter.next()); |
| 655 |
assert_eq!(None, iter.next_back()); |
| 656 |
assert_eq!(None, iter.next()); |
| 657 |
|
| 658 |
let path = HgPath::new(b"abc"); |
| 659 |
let iter = path.bytes(); |
| 660 |
let mut vec = Vec::new(); |
| 661 |
vec.extend(iter); |
| 662 |
assert_eq!(vec![b'a', b'b', b'c'], vec); |
| 663 |
|
| 664 |
let path = HgPath::new(b"abc"); |
| 665 |
let mut iter = path.bytes(); |
| 666 |
assert_eq!(Some(2), iter.rposition(|c| *c == b'c')); |
| 667 |
|
| 668 |
let path = HgPath::new(b"abc"); |
| 669 |
let mut iter = path.bytes(); |
| 670 |
assert_eq!(None, iter.rposition(|c| *c == b'd')); |
| 671 |
} |
| 672 |
|
| 673 |
#[test] |
| 674 |
fn test_join() { |
| 675 |
let path = HgPathBuf::from_bytes(b"a").join(HgPath::new(b"b")); |
| 676 |
assert_eq!(b"a/b", path.as_bytes()); |
| 677 |
|
| 678 |
let path = HgPathBuf::from_bytes(b"a/").join(HgPath::new(b"b/c")); |
| 679 |
assert_eq!(b"a/b/c", path.as_bytes()); |
| 680 |
|
| 681 |
// No leading slash if empty before join |
| 682 |
let path = HgPathBuf::new().join(HgPath::new(b"b/c")); |
| 683 |
assert_eq!(b"b/c", path.as_bytes()); |
| 684 |
|
| 685 |
// The leading slash is an invalid representation of an `HgPath`, but |
| 686 |
// it can happen. This creates another invalid representation of |
| 687 |
// consecutive bytes. |
| 688 |
// TODO What should be done in this case? Should we silently remove |
| 689 |
// the extra slash? Should we change the signature to a problematic |
| 690 |
// `Result<HgPathBuf, HgPathError>`, or should we just keep it so and |
| 691 |
// let the error happen upon filesystem interaction? |
| 692 |
let path = HgPathBuf::from_bytes(b"a/").join(HgPath::new(b"/b")); |
| 693 |
assert_eq!(b"a//b", path.as_bytes()); |
| 694 |
let path = HgPathBuf::from_bytes(b"a").join(HgPath::new(b"/b")); |
| 695 |
assert_eq!(b"a//b", path.as_bytes()); |
| 696 |
} |
| 697 |
|
| 698 |
#[test] |
| 699 |
fn test_relative_to() { |
| 700 |
let path = HgPath::new(b""); |
| 701 |
let base = HgPath::new(b""); |
| 702 |
assert_eq!(Some(path), path.relative_to(base)); |
| 703 |
|
| 704 |
let path = HgPath::new(b"path"); |
| 705 |
let base = HgPath::new(b""); |
| 706 |
assert_eq!(Some(path), path.relative_to(base)); |
| 707 |
|
| 708 |
let path = HgPath::new(b"a"); |
| 709 |
let base = HgPath::new(b"b"); |
| 710 |
assert_eq!(None, path.relative_to(base)); |
| 711 |
|
| 712 |
let path = HgPath::new(b"a/b"); |
| 713 |
let base = HgPath::new(b"a"); |
| 714 |
assert_eq!(None, path.relative_to(base)); |
| 715 |
|
| 716 |
let path = HgPath::new(b"a/b"); |
| 717 |
let base = HgPath::new(b"a/"); |
| 718 |
assert_eq!(Some(HgPath::new(b"b")), path.relative_to(base)); |
| 719 |
|
| 720 |
let path = HgPath::new(b"nested/path/to/b"); |
| 721 |
let base = HgPath::new(b"nested/path/"); |
| 722 |
assert_eq!(Some(HgPath::new(b"to/b")), path.relative_to(base)); |
| 723 |
|
| 724 |
let path = HgPath::new(b"ends/with/dir/"); |
| 725 |
let base = HgPath::new(b"ends/"); |
| 726 |
assert_eq!(Some(HgPath::new(b"with/dir/")), path.relative_to(base)); |
| 727 |
} |
| 728 |
|
| 729 |
#[test] |
| 730 |
#[cfg(unix)] |
| 731 |
fn test_split_drive() { |
| 732 |
// Taken from the Python stdlib's tests |
| 733 |
assert_eq!( |
| 734 |
HgPath::new(br"/foo/bar").split_drive(), |
| 735 |
(HgPath::new(b""), HgPath::new(br"/foo/bar")) |
| 736 |
); |
| 737 |
assert_eq!( |
| 738 |
HgPath::new(br"foo:bar").split_drive(), |
| 739 |
(HgPath::new(b""), HgPath::new(br"foo:bar")) |
| 740 |
); |
| 741 |
assert_eq!( |
| 742 |
HgPath::new(br":foo:bar").split_drive(), |
| 743 |
(HgPath::new(b""), HgPath::new(br":foo:bar")) |
| 744 |
); |
| 745 |
// Also try NT paths; should not split them |
| 746 |
assert_eq!( |
| 747 |
HgPath::new(br"c:\foo\bar").split_drive(), |
| 748 |
(HgPath::new(b""), HgPath::new(br"c:\foo\bar")) |
| 749 |
); |
| 750 |
assert_eq!( |
| 751 |
HgPath::new(b"c:/foo/bar").split_drive(), |
| 752 |
(HgPath::new(b""), HgPath::new(br"c:/foo/bar")) |
| 753 |
); |
| 754 |
assert_eq!( |
| 755 |
HgPath::new(br"\\conky\mountpoint\foo\bar").split_drive(), |
| 756 |
(HgPath::new(b""), HgPath::new(br"\\conky\mountpoint\foo\bar")) |
| 757 |
); |
| 758 |
} |
| 759 |
|
| 760 |
#[test] |
| 761 |
#[cfg(windows)] |
| 762 |
fn test_split_drive() { |
| 763 |
assert_eq!( |
| 764 |
HgPath::new(br"c:\foo\bar").split_drive(), |
| 765 |
(HgPath::new(br"c:"), HgPath::new(br"\foo\bar")) |
| 766 |
); |
| 767 |
assert_eq!( |
| 768 |
HgPath::new(b"c:/foo/bar").split_drive(), |
| 769 |
(HgPath::new(br"c:"), HgPath::new(br"/foo/bar")) |
| 770 |
); |
| 771 |
assert_eq!( |
| 772 |
HgPath::new(br"\\conky\mountpoint\foo\bar").split_drive(), |
| 773 |
(HgPath::new(br"\\conky\mountpoint"), HgPath::new(br"\foo\bar")) |
| 774 |
); |
| 775 |
assert_eq!( |
| 776 |
HgPath::new(br"//conky/mountpoint/foo/bar").split_drive(), |
| 777 |
(HgPath::new(br"//conky/mountpoint"), HgPath::new(br"/foo/bar")) |
| 778 |
); |
| 779 |
assert_eq!( |
| 780 |
HgPath::new(br"\\\conky\mountpoint\foo\bar").split_drive(), |
| 781 |
(HgPath::new(br""), HgPath::new(br"\\\conky\mountpoint\foo\bar")) |
| 782 |
); |
| 783 |
assert_eq!( |
| 784 |
HgPath::new(br"///conky/mountpoint/foo/bar").split_drive(), |
| 785 |
(HgPath::new(br""), HgPath::new(br"///conky/mountpoint/foo/bar")) |
| 786 |
); |
| 787 |
assert_eq!( |
| 788 |
HgPath::new(br"\\conky\\mountpoint\foo\bar").split_drive(), |
| 789 |
(HgPath::new(br""), HgPath::new(br"\\conky\\mountpoint\foo\bar")) |
| 790 |
); |
| 791 |
assert_eq!( |
| 792 |
HgPath::new(br"//conky//mountpoint/foo/bar").split_drive(), |
| 793 |
(HgPath::new(br""), HgPath::new(br"//conky//mountpoint/foo/bar")) |
| 794 |
); |
| 795 |
// UNC part containing U+0130 |
| 796 |
assert_eq!( |
| 797 |
HgPath::new(b"//conky/MOUNTPO\xc4\xb0NT/foo/bar").split_drive(), |
| 798 |
( |
| 799 |
HgPath::new(b"//conky/MOUNTPO\xc4\xb0NT"), |
| 800 |
HgPath::new(br"/foo/bar") |
| 801 |
) |
| 802 |
); |
| 803 |
} |
| 804 |
|
| 805 |
#[test] |
| 806 |
fn test_parent() { |
| 807 |
let path = HgPath::new(b""); |
| 808 |
assert_eq!(path.parent(), path); |
| 809 |
|
| 810 |
let path = HgPath::new(b"a"); |
| 811 |
assert_eq!(path.parent(), HgPath::new(b"")); |
| 812 |
|
| 813 |
let path = HgPath::new(b"a/b"); |
| 814 |
assert_eq!(path.parent(), HgPath::new(b"a")); |
| 815 |
|
| 816 |
let path = HgPath::new(b"a/other/b"); |
| 817 |
assert_eq!(path.parent(), HgPath::new(b"a/other")); |
| 818 |
} |
| 819 |
} |