Vendor dependencies

This commit is contained in:
2026-08-01 16:11:49 +03:00
parent 7f139a0241
commit 6b5e7f0f8b
29706 changed files with 9575646 additions and 0 deletions
@@ -0,0 +1 @@
{"$comment":"This file only protects against accidental modifications. It is not a security mechanism and does not protect against malicious changes.","files":{".cargo_vcs_info.json":"3005ab439f73b2495b27f59777ef0bfd520822c2a46bdbe62d04804c59b77a18","Cargo.toml":"fec1ad4ee9bf924b1841e0a03cf95637b76288abdf8326d86f11276bbad948aa","Cargo.toml.orig":"891fa767cbdfc46dcc7d5fb040c3926b43b218d300a5be50d4c764d25acd1a1b","README.md":"0fdd5c56dfb35a1c3d9e0bdc8bf53fc235c19b12a011f4d72d5eb737956c1dc8","src/lib.rs":"e6d5bb7cb8f99ba35490b000ef9a122824e6373b362734d471849caebb08cfe8","src/path_ext.rs":"41f7f8b7b4edcac6646095f9024d1e2fb29ee75cd823143efd61c2feaa37b337","src/tests.rs":"e76ea59ac762fb0a3b605241e2b32f81aafa3e3070129914dc329dd5dd0609ed"},"package":"ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2"}
@@ -0,0 +1,6 @@
{
"git": {
"sha1": "6d267fbd85b257e4416c9f020131c6da168e1d3d"
},
"path_in_vcs": "relative-path"
}
+42
View File
@@ -0,0 +1,42 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2021"
rust-version = "1.66"
name = "relative-path"
version = "1.9.3"
authors = ["John-John Tedro <udoprog@tedro.se>"]
description = "Portable, relative paths for Rust."
homepage = "https://github.com/udoprog/relative-path"
documentation = "https://docs.rs/relative-path"
readme = "README.md"
keywords = ["path"]
categories = ["filesystem"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/udoprog/relative-path"
[package.metadata.docs.rs]
all-features = true
[dependencies.serde]
version = "1.0.160"
optional = true
[dev-dependencies.anyhow]
version = "1.0.76"
[dev-dependencies.serde]
version = "1.0.160"
features = ["derive"]
[features]
default = []
+27
View File
@@ -0,0 +1,27 @@
[package]
name = "relative-path"
version = "1.9.3"
authors = ["John-John Tedro <udoprog@tedro.se>"]
edition = "2021"
rust-version = "1.66"
description = "Portable, relative paths for Rust."
documentation = "https://docs.rs/relative-path"
readme = "README.md"
homepage = "https://github.com/udoprog/relative-path"
repository = "https://github.com/udoprog/relative-path"
license = "MIT OR Apache-2.0"
keywords = ["path"]
categories = ["filesystem"]
[features]
default = []
[dependencies]
serde = { version = "1.0.160", optional = true }
[dev-dependencies]
anyhow = "1.0.76"
serde = { version = "1.0.160", features = ["derive"] }
[package.metadata.docs.rs]
all-features = true
+279
View File
@@ -0,0 +1,279 @@
# relative-path
[<img alt="github" src="https://img.shields.io/badge/github-udoprog/relative--path-8da0cb?style=for-the-badge&logo=github" height="20">](https://github.com/udoprog/relative-path)
[<img alt="crates.io" src="https://img.shields.io/crates/v/relative-path.svg?style=for-the-badge&color=fc8d62&logo=rust" height="20">](https://crates.io/crates/relative-path)
[<img alt="docs.rs" src="https://img.shields.io/badge/docs.rs-relative--path-66c2a5?style=for-the-badge&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K" height="20">](https://docs.rs/relative-path)
[<img alt="build status" src="https://img.shields.io/github/actions/workflow/status/udoprog/relative-path/ci.yml?branch=main&style=for-the-badge" height="20">](https://github.com/udoprog/relative-path/actions?query=branch%3Amain)
Portable relative UTF-8 paths for Rust.
This crate provides a module analogous to [`std::path`], with the following
characteristics:
* The path separator is set to a fixed character (`/`), regardless of
platform.
* Relative paths cannot represent a path in the filesystem without first
specifying *what they are relative to* using functions such as [`to_path`]
and [`to_logical_path`].
* Relative paths are always guaranteed to be valid UTF-8 strings.
On top of this we support many operations that guarantee the same behavior
across platforms.
For more utilities to manipulate relative paths, see the
[`relative-path-utils` crate].
<br>
## Usage
Add `relative-path` to your `Cargo.toml`:
```toml
relative-path = "1.9.2"
```
Start using relative paths:
```rust
use serde::{Serialize, Deserialize};
use relative_path::RelativePath;
#[derive(Serialize, Deserialize)]
struct Manifest<'a> {
#[serde(borrow)]
source: &'a RelativePath,
}
```
<br>
## Serde Support
This library includes serde support that can be enabled with the `serde`
feature.
<br>
## Why is `std::path` a portability hazard?
Path representations differ across platforms.
* Windows permits using drive volumes (multiple roots) as a prefix (e.g.
`"c:\"`) and backslash (`\`) as a separator.
* Unix references absolute paths from a single root and uses forward slash
(`/`) as a separator.
If we use `PathBuf`, Storing paths in a manifest would allow our application
to build and run on one platform but potentially not others.
Consider the following data model and corresponding toml for a manifest:
```rust
use std::path::PathBuf;
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
struct Manifest {
source: PathBuf,
}
```
```toml
source = "C:\\Users\\udoprog\\repo\\data\\source"
```
This will run for you (assuming `source` exists). So you go ahead and check
the manifest into git. The next day your Linux colleague calls you and
wonders what they have ever done to wrong you?
So what went wrong? Well two things. You forgot to make the `source`
relative, so anyone at the company which has a different username than you
won't be able to use it. So you go ahead and fix that:
```toml
source = "data\\source"
```
But there is still one problem! A backslash (`\`) is only a legal path
separator on Windows. Luckily you learn that forward slashes are supported
both on Windows *and* Linux. So you opt for:
```toml
source = "data/source"
```
Things are working now. So all is well... Right? Sure, but we can do better.
This crate provides types that work with *portable relative paths* (hence
the name). So by using [`RelativePath`] we can systematically help avoid
portability issues like the one above. Avoiding issues at the source is
preferably over spending 5 minutes of onboarding time on a theoretical
problem, hoping that your new hires will remember what to do if they ever
encounter it.
Using [`RelativePathBuf`] we can fix our data model like this:
```rust
use relative_path::RelativePathBuf;
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
pub struct Manifest {
source: RelativePathBuf,
}
```
And where it's used:
```rust
use std::fs;
use std::env::current_dir;
let manifest: Manifest = todo!();
let root = current_dir()?;
let source = manifest.source.to_path(&root);
let content = fs::read(&source)?;
```
<br>
## Overview
Conversion to a platform-specific [`Path`] happens through the [`to_path`]
and [`to_logical_path`] functions. Where you are required to specify the
path that prefixes the relative path. This can come from a function such as
[`std::env::current_dir`].
```rust
use std::env::current_dir;
use std::path::Path;
use relative_path::RelativePath;
let root = current_dir()?;
// to_path unconditionally concatenates a relative path with its base:
let relative_path = RelativePath::new("../foo/./bar");
let full_path = relative_path.to_path(&root);
assert_eq!(full_path, root.join("..\\foo\\.\\bar"));
// to_logical_path tries to apply the logical operations that the relative
// path corresponds to:
let relative_path = RelativePath::new("../foo/./bar");
let full_path = relative_path.to_logical_path(&root);
// Replicate the operation performed by `to_logical_path`.
let mut parent = root.clone();
parent.pop();
assert_eq!(full_path, parent.join("foo\\bar"));
```
When two relative paths are compared to each other, their exact component
makeup determines equality.
```rust
use relative_path::RelativePath;
assert_ne!(
RelativePath::new("foo/bar/../baz"),
RelativePath::new("foo/baz")
);
```
Using platform-specific path separators to construct relative paths is not
supported.
Path separators from other platforms are simply treated as part of a
component:
```rust
use relative_path::RelativePath;
assert_ne!(
RelativePath::new("foo/bar"),
RelativePath::new("foo\\bar")
);
assert_eq!(1, RelativePath::new("foo\\bar").components().count());
assert_eq!(2, RelativePath::new("foo/bar").components().count());
```
To see if two relative paths are equivalent you can use [`normalize`]:
```rust
use relative_path::RelativePath;
assert_eq!(
RelativePath::new("foo/bar/../baz").normalize(),
RelativePath::new("foo/baz").normalize(),
);
```
<br>
## Additional portability notes
While relative paths avoid the most egregious portability issue, that
absolute paths will work equally unwell on all platforms. We cannot avoid
all. This section tries to document additional portability hazards that we
are aware of.
[`RelativePath`], similarly to [`Path`], makes no guarantees that its
constituent components make up legal file names. While components are
strictly separated by slashes, we can still store things in them which may
not be used as legal paths on all platforms.
* A `NUL` character is not permitted on unix platforms - this is a
terminator in C-based filesystem APIs. Slash (`/`) is also used as a path
separator.
* Windows has a number of [reserved characters and names][windows-reserved]
(like `CON`, `PRN`, and `AUX`) which cannot legally be part of a
filesystem component.
* Windows paths are [case-insensitive by default][windows-case]. So,
`Foo.txt` and `foo.txt` are the same files on windows. But they are
considered different paths on most unix systems.
A relative path that *accidentally* contains a platform-specific components
will largely result in a nonsensical paths being generated in the hope that
they will fail fast during development and testing.
```rust
use relative_path::{RelativePath, PathExt};
use std::path::Path;
if cfg!(windows) {
assert_eq!(
Path::new("foo\\c:\\bar\\baz"),
RelativePath::new("c:\\bar\\baz").to_path("foo")
);
}
if cfg!(unix) {
assert_eq!(
Path::new("foo/bar/baz"),
RelativePath::new("/bar/baz").to_path("foo")
);
}
assert_eq!(
Path::new("foo").relative_to("bar")?,
RelativePath::new("../foo"),
);
```
[`None`]: https://doc.rust-lang.org/std/option/enum.Option.html
[`normalize`]: https://docs.rs/relative-path/1/relative_path/struct.RelativePath.html#method.normalize
[`Path`]: https://doc.rust-lang.org/std/path/struct.Path.html
[`RelativePath`]: https://docs.rs/relative-path/1/relative_path/struct.RelativePath.html
[`RelativePathBuf`]: https://docs.rs/relative-path/1/relative_path/struct.RelativePathBuf.html
[`std::env::current_dir`]: https://doc.rust-lang.org/std/env/fn.current_dir.html
[`std::path`]: https://doc.rust-lang.org/std/path/index.html
[`to_logical_path`]: https://docs.rs/relative-path/1/relative_path/struct.RelativePath.html#method.to_logical_path
[`to_path`]: https://docs.rs/relative-path/1/relative_path/struct.RelativePath.html#method.to_path
[windows-reserved]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
[windows-case]: https://learn.microsoft.com/en-us/windows/wsl/case-sensitivity
[`relative-path-utils` crate]: https://docs.rs/relative-path-utils
File diff suppressed because it is too large Load Diff
+353
View File
@@ -0,0 +1,353 @@
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Ported from the pathdiff crate, which adapted the original rustc's
// path_relative_from
// https://github.com/Manishearth/pathdiff/blob/master/src/lib.rs
// https://github.com/rust-lang/rust/blob/e1d0de82cc40b666b88d4a6d2c9dcbc81d7ed27f/src/librustc_back/rpath.rs#L116-L158
use std::error;
use std::fmt;
use std::path::{Path, PathBuf};
use crate::{Component, RelativePathBuf};
// Prevent downstream implementations, so methods may be added without backwards
// breaking changes.
mod sealed {
use std::path::{Path, PathBuf};
pub trait Sealed {}
impl Sealed for Path {}
impl Sealed for PathBuf {}
}
/// An error raised when attempting to convert a path using
/// [`PathExt::relative_to`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RelativeToError {
kind: RelativeToErrorKind,
}
/// Error kind for [`RelativeToError`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
enum RelativeToErrorKind {
/// Non-utf8 component in path.
NonUtf8,
/// Mismatching path prefixes.
PrefixMismatch,
/// A provided path is ambiguous, in that there is no way to determine which
/// components should be added from one path to the other to traverse it.
///
/// For example, `.` is ambiguous relative to `../..` because we don't know
/// the names of the components being traversed.
AmbiguousTraversal,
/// This is a catch-all error since we don't control the `std::path` API a
/// Components iterator might decide (intentionally or not) to produce
/// components which violates its own contract.
///
/// In particular we rely on only relative components being produced after
/// the absolute prefix has been consumed.
IllegalComponent,
}
impl fmt::Display for RelativeToError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self.kind {
RelativeToErrorKind::NonUtf8 => "path contains non-utf8 component".fmt(fmt),
RelativeToErrorKind::PrefixMismatch => {
"paths contain different absolute prefixes".fmt(fmt)
}
RelativeToErrorKind::AmbiguousTraversal => {
"path traversal cannot be determined".fmt(fmt)
}
RelativeToErrorKind::IllegalComponent => "path contains illegal components".fmt(fmt),
}
}
}
impl error::Error for RelativeToError {}
impl From<RelativeToErrorKind> for RelativeToError {
#[inline]
fn from(kind: RelativeToErrorKind) -> Self {
Self { kind }
}
}
/// Extension methods for [`Path`] and [`PathBuf`] to for building and
/// interacting with [`RelativePath`].
///
/// [`RelativePath`]: crate::RelativePath
pub trait PathExt: sealed::Sealed {
/// Build a relative path from the provided directory to `self`.
///
/// Producing a relative path like this is a logical operation and does not
/// guarantee that the constructed path corresponds to what the filesystem
/// would do. On Linux for example symbolic links could mean that the
/// logical path doesn't correspond to the filesystem path.
///
/// # Examples
///
/// ```
/// use std::path::Path;
/// use relative_path::{RelativePath, PathExt};
///
/// let baz = Path::new("/foo/bar/baz");
/// let bar = Path::new("/foo/bar");
/// let qux = Path::new("/foo/bar/qux");
///
/// assert_eq!(bar.relative_to(baz)?, RelativePath::new("../"));
/// assert_eq!(baz.relative_to(bar)?, RelativePath::new("baz"));
/// assert_eq!(qux.relative_to(baz)?, RelativePath::new("../qux"));
/// assert_eq!(baz.relative_to(qux)?, RelativePath::new("../baz"));
/// assert_eq!(bar.relative_to(qux)?, RelativePath::new("../"));
/// # Ok::<_, relative_path::RelativeToError>(())
/// ```
///
/// # Errors
///
/// Errors in case the provided path contains components which cannot be
/// converted into a relative path as needed, such as non-utf8 data.
fn relative_to<P>(&self, root: P) -> Result<RelativePathBuf, RelativeToError>
where
P: AsRef<Path>;
}
impl PathExt for Path {
fn relative_to<P>(&self, root: P) -> Result<RelativePathBuf, RelativeToError>
where
P: AsRef<Path>,
{
use std::path::Component::{CurDir, Normal, ParentDir, Prefix, RootDir};
// Helper function to convert from a std::path::Component to a
// relative_path::Component.
fn std_to_c(c: std::path::Component<'_>) -> Result<Component<'_>, RelativeToError> {
Ok(match c {
CurDir => Component::CurDir,
ParentDir => Component::ParentDir,
Normal(n) => Component::Normal(n.to_str().ok_or(RelativeToErrorKind::NonUtf8)?),
_ => return Err(RelativeToErrorKind::IllegalComponent.into()),
})
}
let root = root.as_ref();
let mut a_it = self.components();
let mut b_it = root.components();
// Ensure that the two paths are both either relative, or have the same
// prefix. Strips any common prefix the two paths do have. Prefixes are
// platform dependent, but different prefixes would for example indicate
// paths for different drives on Windows.
let (a_head, b_head) = loop {
match (a_it.next(), b_it.next()) {
(Some(RootDir), Some(RootDir)) => (),
(Some(Prefix(a)), Some(Prefix(b))) if a == b => (),
(Some(Prefix(_) | RootDir), _) | (_, Some(Prefix(_) | RootDir)) => {
return Err(RelativeToErrorKind::PrefixMismatch.into());
}
(None, None) => break (None, None),
(a, b) if a != b => break (a, b),
_ => (),
}
};
let mut a_it = a_head.into_iter().chain(a_it);
let mut b_it = b_head.into_iter().chain(b_it);
let mut buf = RelativePathBuf::new();
loop {
let a = if let Some(a) = a_it.next() {
a
} else {
for _ in b_it {
buf.push(Component::ParentDir);
}
break;
};
match b_it.next() {
Some(CurDir) => buf.push(std_to_c(a)?),
Some(ParentDir) => {
return Err(RelativeToErrorKind::AmbiguousTraversal.into());
}
root => {
if root.is_some() {
buf.push(Component::ParentDir);
}
for comp in b_it {
match comp {
ParentDir => {
if !buf.pop() {
return Err(RelativeToErrorKind::AmbiguousTraversal.into());
}
}
CurDir => (),
_ => buf.push(Component::ParentDir),
}
}
buf.push(std_to_c(a)?);
for c in a_it {
buf.push(std_to_c(c)?);
}
break;
}
}
}
Ok(buf)
}
}
impl PathExt for PathBuf {
#[inline]
fn relative_to<P>(&self, root: P) -> Result<RelativePathBuf, RelativeToError>
where
P: AsRef<Path>,
{
self.as_path().relative_to(root)
}
}
#[cfg(test)]
mod tests {
use std::path::Path;
use super::{PathExt, RelativeToErrorKind};
use crate::{RelativePathBuf, RelativeToError};
macro_rules! assert_relative_to {
($path:expr, $base:expr, Ok($expected:expr) $(,)?) => {
assert_eq!(
Path::new($path).relative_to($base),
Ok(RelativePathBuf::from($expected))
);
};
($path:expr, $base:expr, Err($expected:ident) $(,)?) => {
assert_eq!(
Path::new($path).relative_to($base),
Err(RelativeToError::from(RelativeToErrorKind::$expected))
);
};
}
#[cfg(windows)]
macro_rules! abs {
($path:expr) => {
Path::new(concat!("C:\\", $path))
};
}
#[cfg(not(windows))]
macro_rules! abs {
($path:expr) => {
Path::new(concat!("/", $path))
};
}
#[test]
#[cfg(windows)]
fn test_different_prefixes() {
assert_relative_to!("C:\\repo", "D:\\repo", Err(PrefixMismatch),);
assert_relative_to!("C:\\repo", "C:\\repo", Ok(""));
assert_relative_to!(
"\\\\server\\share\\repo",
"\\\\server2\\share\\repo",
Err(PrefixMismatch),
);
}
#[test]
fn test_absolute() {
assert_relative_to!(abs!("foo"), abs!("bar"), Ok("../foo"));
assert_relative_to!("foo", "bar", Ok("../foo"));
assert_relative_to!(abs!("foo"), "bar", Err(PrefixMismatch));
assert_relative_to!("foo", abs!("bar"), Err(PrefixMismatch));
}
#[test]
fn test_identity() {
assert_relative_to!(".", ".", Ok(""));
assert_relative_to!("../foo", "../foo", Ok(""));
assert_relative_to!("./foo", "./foo", Ok(""));
assert_relative_to!("/foo", "/foo", Ok(""));
assert_relative_to!("foo", "foo", Ok(""));
assert_relative_to!("../foo/bar/baz", "../foo/bar/baz", Ok(""));
assert_relative_to!("foo/bar/baz", "foo/bar/baz", Ok(""));
}
#[test]
fn test_subset() {
assert_relative_to!("foo", "fo", Ok("../foo"));
assert_relative_to!("fo", "foo", Ok("../fo"));
}
#[test]
fn test_empty() {
assert_relative_to!("", "", Ok(""));
assert_relative_to!("foo", "", Ok("foo"));
assert_relative_to!("", "foo", Ok(".."));
}
#[test]
fn test_relative() {
assert_relative_to!("../foo", "../bar", Ok("../foo"));
assert_relative_to!("../foo", "../foo/bar/baz", Ok("../.."));
assert_relative_to!("../foo/bar/baz", "../foo", Ok("bar/baz"));
assert_relative_to!("foo/bar/baz", "foo", Ok("bar/baz"));
assert_relative_to!("foo/bar/baz", "foo/bar", Ok("baz"));
assert_relative_to!("foo/bar/baz", "foo/bar/baz", Ok(""));
assert_relative_to!("foo/bar/baz", "foo/bar/baz/", Ok(""));
assert_relative_to!("foo/bar/baz/", "foo", Ok("bar/baz"));
assert_relative_to!("foo/bar/baz/", "foo/bar", Ok("baz"));
assert_relative_to!("foo/bar/baz/", "foo/bar/baz", Ok(""));
assert_relative_to!("foo/bar/baz/", "foo/bar/baz/", Ok(""));
assert_relative_to!("foo/bar/baz", "foo/", Ok("bar/baz"));
assert_relative_to!("foo/bar/baz", "foo/bar/", Ok("baz"));
assert_relative_to!("foo/bar/baz", "foo/bar/baz", Ok(""));
}
#[test]
fn test_current_directory() {
assert_relative_to!(".", "foo", Ok("../."));
assert_relative_to!("foo", ".", Ok("foo"));
assert_relative_to!("/foo", "/.", Ok("foo"));
}
#[test]
fn assert_does_not_skip_parents() {
assert_relative_to!("some/path", "some/foo/baz/path", Ok("../../../path"));
assert_relative_to!("some/path", "some/foo/bar/../baz/path", Ok("../../../path"));
}
#[test]
fn test_ambiguous_paths() {
// Parent directory name is unknown, so trying to make current directory
// relative to it is impossible.
assert_relative_to!(".", "../..", Err(AmbiguousTraversal));
assert_relative_to!(".", "a/../..", Err(AmbiguousTraversal));
// Common prefixes are ok.
assert_relative_to!("../a/..", "../a/../b", Ok(".."));
assert_relative_to!("../a/../b", "../a/..", Ok("b"));
}
}
+790
View File
@@ -0,0 +1,790 @@
#![allow(clippy::too_many_lines)]
use super::*;
use std::path::Path;
use std::rc::Rc;
use std::sync::Arc;
macro_rules! t(
($path:expr, iter: $iter:expr) => (
{
let path = RelativePath::new($path);
// Forward iteration
let comps = path.iter().map(str::to_string).collect::<Vec<String>>();
let exp: &[&str] = &$iter;
let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>();
assert!(comps == exps, "iter: Expected {:?}, found {:?}",
exps, comps);
// Reverse iteration
let comps = RelativePath::new($path).iter().rev().map(str::to_string)
.collect::<Vec<String>>();
let exps = exps.into_iter().rev().collect::<Vec<String>>();
assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}",
exps, comps);
}
);
($path:expr, parent: $parent:expr, file_name: $file:expr) => (
{
let path = RelativePath::new($path);
let parent = path.parent().map(|p| p.as_str());
let exp_parent: Option<&str> = $parent;
assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}",
exp_parent, parent);
let file = path.file_name();
let exp_file: Option<&str> = $file;
assert!(file == exp_file, "file_name: Expected {:?}, found {:?}",
exp_file, file);
}
);
($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => (
{
let path = RelativePath::new($path);
let stem = path.file_stem();
let exp_stem: Option<&str> = $file_stem;
assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}",
exp_stem, stem);
let ext = path.extension();
let exp_ext: Option<&str> = $extension;
assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}",
exp_ext, ext);
}
);
($path:expr, iter: $iter:expr,
parent: $parent:expr, file_name: $file:expr,
file_stem: $file_stem:expr, extension: $extension:expr) => (
{
t!($path, iter: $iter);
t!($path, parent: $parent, file_name: $file);
t!($path, file_stem: $file_stem, extension: $extension);
}
);
);
fn assert_components(components: &[&str], path: &RelativePath) {
let components = components
.iter()
.copied()
.map(Component::Normal)
.collect::<Vec<_>>();
let result: Vec<_> = path.components().collect();
assert_eq!(&components[..], &result[..]);
}
fn rp(input: &str) -> &RelativePath {
RelativePath::new(input)
}
#[test]
#[allow(clippy::cognitive_complexity)]
pub fn test_decompositions() {
t!("",
iter: [],
parent: None,
file_name: None,
file_stem: None,
extension: None
);
t!("foo",
iter: ["foo"],
parent: Some(""),
file_name: Some("foo"),
file_stem: Some("foo"),
extension: None
);
t!("/",
iter: [],
parent: Some(""),
file_name: None,
file_stem: None,
extension: None
);
t!("/foo",
iter: ["foo"],
parent: Some(""),
file_name: Some("foo"),
file_stem: Some("foo"),
extension: None
);
t!("foo/",
iter: ["foo"],
parent: Some(""),
file_name: Some("foo"),
file_stem: Some("foo"),
extension: None
);
t!("/foo/",
iter: ["foo"],
parent: Some(""),
file_name: Some("foo"),
file_stem: Some("foo"),
extension: None
);
t!("foo/bar",
iter: ["foo", "bar"],
parent: Some("foo"),
file_name: Some("bar"),
file_stem: Some("bar"),
extension: None
);
t!("/foo/bar",
iter: ["foo", "bar"],
parent: Some("/foo"),
file_name: Some("bar"),
file_stem: Some("bar"),
extension: None
);
t!("///foo///",
iter: ["foo"],
parent: Some(""),
file_name: Some("foo"),
file_stem: Some("foo"),
extension: None
);
t!("///foo///bar",
iter: ["foo", "bar"],
parent: Some("///foo"),
file_name: Some("bar"),
file_stem: Some("bar"),
extension: None
);
t!("./.",
iter: [".", "."],
parent: Some(""),
file_name: None,
file_stem: None,
extension: None
);
t!("/..",
iter: [".."],
parent: Some(""),
file_name: None,
file_stem: None,
extension: None
);
t!("../",
iter: [".."],
parent: Some(""),
file_name: None,
file_stem: None,
extension: None
);
t!("foo/.",
iter: ["foo", "."],
parent: Some(""),
file_name: Some("foo"),
file_stem: Some("foo"),
extension: None
);
t!("foo/..",
iter: ["foo", ".."],
parent: Some("foo"),
file_name: None,
file_stem: None,
extension: None
);
t!("foo/./",
iter: ["foo", "."],
parent: Some(""),
file_name: Some("foo"),
file_stem: Some("foo"),
extension: None
);
t!("foo/./bar",
iter: ["foo", ".", "bar"],
parent: Some("foo/."),
file_name: Some("bar"),
file_stem: Some("bar"),
extension: None
);
t!("foo/../",
iter: ["foo", ".."],
parent: Some("foo"),
file_name: None,
file_stem: None,
extension: None
);
t!("foo/../bar",
iter: ["foo", "..", "bar"],
parent: Some("foo/.."),
file_name: Some("bar"),
file_stem: Some("bar"),
extension: None
);
t!("./a",
iter: [".", "a"],
parent: Some("."),
file_name: Some("a"),
file_stem: Some("a"),
extension: None
);
t!(".",
iter: ["."],
parent: Some(""),
file_name: None,
file_stem: None,
extension: None
);
t!("./",
iter: ["."],
parent: Some(""),
file_name: None,
file_stem: None,
extension: None
);
t!("a/b",
iter: ["a", "b"],
parent: Some("a"),
file_name: Some("b"),
file_stem: Some("b"),
extension: None
);
t!("a//b",
iter: ["a", "b"],
parent: Some("a"),
file_name: Some("b"),
file_stem: Some("b"),
extension: None
);
t!("a/./b",
iter: ["a", ".", "b"],
parent: Some("a/."),
file_name: Some("b"),
file_stem: Some("b"),
extension: None
);
t!("a/b/c",
iter: ["a", "b", "c"],
parent: Some("a/b"),
file_name: Some("c"),
file_stem: Some("c"),
extension: None
);
t!(".foo",
iter: [".foo"],
parent: Some(""),
file_name: Some(".foo"),
file_stem: Some(".foo"),
extension: None
);
}
#[test]
pub fn test_stem_ext() {
t!("foo",
file_stem: Some("foo"),
extension: None
);
t!("foo.",
file_stem: Some("foo"),
extension: Some("")
);
t!(".foo",
file_stem: Some(".foo"),
extension: None
);
t!("foo.txt",
file_stem: Some("foo"),
extension: Some("txt")
);
t!("foo.bar.txt",
file_stem: Some("foo.bar"),
extension: Some("txt")
);
t!("foo.bar.",
file_stem: Some("foo.bar"),
extension: Some("")
);
t!(".", file_stem: None, extension: None);
t!("..", file_stem: None, extension: None);
t!("", file_stem: None, extension: None);
}
#[test]
pub fn test_set_file_name() {
macro_rules! tfn(
($path:expr, $file:expr, $expected:expr) => ( {
let mut p = RelativePathBuf::from($path);
p.set_file_name($file);
assert!(p.as_str() == $expected,
"setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
$path, $file, $expected,
p.as_str());
});
);
tfn!("foo", "foo", "foo");
tfn!("foo", "bar", "bar");
tfn!("foo", "", "");
tfn!("", "foo", "foo");
tfn!(".", "foo", "./foo");
tfn!("foo/", "bar", "bar");
tfn!("foo/.", "bar", "bar");
tfn!("..", "foo", "../foo");
tfn!("foo/..", "bar", "foo/../bar");
tfn!("/", "foo", "/foo");
}
#[test]
pub fn test_set_extension() {
macro_rules! tse(
($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
let mut p = RelativePathBuf::from($path);
let output = p.set_extension($ext);
assert!(p.as_str() == $expected && output == $output,
"setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
$path, $ext, $expected, $output,
p.as_str(), output);
});
);
tse!("foo", "txt", "foo.txt", true);
tse!("foo.bar", "txt", "foo.txt", true);
tse!("foo.bar.baz", "txt", "foo.bar.txt", true);
tse!(".test", "txt", ".test.txt", true);
tse!("foo.txt", "", "foo", true);
tse!("foo", "", "foo", true);
tse!("", "foo", "", false);
tse!(".", "foo", ".", false);
tse!("foo/", "bar", "foo.bar", true);
tse!("foo/.", "bar", "foo.bar", true);
tse!("..", "foo", "..", false);
tse!("foo/..", "bar", "foo/..", false);
tse!("/", "foo", "/", false);
}
#[test]
fn test_eq_recievers() {
use std::borrow::Cow;
let borrowed: &RelativePath = RelativePath::new("foo/bar");
let mut owned: RelativePathBuf = RelativePathBuf::new();
owned.push("foo");
owned.push("bar");
let borrowed_cow: Cow<RelativePath> = borrowed.into();
let owned_cow: Cow<RelativePath> = owned.clone().into();
macro_rules! t {
($($current:expr),+) => {
$(
assert_eq!($current, borrowed);
assert_eq!($current, owned);
assert_eq!($current, borrowed_cow);
assert_eq!($current, owned_cow);
)+
}
}
t!(borrowed, owned, borrowed_cow, owned_cow);
}
#[test]
#[allow(clippy::cognitive_complexity)]
pub fn test_compare() {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
fn hash<T: Hash>(t: T) -> u64 {
let mut s = DefaultHasher::new();
t.hash(&mut s);
s.finish()
}
macro_rules! tc(
($path1:expr, $path2:expr, eq: $eq:expr,
starts_with: $starts_with:expr, ends_with: $ends_with:expr,
relative_from: $relative_from:expr) => ({
let path1 = RelativePath::new($path1);
let path2 = RelativePath::new($path2);
let eq = path1 == path2;
assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}",
$path1, $path2, $eq, eq);
assert!($eq == (hash(path1) == hash(path2)),
"{:?} == {:?}, expected {:?}, got {} and {}",
$path1, $path2, $eq, hash(path1), hash(path2));
let starts_with = path1.starts_with(path2);
assert!(starts_with == $starts_with,
"{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2,
$starts_with, starts_with);
let ends_with = path1.ends_with(path2);
assert!(ends_with == $ends_with,
"{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2,
$ends_with, ends_with);
let relative_from = path1.strip_prefix(path2)
.map(|p| p.as_str())
.ok();
let exp: Option<&str> = $relative_from;
assert!(relative_from == exp,
"{:?}.strip_prefix({:?}), expected {:?}, got {:?}",
$path1, $path2, exp, relative_from);
});
);
tc!("", "",
eq: true,
starts_with: true,
ends_with: true,
relative_from: Some("")
);
tc!("foo", "",
eq: false,
starts_with: true,
ends_with: true,
relative_from: Some("foo")
);
tc!("", "foo",
eq: false,
starts_with: false,
ends_with: false,
relative_from: None
);
tc!("foo", "foo",
eq: true,
starts_with: true,
ends_with: true,
relative_from: Some("")
);
tc!("foo/", "foo",
eq: true,
starts_with: true,
ends_with: true,
relative_from: Some("")
);
tc!("foo/bar", "foo",
eq: false,
starts_with: true,
ends_with: false,
relative_from: Some("bar")
);
tc!("foo/bar/baz", "foo/bar",
eq: false,
starts_with: true,
ends_with: false,
relative_from: Some("baz")
);
tc!("foo/bar", "foo/bar/baz",
eq: false,
starts_with: false,
ends_with: false,
relative_from: None
);
}
#[test]
fn test_join() {
assert_components(&["foo", "bar", "baz"], &rp("foo/bar").join("baz///"));
assert_components(
&["hello", "world", "foo", "bar", "baz"],
&rp("hello/world").join("///foo/bar/baz"),
);
assert_components(&["foo", "bar", "baz"], &rp("").join("foo/bar/baz"));
}
#[test]
fn test_components_iterator() {
use self::Component::*;
assert_eq!(
vec![Normal("hello"), Normal("world")],
rp("/hello///world//").components().collect::<Vec<_>>()
);
}
#[test]
fn test_to_path_buf() {
let path = rp("/hello///world//");
let path_buf = path.to_path(".");
let expected = Path::new(".").join("hello").join("world");
assert_eq!(expected, path_buf);
}
#[test]
fn test_eq() {
assert_eq!(rp("//foo///bar"), rp("/foo/bar"));
assert_eq!(rp("foo///bar"), rp("foo/bar"));
assert_eq!(rp("foo"), rp("foo"));
assert_eq!(rp("foo"), rp("foo").to_relative_path_buf());
}
#[test]
fn test_next_back() {
use self::Component::*;
let mut it = rp("baz/bar///foo").components();
assert_eq!(Some(Normal("foo")), it.next_back());
assert_eq!(Some(Normal("bar")), it.next_back());
assert_eq!(Some(Normal("baz")), it.next_back());
assert_eq!(None, it.next_back());
}
#[test]
fn test_parent() {
let path = rp("baz/./bar/foo//./.");
assert_eq!(Some(rp("baz/./bar")), path.parent());
assert_eq!(
Some(rp("baz/.")),
path.parent().and_then(RelativePath::parent)
);
assert_eq!(
Some(rp("")),
path.parent()
.and_then(RelativePath::parent)
.and_then(RelativePath::parent)
);
assert_eq!(
None,
path.parent()
.and_then(RelativePath::parent)
.and_then(RelativePath::parent)
.and_then(RelativePath::parent)
);
}
#[test]
fn test_relative_path_buf() {
assert_eq!(
rp("hello/world/."),
rp("/hello///world//").to_owned().join(".")
);
}
#[test]
fn test_normalize() {
assert_eq!(rp("c/d"), rp("a/.././b/../c/d").normalize());
}
#[test]
fn test_relative_to() {
assert_eq!(
rp("foo/foo/bar"),
rp("foo/bar").join_normalized("../foo/bar")
);
assert_eq!(
rp("../c/e"),
rp("x/y").join_normalized("../../a/b/../../../c/d/../e")
);
}
#[test]
fn test_from() {
assert_eq!(
rp("foo/bar").to_owned(),
RelativePathBuf::from(String::from("foo/bar")),
);
assert_eq!(
RelativePathBuf::from(rp("foo/bar")),
RelativePathBuf::from("foo/bar"),
);
assert_eq!(rp("foo/bar").to_owned(), RelativePathBuf::from("foo/bar"),);
assert_eq!(&*Box::<RelativePath>::from(rp("foo/bar")), rp("foo/bar"));
assert_eq!(
&*Box::<RelativePath>::from(RelativePathBuf::from("foo/bar")),
rp("foo/bar")
);
assert_eq!(&*Arc::<RelativePath>::from(rp("foo/bar")), rp("foo/bar"));
assert_eq!(
&*Arc::<RelativePath>::from(RelativePathBuf::from("foo/bar")),
rp("foo/bar")
);
assert_eq!(&*Rc::<RelativePath>::from(rp("foo/bar")), rp("foo/bar"));
assert_eq!(
&*Rc::<RelativePath>::from(RelativePathBuf::from("foo/bar")),
rp("foo/bar")
);
}
#[test]
fn test_relative_path_asref_str() {
assert_eq!(
<RelativePath as AsRef<str>>::as_ref(rp("foo/bar")),
"foo/bar"
);
}
#[test]
fn test_default() {
assert_eq!(RelativePathBuf::new(), RelativePathBuf::default(),);
}
#[test]
pub fn test_push() {
macro_rules! tp(
($path:expr, $push:expr, $expected:expr) => ( {
let mut actual = RelativePathBuf::from($path);
actual.push($push);
assert!(actual.as_str() == $expected,
"pushing {:?} onto {:?}: Expected {:?}, got {:?}",
$push, $path, $expected, actual.as_str());
});
);
tp!("", "foo", "foo");
tp!("foo", "bar", "foo/bar");
tp!("foo/", "bar", "foo/bar");
tp!("foo//", "bar", "foo//bar");
tp!("foo/.", "bar", "foo/./bar");
tp!("foo./.", "bar", "foo././bar");
tp!("foo", "", "foo/");
tp!("foo", ".", "foo/.");
tp!("foo", "..", "foo/..");
}
#[test]
pub fn test_pop() {
macro_rules! tp(
($path:expr, $expected:expr, $output:expr) => ( {
let mut actual = RelativePathBuf::from($path);
let output = actual.pop();
assert!(actual.as_str() == $expected && output == $output,
"popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
$path, $expected, $output,
actual.as_str(), output);
});
);
tp!("", "", false);
tp!("/", "", true);
tp!("foo", "", true);
tp!(".", "", true);
tp!("/foo", "", true);
tp!("/foo/bar", "/foo", true);
tp!("/foo/bar/.", "/foo", true);
tp!("foo/bar", "foo", true);
tp!("foo/.", "", true);
tp!("foo//bar", "foo", true);
}
#[test]
pub fn test_display() {
// NB: display delegated to the underlying string.
assert_eq!(RelativePathBuf::from("foo/bar").to_string(), "foo/bar");
assert_eq!(RelativePath::new("foo/bar").to_string(), "foo/bar");
assert_eq!(format!("{}", RelativePathBuf::from("foo/bar")), "foo/bar");
assert_eq!(format!("{}", RelativePath::new("foo/bar")), "foo/bar");
}
#[cfg(unix)]
#[test]
pub fn test_unix_from_path() {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
assert_eq!(
Err(FromPathErrorKind::NonRelative.into()),
RelativePath::from_path("/foo/bar")
);
// Continuation byte without continuation.
let non_utf8 = OsStr::from_bytes(&[0x80u8]);
assert_eq!(
Err(FromPathErrorKind::NonUtf8.into()),
RelativePath::from_path(non_utf8)
);
}
#[cfg(windows)]
#[test]
pub fn test_windows_from_path() {
assert_eq!(
Err(FromPathErrorKind::NonRelative.into()),
RelativePath::from_path("c:\\foo\\bar")
);
assert_eq!(
Err(FromPathErrorKind::BadSeparator.into()),
RelativePath::from_path("foo\\bar")
);
}
#[cfg(unix)]
#[test]
pub fn test_unix_owned_from_path() {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
assert_eq!(
Err(FromPathErrorKind::NonRelative.into()),
RelativePathBuf::from_path(Path::new("/foo/bar"))
);
// Continuation byte without continuation.
let non_utf8 = OsStr::from_bytes(&[0x80u8]);
assert_eq!(
Err(FromPathErrorKind::NonUtf8.into()),
RelativePathBuf::from_path(Path::new(non_utf8))
);
}
#[cfg(windows)]
#[test]
pub fn test_windows_owned_from_path() {
assert_eq!(
Err(FromPathErrorKind::NonRelative.into()),
RelativePathBuf::from_path(Path::new("c:\\foo\\bar"))
);
}