Skip to content

Add gix_path::relative_path::RelativePath #1921

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Apr 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

27 changes: 20 additions & 7 deletions gix-fs/src/stack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,30 +50,43 @@ fn component_to_os_str<'a>(

impl ToNormalPathComponents for &BStr {
fn to_normal_path_components(&self) -> impl Iterator<Item = Result<&OsStr, to_normal_path_components::Error>> {
self.split(|b| *b == b'/').filter_map(bytes_component_to_os_str)
self.split(|b| *b == b'/')
.filter_map(|c| bytes_component_to_os_str(c, self))
}
}

impl ToNormalPathComponents for &str {
fn to_normal_path_components(&self) -> impl Iterator<Item = Result<&OsStr, to_normal_path_components::Error>> {
self.split('/').filter_map(|c| bytes_component_to_os_str(c.as_bytes()))
self.split('/')
.filter_map(|c| bytes_component_to_os_str(c.as_bytes(), (*self).into()))
}
}

impl ToNormalPathComponents for &BString {
fn to_normal_path_components(&self) -> impl Iterator<Item = Result<&OsStr, to_normal_path_components::Error>> {
self.split(|b| *b == b'/').filter_map(bytes_component_to_os_str)
self.split(|b| *b == b'/')
.filter_map(|c| bytes_component_to_os_str(c, self.as_bstr()))
}
}

fn bytes_component_to_os_str(component: &[u8]) -> Option<Result<&OsStr, to_normal_path_components::Error>> {
fn bytes_component_to_os_str<'a>(
component: &'a [u8],
path: &BStr,
) -> Option<Result<&'a OsStr, to_normal_path_components::Error>> {
if component.is_empty() {
return None;
}
gix_path::try_from_byte_slice(component.as_bstr())
let component = match gix_path::try_from_byte_slice(component.as_bstr())
.map_err(|_| to_normal_path_components::Error::IllegalUtf8)
.map(Path::as_os_str)
.into()
{
Ok(c) => c,
Err(err) => return Some(Err(err)),
};
let component = component.components().next()?;
Some(component_to_os_str(
component,
gix_path::try_from_byte_slice(path.as_ref()).ok()?,
))
}

/// Access
Expand Down
13 changes: 13 additions & 0 deletions gix-fs/tests/fs/stack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,19 @@ fn absolute_paths_are_invalid() -> crate::Result {
r#"Input path "/" contains relative or absolute components"#,
"a leading slash is always considered absolute"
);
s.make_relative_path_current("/", &mut r)?;
assert_eq!(
s.current(),
s.root(),
"as string this is a no-op as it's just split by /"
);

let err = s.make_relative_path_current("../breakout", &mut r).unwrap_err();
assert_eq!(
err.to_string(),
r#"Input path "../breakout" contains relative or absolute components"#,
"otherwise breakout attempts are detected"
);
s.make_relative_path_current(p("a/"), &mut r)?;
assert_eq!(
s.current(),
Expand Down
2 changes: 1 addition & 1 deletion gix-negotiate/tests/baseline/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ fn run() -> crate::Result {
// }
for tip in lookup_names(&["HEAD"]).into_iter().chain(
refs.iter()?
.prefixed(b"refs/heads")?
.prefixed(b"refs/heads".try_into().unwrap())?
.filter_map(Result::ok)
.map(|r| r.target.into_id()),
) {
Expand Down
1 change: 1 addition & 0 deletions gix-path/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ doctest = false

[dependencies]
gix-trace = { version = "^0.1.12", path = "../gix-trace" }
gix-validate = { version = "^0.9.4", path = "../gix-validate" }
bstr = { version = "1.12.0", default-features = false, features = ["std"] }
thiserror = "2.0.0"
once_cell = "1.21.3"
Expand Down
6 changes: 5 additions & 1 deletion gix-path/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
//! ever get into a code-path which does panic though.
//! </details>
#![deny(missing_docs, rust_2018_idioms)]
#![cfg_attr(not(test), forbid(unsafe_code))]
#![cfg_attr(not(test), deny(unsafe_code))]

/// A dummy type to represent path specs and help finding all spots that take path specs once it is implemented.
mod convert;
Expand All @@ -62,3 +62,7 @@ pub use realpath::function::{realpath, realpath_opts};

/// Information about the environment in terms of locations of resources.
pub mod env;

///
pub mod relative_path;
pub use relative_path::types::RelativePath;
113 changes: 113 additions & 0 deletions gix-path/src/relative_path.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
use bstr::BStr;
use bstr::BString;
use bstr::ByteSlice;
use gix_validate::path::component::Options;
use std::path::Path;

use crate::os_str_into_bstr;
use crate::try_from_bstr;
use crate::try_from_byte_slice;

pub(super) mod types {
use bstr::{BStr, ByteSlice};
/// A wrapper for `BStr`. It is used to enforce the following constraints:
///
/// - The path separator always is `/`, independent of the platform.
/// - Only normal components are allowed.
/// - It is always represented as a bunch of bytes.
#[derive()]
pub struct RelativePath {
inner: BStr,
}

impl AsRef<[u8]> for RelativePath {
#[inline]
fn as_ref(&self) -> &[u8] {
self.inner.as_bytes()
}
}
}
use types::RelativePath;

impl RelativePath {
fn new_unchecked(value: &BStr) -> Result<&RelativePath, Error> {
// SAFETY: `RelativePath` is transparent and equivalent to a `&BStr` if provided as reference.
#[allow(unsafe_code)]
unsafe {
std::mem::transmute(value)
}
}
}

/// The error used in [`RelativePath`].
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
pub enum Error {
#[error("A RelativePath is not allowed to be absolute")]
IsAbsolute,
#[error(transparent)]
ContainsInvalidComponent(#[from] gix_validate::path::component::Error),
#[error(transparent)]
IllegalUtf8(#[from] crate::Utf8Error),
}

fn relative_path_from_value_and_path<'a>(path_bstr: &'a BStr, path: &Path) -> Result<&'a RelativePath, Error> {
if path.is_absolute() {
return Err(Error::IsAbsolute);
}

let options = Options::default();

for component in path.components() {
let component = os_str_into_bstr(component.as_os_str())?;
gix_validate::path::component(component, None, options)?;
}

RelativePath::new_unchecked(BStr::new(path_bstr.as_bytes()))
}

impl<'a> TryFrom<&'a str> for &'a RelativePath {
type Error = Error;

fn try_from(value: &'a str) -> Result<Self, Self::Error> {
relative_path_from_value_and_path(value.into(), Path::new(value))
}
}

impl<'a> TryFrom<&'a BStr> for &'a RelativePath {
type Error = Error;

fn try_from(value: &'a BStr) -> Result<Self, Self::Error> {
let path = try_from_bstr(value)?;
relative_path_from_value_and_path(value, &path)
}
}

impl<'a> TryFrom<&'a [u8]> for &'a RelativePath {
type Error = Error;

#[inline]
fn try_from(value: &'a [u8]) -> Result<Self, Self::Error> {
let path = try_from_byte_slice(value)?;
relative_path_from_value_and_path(value.as_bstr(), path)
}
}

impl<'a, const N: usize> TryFrom<&'a [u8; N]> for &'a RelativePath {
type Error = Error;

#[inline]
fn try_from(value: &'a [u8; N]) -> Result<Self, Self::Error> {
let path = try_from_byte_slice(value.as_bstr())?;
relative_path_from_value_and_path(value.as_bstr(), path)
}
}

impl<'a> TryFrom<&'a BString> for &'a RelativePath {
type Error = Error;

fn try_from(value: &'a BString) -> Result<Self, Self::Error> {
let path = try_from_bstr(value.as_bstr())?;
relative_path_from_value_and_path(value.as_bstr(), &path)
}
}
1 change: 1 addition & 0 deletions gix-path/tests/path/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ pub type Result<T = ()> = std::result::Result<T, Box<dyn std::error::Error>>;

mod convert;
mod realpath;
mod relative_path;
mod home_dir {
#[test]
fn returns_existing_directory() {
Expand Down
160 changes: 160 additions & 0 deletions gix-path/tests/path/relative_path.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
use bstr::{BStr, BString};
use gix_path::relative_path::Error;
use gix_path::RelativePath;

#[cfg(not(windows))]
#[test]
fn absolute_paths_return_err() {
let path_str: &str = "/refs/heads";
let path_bstr: &BStr = path_str.into();
let path_u8a: &[u8; 11] = b"/refs/heads";
let path_u8: &[u8] = &b"/refs/heads"[..];
let path_bstring: BString = "/refs/heads".into();

assert!(matches!(
TryInto::<&RelativePath>::try_into(path_str),
Err(Error::IsAbsolute)
));
assert!(matches!(
TryInto::<&RelativePath>::try_into(path_bstr),
Err(Error::IsAbsolute)
));
assert!(matches!(
TryInto::<&RelativePath>::try_into(path_u8),
Err(Error::IsAbsolute)
));
assert!(matches!(
TryInto::<&RelativePath>::try_into(path_u8a),
Err(Error::IsAbsolute)
));
assert!(matches!(
TryInto::<&RelativePath>::try_into(&path_bstring),
Err(Error::IsAbsolute)
));
}

#[cfg(windows)]
#[test]
fn absolute_paths_with_backslashes_return_err() {
let path_str: &str = r"c:\refs\heads";
let path_bstr: &BStr = path_str.into();
let path_u8: &[u8] = &b"c:\\refs\\heads"[..];
let path_bstring: BString = r"c:\refs\heads".into();

assert!(matches!(
TryInto::<&RelativePath>::try_into(path_str),
Err(Error::IsAbsolute)
));
assert!(matches!(
TryInto::<&RelativePath>::try_into(path_bstr),
Err(Error::IsAbsolute)
));
assert!(matches!(
TryInto::<&RelativePath>::try_into(path_u8),
Err(Error::IsAbsolute)
));
assert!(matches!(
TryInto::<&RelativePath>::try_into(&path_bstring),
Err(Error::IsAbsolute)
));
}

#[test]
fn dots_in_paths_return_err() {
let path_str: &str = "./heads";
let path_bstr: &BStr = path_str.into();
let path_u8: &[u8] = &b"./heads"[..];
let path_bstring: BString = "./heads".into();

assert!(matches!(
TryInto::<&RelativePath>::try_into(path_str),
Err(Error::ContainsInvalidComponent(_))
));
assert!(matches!(
TryInto::<&RelativePath>::try_into(path_bstr),
Err(Error::ContainsInvalidComponent(_))
));
assert!(matches!(
TryInto::<&RelativePath>::try_into(path_u8),
Err(Error::ContainsInvalidComponent(_))
));
assert!(matches!(
TryInto::<&RelativePath>::try_into(&path_bstring),
Err(Error::ContainsInvalidComponent(_))
));
}

#[test]
fn dots_in_paths_with_backslashes_return_err() {
let path_str: &str = r".\heads";
let path_bstr: &BStr = path_str.into();
let path_u8: &[u8] = &b".\\heads"[..];
let path_bstring: BString = r".\heads".into();

assert!(matches!(
TryInto::<&RelativePath>::try_into(path_str),
Err(Error::ContainsInvalidComponent(_))
));
assert!(matches!(
TryInto::<&RelativePath>::try_into(path_bstr),
Err(Error::ContainsInvalidComponent(_))
));
assert!(matches!(
TryInto::<&RelativePath>::try_into(path_u8),
Err(Error::ContainsInvalidComponent(_))
));
assert!(matches!(
TryInto::<&RelativePath>::try_into(&path_bstring),
Err(Error::ContainsInvalidComponent(_))
));
}

#[test]
fn double_dots_in_paths_return_err() {
let path_str: &str = "../heads";
let path_bstr: &BStr = path_str.into();
let path_u8: &[u8] = &b"../heads"[..];
let path_bstring: BString = "../heads".into();

assert!(matches!(
TryInto::<&RelativePath>::try_into(path_str),
Err(Error::ContainsInvalidComponent(_))
));
assert!(matches!(
TryInto::<&RelativePath>::try_into(path_bstr),
Err(Error::ContainsInvalidComponent(_))
));
assert!(matches!(
TryInto::<&RelativePath>::try_into(path_u8),
Err(Error::ContainsInvalidComponent(_))
));
assert!(matches!(
TryInto::<&RelativePath>::try_into(&path_bstring),
Err(Error::ContainsInvalidComponent(_))
));
}

#[test]
fn double_dots_in_paths_with_backslashes_return_err() {
let path_str: &str = r"..\heads";
let path_bstr: &BStr = path_str.into();
let path_u8: &[u8] = &b"..\\heads"[..];
let path_bstring: BString = r"..\heads".into();

assert!(matches!(
TryInto::<&RelativePath>::try_into(path_str),
Err(Error::ContainsInvalidComponent(_))
));
assert!(matches!(
TryInto::<&RelativePath>::try_into(path_bstr),
Err(Error::ContainsInvalidComponent(_))
));
assert!(matches!(
TryInto::<&RelativePath>::try_into(path_u8),
Err(Error::ContainsInvalidComponent(_))
));
assert!(matches!(
TryInto::<&RelativePath>::try_into(&path_bstring),
Err(Error::ContainsInvalidComponent(_))
));
}
Loading
Loading