mirror of
https://github.com/openai/codex.git
synced 2026-11-20 22:40:37 +00:00
Add cross-platform PathUri lexical helpers
This commit is contained in:
@@ -0,0 +1,130 @@
|
||||
use super::PathConvention;
|
||||
use super::PathUri;
|
||||
use super::PathUriParseError;
|
||||
use super::decode_bad_path_uri;
|
||||
use super::decode_uri_path;
|
||||
use super::is_windows_drive_uri_segment;
|
||||
use super::is_windows_separator_byte;
|
||||
|
||||
impl PathUri {
|
||||
/// Parses absolute native path text without consulting the current host.
|
||||
///
|
||||
/// POSIX paths, rooted Windows drive paths, and UNC paths are recognized
|
||||
/// from their spelling. Relative paths, drive-relative paths, Windows
|
||||
/// root-relative paths, and device namespace paths are rejected. Call
|
||||
/// [`Self::parse`] instead when the input is already a `file:` URI.
|
||||
pub fn from_inferred_absolute_path(path: &str) -> Result<Self, PathUriParseError> {
|
||||
let convention = inferred_absolute_path_convention(path)
|
||||
.ok_or_else(|| PathUriParseError::ExpectedAbsoluteNativePath(path.to_string()))?;
|
||||
Self::from_absolute_native_path(path, convention)
|
||||
.ok_or_else(|| PathUriParseError::ExpectedAbsoluteNativePath(path.to_string()))
|
||||
}
|
||||
|
||||
/// Lexically resolves target-relative path text against this URI.
|
||||
///
|
||||
/// Unlike [`Self::join`], this rejects absolute, root-relative, UNC, and
|
||||
/// drive-relative input under either POSIX or Windows path grammar. Parent
|
||||
/// segments may normalize components within the relative input, but may
|
||||
/// not traverse above the receiver URI.
|
||||
pub fn join_relative(&self, path: &str) -> Result<Self, PathUriParseError> {
|
||||
if has_rooted_or_drive_prefix(path) {
|
||||
return Err(PathUriParseError::JoinPathMustBeRelative(path.to_string()));
|
||||
}
|
||||
if path.is_empty() {
|
||||
return Ok(self.clone());
|
||||
}
|
||||
if decode_bad_path_uri(&self.0).is_some() {
|
||||
return self.join(path);
|
||||
}
|
||||
|
||||
let convention =
|
||||
self.infer_path_convention()
|
||||
.ok_or_else(|| PathUriParseError::InvalidFileUriPath {
|
||||
path: self.to_string(),
|
||||
})?;
|
||||
let mut depth = 0usize;
|
||||
for component in convention.path_segments(path) {
|
||||
match component {
|
||||
"" | "." => {}
|
||||
".." if depth == 0 => {
|
||||
return Err(PathUriParseError::JoinPathEscapesBase(path.to_string()));
|
||||
}
|
||||
".." => depth -= 1,
|
||||
_ => depth += 1,
|
||||
}
|
||||
}
|
||||
|
||||
self.join(path)
|
||||
}
|
||||
|
||||
/// Returns this URI's normalized lexical path relative to `root`.
|
||||
///
|
||||
/// The result is available only when this URI is equal to or a descendant
|
||||
/// of `root` under the same inferred path convention and URI authority.
|
||||
/// The returned text uses `/` separators on every platform. Opaque fallback
|
||||
/// URIs do not support lexical containment.
|
||||
pub fn relative_path_from(&self, root: &Self) -> Option<String> {
|
||||
if decode_bad_path_uri(&self.0).is_some() || decode_bad_path_uri(&root.0).is_some() {
|
||||
return None;
|
||||
}
|
||||
let convention = self.infer_path_convention()?;
|
||||
if root.infer_path_convention() != Some(convention)
|
||||
|| self.0.host_str() != root.0.host_str()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
let candidate = lexical_segments(self);
|
||||
let root = lexical_segments(root);
|
||||
if convention == PathConvention::Windows
|
||||
&& (candidate.first().is_none_or(|segment| {
|
||||
self.0.host_str().is_none() && !is_windows_drive_uri_segment(segment)
|
||||
}) || root.first().is_none_or(|segment| {
|
||||
self.0.host_str().is_none() && !is_windows_drive_uri_segment(segment)
|
||||
}))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let relative = candidate.strip_prefix(root.as_slice())?;
|
||||
Some(
|
||||
relative
|
||||
.iter()
|
||||
.map(|segment| decode_uri_path(segment))
|
||||
.collect::<Vec<_>>()
|
||||
.join("/"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn inferred_absolute_path_convention(path: &str) -> Option<PathConvention> {
|
||||
let bytes = path.as_bytes();
|
||||
let rooted_drive = matches!(
|
||||
bytes,
|
||||
[drive, b':', separator, ..]
|
||||
if drive.is_ascii_alphabetic() && is_windows_separator_byte(*separator)
|
||||
);
|
||||
let unc = matches!(bytes, [b'\\', b'\\', third, ..] if !matches!(*third, b'.' | b'?'));
|
||||
if path.contains('\0') {
|
||||
None
|
||||
} else if rooted_drive || unc {
|
||||
Some(PathConvention::Windows)
|
||||
} else if path.starts_with('/') {
|
||||
Some(PathConvention::Posix)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn has_rooted_or_drive_prefix(path: &str) -> bool {
|
||||
matches!(path.as_bytes(), [b'/' | b'\\', ..])
|
||||
|| matches!(path.as_bytes(), [drive, b':', ..] if drive.is_ascii_alphabetic())
|
||||
}
|
||||
|
||||
fn lexical_segments(path: &PathUri) -> Vec<&str> {
|
||||
path.0
|
||||
.path_segments()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|segment| !segment.is_empty())
|
||||
.collect()
|
||||
}
|
||||
@@ -19,6 +19,7 @@ use ts_rs::TS;
|
||||
use url::Url;
|
||||
|
||||
mod api_path_string;
|
||||
mod lexical;
|
||||
|
||||
pub use api_path_string::LegacyAppPathString;
|
||||
pub use api_path_string::LegacyAppPathStringError;
|
||||
@@ -693,6 +694,10 @@ pub enum PathUriParseError {
|
||||
FragmentNotAllowed,
|
||||
#[error("path `{0}` must be relative when joining a path URI")]
|
||||
JoinPathMustBeRelative(String),
|
||||
#[error("relative path `{0}` escapes the base path URI")]
|
||||
JoinPathEscapesBase(String),
|
||||
#[error("path `{0}` is not an absolute POSIX, drive, or UNC path")]
|
||||
ExpectedAbsoluteNativePath(String),
|
||||
}
|
||||
|
||||
/// Path syntax used to render a [`PathUri`] as an operating-system path.
|
||||
|
||||
@@ -697,6 +697,204 @@ fn join_uses_the_base_uri_path_convention() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inferred_absolute_paths_parse_without_host_path_semantics() {
|
||||
for (path, expected) in [
|
||||
("/workspace/a file.rs", "file:///workspace/a%20file.rs"),
|
||||
("/tmp/100%", "file:///tmp/100%25"),
|
||||
(
|
||||
r"C:\Users\Alice Smith\main.rs",
|
||||
"file:///C:/Users/Alice%20Smith/main.rs",
|
||||
),
|
||||
("d:/src/main.rs", "file:///d:/src/main.rs"),
|
||||
(
|
||||
r"\\server\share\project\main.rs",
|
||||
"file://server/share/project/main.rs",
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
PathUri::from_inferred_absolute_path(path),
|
||||
Ok(PathUri::parse(expected).expect("valid expected URI")),
|
||||
"parsing {path}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inferred_absolute_paths_reject_other_input_forms() {
|
||||
for path in [
|
||||
"",
|
||||
".",
|
||||
"src/main.rs",
|
||||
r"C:src\main.rs",
|
||||
r"\Windows\System32",
|
||||
r"\\server",
|
||||
r"\\?\C:\workspace",
|
||||
r"\\.\COM1",
|
||||
"file:///workspace",
|
||||
"/tmp/null\0byte",
|
||||
] {
|
||||
assert_eq!(
|
||||
PathUri::from_inferred_absolute_path(path),
|
||||
Err(PathUriParseError::ExpectedAbsoluteNativePath(
|
||||
path.to_string()
|
||||
)),
|
||||
"parsing {path:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn join_relative_normalizes_target_relative_text() {
|
||||
for (base, relative, expected) in [
|
||||
(
|
||||
"file:///workspace/src",
|
||||
"generated/../lib.rs",
|
||||
"file:///workspace/src/lib.rs",
|
||||
),
|
||||
(
|
||||
"file:///C:/workspace/src",
|
||||
r"generated\..\lib.rs",
|
||||
"file:///C:/workspace/src/lib.rs",
|
||||
),
|
||||
("file:///workspace", "", "file:///workspace"),
|
||||
("file:///workspace", ".", "file:///workspace"),
|
||||
] {
|
||||
let base = PathUri::parse(base).expect("valid base URI");
|
||||
let expected = PathUri::parse(expected).expect("valid expected URI");
|
||||
assert_eq!(
|
||||
base.join_relative(relative),
|
||||
Ok(expected),
|
||||
"joining {relative}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn join_relative_rejects_rooted_text_under_either_path_grammar() {
|
||||
for base in ["file:///workspace", "file:///C:/workspace"] {
|
||||
let base = PathUri::parse(base).expect("valid base URI");
|
||||
for path in [
|
||||
"/tmp/file.rs",
|
||||
r"\Windows\file.rs",
|
||||
r"C:\tmp\file.rs",
|
||||
"C:/tmp/file.rs",
|
||||
r"C:tmp\file.rs",
|
||||
r"\\server\share\file.rs",
|
||||
"//server/share/file.rs",
|
||||
] {
|
||||
assert_eq!(
|
||||
base.join_relative(path),
|
||||
Err(PathUriParseError::JoinPathMustBeRelative(path.to_string())),
|
||||
"joining {path} to {base}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn join_relative_rejects_parent_traversal_above_the_base_uri() {
|
||||
for (base, path) in [
|
||||
("file:///workspace/src", "../tests"),
|
||||
("file:///", ".."),
|
||||
("file:///C:/workspace", r"..\Windows"),
|
||||
("file:///C:", ".."),
|
||||
("file://server/share/workspace", r"..\sibling"),
|
||||
("file://server/share", ".."),
|
||||
("file://server/", ".."),
|
||||
("file:///workspace", "child/../.."),
|
||||
] {
|
||||
let base = PathUri::parse(base).expect("valid base URI");
|
||||
assert_eq!(
|
||||
base.join_relative(path),
|
||||
Err(PathUriParseError::JoinPathEscapesBase(path.to_string())),
|
||||
"joining {path} to {base}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn join_relative_allows_normalization_that_stays_within_the_relative_input() {
|
||||
for (base, path, expected) in [
|
||||
("file:///workspace", "a/../b", "file:///workspace/b"),
|
||||
("file:///C:/workspace", r"a\..\b", "file:///C:/workspace/b"),
|
||||
(
|
||||
"file://server/share/workspace",
|
||||
r"a\..\b",
|
||||
"file://server/share/workspace/b",
|
||||
),
|
||||
] {
|
||||
let base = PathUri::parse(base).expect("valid base URI");
|
||||
let expected = PathUri::parse(expected).expect("valid expected URI");
|
||||
assert_eq!(base.join_relative(path), Ok(expected));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_path_from_returns_descendant_paths_with_normalized_separators() {
|
||||
for (candidate, root, expected) in [
|
||||
("file:///workspace", "file:///workspace", ""),
|
||||
(
|
||||
"file:///workspace/src/a%20file.rs",
|
||||
"file:///workspace",
|
||||
"src/a file.rs",
|
||||
),
|
||||
(
|
||||
"file:///workspace/src/a%252Fb",
|
||||
"file:///workspace",
|
||||
"src/a%2Fb",
|
||||
),
|
||||
(
|
||||
"file:///C:/workspace/src/main.rs",
|
||||
"file:///C:/workspace",
|
||||
"src/main.rs",
|
||||
),
|
||||
(
|
||||
"file://server/share/project/src/main.rs",
|
||||
"file://server/share/project",
|
||||
"src/main.rs",
|
||||
),
|
||||
("file:///workspace/src", "file:///", "workspace/src"),
|
||||
] {
|
||||
let candidate = PathUri::parse(candidate).expect("valid candidate URI");
|
||||
let root = PathUri::parse(root).expect("valid root URI");
|
||||
assert_eq!(
|
||||
candidate.relative_path_from(&root),
|
||||
Some(expected.to_string()),
|
||||
"relativizing {candidate} from {root}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_path_from_requires_authority_convention_and_descendant_containment() {
|
||||
for (candidate, root) in [
|
||||
("file:///workspace-other/file", "file:///workspace"),
|
||||
("file:///workspace", "file:///workspace/src"),
|
||||
("file:///sibling/file", "file:///workspace"),
|
||||
("file:///C:/workspace/file", "file:///D:/workspace"),
|
||||
("file:///C:/workspace/file", "file:///workspace"),
|
||||
(
|
||||
"file://other/share/workspace/file",
|
||||
"file://server/share/workspace",
|
||||
),
|
||||
(
|
||||
"file://server/other/workspace/file",
|
||||
"file://server/share/workspace",
|
||||
),
|
||||
("file://server/share/file", "file://server/"),
|
||||
("file:///%00/bad/path/YQ", "file:///%00/bad/path/YQ"),
|
||||
] {
|
||||
let candidate = PathUri::parse(candidate).expect("valid candidate URI");
|
||||
let root = PathUri::parse(root).expect("valid root URI");
|
||||
assert_eq!(
|
||||
candidate.relative_path_from(&root),
|
||||
None,
|
||||
"relativizing {candidate} from {root}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn to_url_returns_the_validated_url() {
|
||||
let uri = PathUri::parse("file://localhost/workspace/a%20file.rs").expect("valid file URI");
|
||||
|
||||
Reference in New Issue
Block a user