Base: codex-main originale (prima del fork aKode)
This commit is contained in:
46
codex-rs/utils/path-uri/src/absolute_path_normalization.rs
Normal file
46
codex-rs/utils/path-uri/src/absolute_path_normalization.rs
Normal file
@@ -0,0 +1,46 @@
|
||||
use crate::PathConvention;
|
||||
use crate::PathUri;
|
||||
use url::Url;
|
||||
|
||||
pub(super) fn path_uri_from_segments<'a>(
|
||||
convention: PathConvention,
|
||||
host: Option<&str>,
|
||||
segments: impl Iterator<Item = &'a str>,
|
||||
) -> Option<PathUri> {
|
||||
let mut url = Url::parse("file:///").ok()?;
|
||||
if let Some(host) = host {
|
||||
url.set_host(Some(host)).ok()?;
|
||||
}
|
||||
let anchor_depth = usize::from(convention == PathConvention::Windows);
|
||||
let mut depth = 0;
|
||||
let mut normalized_segments = Vec::new();
|
||||
let mut has_trailing_separator = false;
|
||||
for segment in segments {
|
||||
match segment {
|
||||
"" => has_trailing_separator = true,
|
||||
"." => has_trailing_separator = false,
|
||||
".." => {
|
||||
has_trailing_separator = false;
|
||||
if depth > anchor_depth {
|
||||
normalized_segments.pop();
|
||||
depth -= 1;
|
||||
}
|
||||
}
|
||||
segment => {
|
||||
normalized_segments.push(segment);
|
||||
depth += 1;
|
||||
has_trailing_separator = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if has_trailing_separator
|
||||
|| (convention == PathConvention::Windows && host.is_none() && depth == anchor_depth)
|
||||
{
|
||||
normalized_segments.push("");
|
||||
}
|
||||
{
|
||||
let mut url_segments = url.path_segments_mut().ok()?;
|
||||
url_segments.clear().extend(normalized_segments);
|
||||
}
|
||||
PathUri::try_from(url).ok()
|
||||
}
|
||||
444
codex-rs/utils/path-uri/src/api_path_string.rs
Normal file
444
codex-rs/utils/path-uri/src/api_path_string.rs
Normal file
@@ -0,0 +1,444 @@
|
||||
use crate::PathConvention;
|
||||
use crate::PathUri;
|
||||
use crate::PathUriParseError;
|
||||
use crate::is_windows_separator_byte;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use serde::Serializer;
|
||||
use std::fmt;
|
||||
use std::path::Path;
|
||||
use thiserror::Error;
|
||||
use ts_rs::TS;
|
||||
|
||||
/// A UTF-8 path for preserving raw path compatibility at the app-server API
|
||||
/// boundary while Codex migrates to [`PathUri`].
|
||||
///
|
||||
/// Supports storing arbitrary strings read from the API and converting to and
|
||||
/// from [`PathUri`] using an explicitly selected native path convention.
|
||||
///
|
||||
/// When converting from [`PathUri`], "native" refers to the supplied
|
||||
/// [`PathConvention`], which may be foreign to the operating system running
|
||||
/// this process. The inner string is private so path-producing code must use a
|
||||
/// path conversion method instead of bypassing the intended conversion
|
||||
/// boundary. Non-UTF-8 paths are converted to UTF-8 lossily because this API
|
||||
/// value is serialized as a JSON string.
|
||||
///
|
||||
/// Deserialization and [`Self::from_string`] accept any UTF-8 string without
|
||||
/// interpreting or validating it. Use [`Self::from_string`] when a caller
|
||||
/// already owns legacy app-server path text and needs to preserve its wire
|
||||
/// spelling; use [`Self::from_path`], [`Self::from_abs_path`], or
|
||||
/// [`Self::from_path_uri`] when converting an actual path value. Relative
|
||||
/// path text remains valid until an operation such as [`Self::to_path_uri`]
|
||||
/// requires an absolute path.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, TS)]
|
||||
#[serde(transparent)]
|
||||
#[ts(type = "string")]
|
||||
pub struct LegacyAppPathString(String);
|
||||
|
||||
impl LegacyAppPathString {
|
||||
/// Preserves already-legacy app-server path text without interpreting it
|
||||
/// using the current host.
|
||||
///
|
||||
/// This is for API-boundary values that are already strings, including
|
||||
/// relative or foreign-platform spellings. Callers with a local
|
||||
/// [`Path`], [`AbsolutePathBuf`], or [`PathUri`] should use the
|
||||
/// corresponding typed constructor instead.
|
||||
pub fn from_string(path: impl Into<String>) -> Self {
|
||||
Self(path.into())
|
||||
}
|
||||
|
||||
/// Preserves path text without interpreting it using the current host.
|
||||
pub fn from_path(path: &Path) -> Self {
|
||||
Self(path.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
/// Renders an absolute path using the current host's path convention.
|
||||
pub fn from_abs_path(path: &AbsolutePathBuf) -> Self {
|
||||
Self::from_path(path.as_path())
|
||||
}
|
||||
|
||||
/// Renders a path URI using the requested native path convention.
|
||||
///
|
||||
/// Rendering fails when the URI shape does not match the convention, such
|
||||
/// as a POSIX path rendered as Windows or a UNC path rendered as POSIX. It
|
||||
/// also fails when an opaque fallback does not encode an absolute path for
|
||||
/// the convention. Non-UTF-8 segments are rendered lossily, and encoded
|
||||
/// separators are emitted as native path text.
|
||||
pub fn from_path_uri(
|
||||
path: &PathUri,
|
||||
convention: PathConvention,
|
||||
) -> Result<Self, LegacyAppPathStringError> {
|
||||
if let Some(path_bytes) = path.opaque_fallback_bytes() {
|
||||
return render_opaque_fallback(path, &path_bytes, convention).map(Self);
|
||||
}
|
||||
match convention {
|
||||
PathConvention::Posix => render_posix_path(path),
|
||||
PathConvention::Windows => render_windows_path(path),
|
||||
}
|
||||
.map(Self)
|
||||
}
|
||||
|
||||
/// Parses this API string as an absolute path using the requested native
|
||||
/// path convention and returns its canonical path URI.
|
||||
pub fn to_path_uri(
|
||||
&self,
|
||||
convention: PathConvention,
|
||||
) -> Result<PathUri, LegacyAppPathStringError> {
|
||||
PathUri::from_absolute_native_path(&self.0, convention).ok_or_else(|| {
|
||||
LegacyAppPathStringError::InvalidNativePath {
|
||||
path: self.0.clone(),
|
||||
convention: Some(convention),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolves this raw API path spelling against an executor cwd.
|
||||
///
|
||||
/// Relative paths use the cwd's inferred convention. Home-relative paths
|
||||
/// use the supplied executor home, and clearly foreign absolute paths are
|
||||
/// rejected rather than reinterpreted as relative path text.
|
||||
pub fn resolve_against(
|
||||
&self,
|
||||
cwd: &PathUri,
|
||||
user_home_dir: Option<&PathUri>,
|
||||
) -> Result<PathUri, LegacyAppPathStringError> {
|
||||
let convention = cwd.infer_path_convention().ok_or_else(|| {
|
||||
LegacyAppPathStringError::MissingBaseConvention {
|
||||
cwd: cwd.to_string(),
|
||||
}
|
||||
})?;
|
||||
let is_windows = convention == PathConvention::Windows;
|
||||
let path = self.as_str();
|
||||
let home_relative = convention.home_relative_suffix(path);
|
||||
if let Some(suffix) = home_relative {
|
||||
let home =
|
||||
user_home_dir.ok_or_else(|| LegacyAppPathStringError::MissingHomeDirectory {
|
||||
path: path.to_string(),
|
||||
})?;
|
||||
return Ok(home.join(suffix.trim_start_matches(|separator| {
|
||||
separator == '/' || is_windows && separator == '\\'
|
||||
}))?);
|
||||
}
|
||||
|
||||
if is_windows && (path.starts_with("//") || path.starts_with(r"\\")) {
|
||||
return self.to_path_uri(PathConvention::Windows);
|
||||
}
|
||||
|
||||
match self.infer_absolute_path_convention() {
|
||||
Some(path_convention) if path_convention == convention => self.to_path_uri(convention),
|
||||
Some(PathConvention::Posix) if is_windows => Ok(cwd.join(path)?),
|
||||
Some(path_convention) => Err(LegacyAppPathStringError::MismatchedConvention {
|
||||
path: path.to_string(),
|
||||
path_convention,
|
||||
cwd: cwd.to_string(),
|
||||
convention,
|
||||
}),
|
||||
None => Ok(cwd.join(path)?),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses this API string as an absolute path using the convention inferred from its spelling.
|
||||
pub fn to_inferred_path_uri(&self) -> Option<PathUri> {
|
||||
PathUri::try_from(self.clone()).ok()
|
||||
}
|
||||
|
||||
/// Renders this API path for display in a user interface.
|
||||
///
|
||||
/// Absolute paths are normalized using their inferred native convention.
|
||||
/// Strings that cannot be interpreted as absolute paths retain their raw
|
||||
/// API spelling.
|
||||
pub fn render_for_ui(&self) -> String {
|
||||
self.to_inferred_path_uri()
|
||||
.map(|path| path.inferred_native_path_string())
|
||||
.unwrap_or_else(|| self.0.clone())
|
||||
}
|
||||
|
||||
/// Parses this API string as a host-native absolute path.
|
||||
pub fn to_inferred_abs_path(&self) -> Option<AbsolutePathBuf> {
|
||||
AbsolutePathBuf::try_from(self.clone()).ok()
|
||||
}
|
||||
|
||||
/// Infers the path convention of an absolute API path from its spelling.
|
||||
///
|
||||
/// Two leading separators select Windows UNC or namespace syntax, including
|
||||
/// forward and mixed slashes, independently of the current host. This favors
|
||||
/// UNC paths over ambiguous double-slash POSIX paths. Call [`Self::to_path_uri`]
|
||||
/// with an explicit POSIX convention to preserve that interpretation.
|
||||
/// Relative paths return `None`; inferred prefixes still require validation.
|
||||
pub fn infer_absolute_path_convention(&self) -> Option<PathConvention> {
|
||||
let bytes = self.0.as_bytes();
|
||||
let has_windows_drive_root = matches!(
|
||||
bytes,
|
||||
[drive, b':', separator, ..]
|
||||
if drive.is_ascii_alphabetic() && is_windows_separator_byte(*separator)
|
||||
);
|
||||
let has_windows_unc_root = matches!(
|
||||
bytes,
|
||||
[first, second, ..]
|
||||
if is_windows_separator_byte(*first) && is_windows_separator_byte(*second)
|
||||
);
|
||||
if has_windows_drive_root || has_windows_unc_root {
|
||||
Some(PathConvention::Windows)
|
||||
} else if self.0.starts_with('/') {
|
||||
Some(PathConvention::Posix)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
|
||||
pub fn into_string(self) -> String {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl From<AbsolutePathBuf> for LegacyAppPathString {
|
||||
fn from(path: AbsolutePathBuf) -> Self {
|
||||
Self::from_abs_path(&path)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PathUri> for LegacyAppPathString {
|
||||
fn from(path: PathUri) -> Self {
|
||||
Self(path.inferred_native_path_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<LegacyAppPathString> for PathUri {
|
||||
type Error = LegacyAppPathStringError;
|
||||
|
||||
fn try_from(path: LegacyAppPathString) -> Result<Self, Self::Error> {
|
||||
let Some(convention) = path.infer_absolute_path_convention() else {
|
||||
return Err(LegacyAppPathStringError::InvalidNativePath {
|
||||
path: path.0,
|
||||
convention: None,
|
||||
});
|
||||
};
|
||||
PathUri::from_absolute_native_path(path.as_str(), convention).ok_or({
|
||||
LegacyAppPathStringError::InvalidNativePath {
|
||||
path: path.0,
|
||||
convention: Some(convention),
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<LegacyAppPathString> for AbsolutePathBuf {
|
||||
type Error = LegacyAppPathStringError;
|
||||
|
||||
fn try_from(path: LegacyAppPathString) -> Result<Self, Self::Error> {
|
||||
AbsolutePathBuf::from_absolute_path_checked(path.as_str()).map_err(|_| {
|
||||
LegacyAppPathStringError::InvalidNativePath {
|
||||
path: path.0,
|
||||
convention: None,
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn render_opaque_fallback(
|
||||
path: &PathUri,
|
||||
path_bytes: &[u8],
|
||||
convention: PathConvention,
|
||||
) -> Result<String, LegacyAppPathStringError> {
|
||||
let rendered = match convention {
|
||||
PathConvention::Posix if path_bytes.starts_with(b"/") => {
|
||||
Some(String::from_utf8_lossy(path_bytes).into_owned())
|
||||
}
|
||||
PathConvention::Windows => render_windows_opaque_fallback(path_bytes),
|
||||
PathConvention::Posix => None,
|
||||
};
|
||||
rendered.ok_or_else(|| LegacyAppPathStringError::OpaqueFallback {
|
||||
path: path.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
fn render_windows_opaque_fallback(path_bytes: &[u8]) -> Option<String> {
|
||||
if !path_bytes.len().is_multiple_of(2) {
|
||||
return None;
|
||||
}
|
||||
let path_wide = path_bytes
|
||||
.chunks_exact(2)
|
||||
.map(|bytes| u16::from_le_bytes([bytes[0], bytes[1]]))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Windows absolute paths either have a rooted drive prefix (`C:\\`) or a
|
||||
// rooted namespace/UNC prefix (`\\server`, `\\.\\`, or `\\?\\`).
|
||||
let has_drive_root = matches!(
|
||||
path_wide.as_slice(),
|
||||
[drive, colon, separator, ..]
|
||||
if ((u16::from(b'A')..=u16::from(b'Z')).contains(drive)
|
||||
|| (u16::from(b'a')..=u16::from(b'z')).contains(drive))
|
||||
&& *colon == u16::from(b':')
|
||||
&& is_windows_separator(*separator)
|
||||
);
|
||||
let has_namespace_or_unc_root = matches!(
|
||||
path_wide.as_slice(),
|
||||
[first, second, ..]
|
||||
if is_windows_separator(*first) && is_windows_separator(*second)
|
||||
);
|
||||
(has_drive_root || has_namespace_or_unc_root).then(|| String::from_utf16_lossy(&path_wide))
|
||||
}
|
||||
|
||||
fn is_windows_separator(character: u16) -> bool {
|
||||
character == u16::from(b'\\') || character == u16::from(b'/')
|
||||
}
|
||||
|
||||
impl fmt::Display for LegacyAppPathString {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for LegacyAppPathString {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
serializer.serialize_str(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for LegacyAppPathString {
|
||||
fn schema_name() -> String {
|
||||
"LegacyAppPathString".to_string()
|
||||
}
|
||||
|
||||
fn json_schema(generator: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {
|
||||
String::json_schema(generator)
|
||||
}
|
||||
}
|
||||
|
||||
fn render_posix_path(path: &PathUri) -> Result<String, LegacyAppPathStringError> {
|
||||
let url = path.to_url();
|
||||
// POSIX file paths do not have a UNC authority, so `file://server/share`
|
||||
// cannot be represented as `/share` without losing the server identity.
|
||||
if url.host_str().is_some() {
|
||||
return Err(incompatible_convention(path, PathConvention::Posix));
|
||||
}
|
||||
|
||||
// URI segments are already separated with `/` on every host. Decode each
|
||||
// one independently so `file:///a%20dir/file` becomes `/a dir/file`.
|
||||
let mut rendered = String::new();
|
||||
for segment in path_segments(&url) {
|
||||
rendered.push('/');
|
||||
rendered.push_str(&decode_native_segment(segment));
|
||||
}
|
||||
Ok(rendered)
|
||||
}
|
||||
|
||||
fn render_windows_path(path: &PathUri) -> Result<String, LegacyAppPathStringError> {
|
||||
let url = path.to_url();
|
||||
let mut segments = path_segments(&url);
|
||||
let mut rendered = String::new();
|
||||
if let Some(host) = url.host_str() {
|
||||
// A URI authority selects the UNC form: `file://server/share/file`
|
||||
// becomes `\\server\share\file`. The first segment is the share name,
|
||||
// which must be present.
|
||||
let Some(share) = segments.next() else {
|
||||
return Err(incompatible_convention(path, PathConvention::Windows));
|
||||
};
|
||||
let share = decode_native_segment(share);
|
||||
if share.is_empty() {
|
||||
return Err(incompatible_convention(path, PathConvention::Windows));
|
||||
}
|
||||
rendered.push_str(r"\\");
|
||||
rendered.push_str(host);
|
||||
rendered.push('\\');
|
||||
rendered.push_str(&share);
|
||||
} else {
|
||||
// Without an authority, Windows requires a drive root. For example,
|
||||
// `file:///C:/src/main.rs` begins with the `C:` URI segment and renders
|
||||
// as `C:\src\main.rs`; a POSIX URI such as `file:///usr/bin` is rejected.
|
||||
let Some(drive) = segments.next() else {
|
||||
return Err(incompatible_convention(path, PathConvention::Windows));
|
||||
};
|
||||
let drive = decode_native_segment(drive);
|
||||
let bytes = drive.as_bytes();
|
||||
if bytes.len() != 2 || !bytes[0].is_ascii_alphabetic() || bytes[1] != b':' {
|
||||
return Err(incompatible_convention(path, PathConvention::Windows));
|
||||
}
|
||||
rendered.push_str(&drive);
|
||||
}
|
||||
|
||||
for segment in segments {
|
||||
// URL path separators become Windows separators after each component
|
||||
// has been decoded.
|
||||
let segment = decode_native_segment(segment);
|
||||
rendered.push('\\');
|
||||
rendered.push_str(&segment);
|
||||
}
|
||||
// `file:///C:` and `file:///C:/` both identify the drive root, never the
|
||||
// drive-relative path `C:`.
|
||||
if rendered.len() == 2 && rendered.as_bytes()[1] == b':' {
|
||||
rendered.push('\\');
|
||||
}
|
||||
Ok(rendered)
|
||||
}
|
||||
|
||||
fn path_segments(url: &url::Url) -> std::str::Split<'_, char> {
|
||||
url.path_segments()
|
||||
.unwrap_or_else(|| unreachable!("validated file URLs have path segments"))
|
||||
}
|
||||
|
||||
fn decode_native_segment(segment: &str) -> String {
|
||||
// Decode exactly once. Thus `%20` becomes a space and `%252F` becomes the
|
||||
// literal text `%2F`, rather than being decoded a second time into `/`.
|
||||
let bytes = urlencoding::decode_binary(segment.as_bytes());
|
||||
String::from_utf8_lossy(&bytes).into_owned()
|
||||
}
|
||||
|
||||
fn incompatible_convention(path: &PathUri, convention: PathConvention) -> LegacyAppPathStringError {
|
||||
LegacyAppPathStringError::IncompatibleConvention {
|
||||
path: path.to_string(),
|
||||
convention,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Error, PartialEq, Eq)]
|
||||
pub enum LegacyAppPathStringError {
|
||||
#[error("opaque fallback path URI `{path}` cannot be recovered as a native path")]
|
||||
OpaqueFallback { path: String },
|
||||
#[error("path URI `{path}` cannot be rendered using {convention} path syntax")]
|
||||
IncompatibleConvention {
|
||||
path: String,
|
||||
convention: PathConvention,
|
||||
},
|
||||
#[error(
|
||||
"path `{path}` is not absolute{convention}",
|
||||
convention = .convention.map(|convention| format!(" using {convention} path syntax")).unwrap_or_default()
|
||||
)]
|
||||
InvalidNativePath {
|
||||
path: String,
|
||||
convention: Option<PathConvention>,
|
||||
},
|
||||
#[error("unsupported configuration path {path:?} using {convention} path syntax")]
|
||||
UnsupportedConfigPath {
|
||||
path: String,
|
||||
convention: PathConvention,
|
||||
},
|
||||
#[error("path URI `{cwd}` has no path convention")]
|
||||
MissingBaseConvention { cwd: String },
|
||||
#[error("cannot resolve home-relative path `{path}` without an executor home")]
|
||||
MissingHomeDirectory { path: String },
|
||||
#[error(
|
||||
"path {path} uses {path_convention} paths, but executor cwd {cwd} uses {convention} paths"
|
||||
)]
|
||||
MismatchedConvention {
|
||||
path: String,
|
||||
path_convention: PathConvention,
|
||||
cwd: String,
|
||||
convention: PathConvention,
|
||||
},
|
||||
#[error(transparent)]
|
||||
PathUri(#[from] PathUriParseError),
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "api_path_string_tests.rs"]
|
||||
mod tests;
|
||||
718
codex-rs/utils/path-uri/src/api_path_string_tests.rs
Normal file
718
codex-rs/utils/path-uri/src/api_path_string_tests.rs
Normal file
@@ -0,0 +1,718 @@
|
||||
use super::*;
|
||||
use crate::PathUri;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct RenderCase {
|
||||
uri: &'static str,
|
||||
convention: PathConvention,
|
||||
expected: RenderExpectation,
|
||||
}
|
||||
|
||||
impl RenderCase {
|
||||
const fn round_trips(
|
||||
uri: &'static str,
|
||||
convention: PathConvention,
|
||||
rendered: &'static str,
|
||||
) -> Self {
|
||||
Self {
|
||||
uri,
|
||||
convention,
|
||||
expected: RenderExpectation::RoundTrip(rendered),
|
||||
}
|
||||
}
|
||||
|
||||
const fn rejects(uri: &'static str, convention: PathConvention, error: ExpectedError) -> Self {
|
||||
Self {
|
||||
uri,
|
||||
convention,
|
||||
expected: RenderExpectation::Error(error),
|
||||
}
|
||||
}
|
||||
|
||||
const fn renders_lossily(
|
||||
uri: &'static str,
|
||||
convention: PathConvention,
|
||||
rendered: &'static str,
|
||||
) -> Self {
|
||||
Self {
|
||||
uri,
|
||||
convention,
|
||||
expected: RenderExpectation::RenderOnly(rendered),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum RenderExpectation {
|
||||
RoundTrip(&'static str),
|
||||
RenderOnly(&'static str),
|
||||
Error(ExpectedError),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum ExpectedError {
|
||||
OpaqueFallback,
|
||||
IncompatibleConvention,
|
||||
}
|
||||
|
||||
const RENDER_CASES: &[RenderCase] = &[
|
||||
// POSIX paths.
|
||||
RenderCase::round_trips("file:///", PathConvention::Posix, "/"),
|
||||
RenderCase::round_trips(
|
||||
"file:///home/alice/src/main.rs",
|
||||
PathConvention::Posix,
|
||||
"/home/alice/src/main.rs",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///home/alice/a%20file.rs",
|
||||
PathConvention::Posix,
|
||||
"/home/alice/a file.rs",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///workspace/src/lib.rs",
|
||||
PathConvention::Posix,
|
||||
"/workspace/src/lib.rs",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///workspace/tests/test.rs",
|
||||
PathConvention::Posix,
|
||||
"/workspace/tests/test.rs",
|
||||
),
|
||||
RenderCase::round_trips("file:///etc", PathConvention::Posix, "/etc"),
|
||||
RenderCase::round_trips("file:///tmp/", PathConvention::Posix, "/tmp/"),
|
||||
RenderCase::renders_lossily("file:///C:/Project", PathConvention::Posix, "/C:/Project"),
|
||||
RenderCase::renders_lossily("file:///C:", PathConvention::Posix, "/C:"),
|
||||
RenderCase::round_trips("file:///tmp/%E2%98%83", PathConvention::Posix, "/tmp/☃"),
|
||||
RenderCase::round_trips("file:///tmp/a%5Cb", PathConvention::Posix, "/tmp/a\\b"),
|
||||
RenderCase::round_trips(
|
||||
"file:///tmp/100%25/file",
|
||||
PathConvention::Posix,
|
||||
"/tmp/100%/file",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///tmp/a%3Fb%23c%25d",
|
||||
PathConvention::Posix,
|
||||
"/tmp/a?b#c%d",
|
||||
),
|
||||
RenderCase::round_trips("file:///tmp/a%252Fb", PathConvention::Posix, "/tmp/a%2Fb"),
|
||||
RenderCase::round_trips(
|
||||
"file:///bad/path/L3RtcC9udWxsLQAt_y1ieXRl",
|
||||
PathConvention::Posix,
|
||||
"/bad/path/L3RtcC9udWxsLQAt_y1ieXRl",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"FILE:///workspace/src",
|
||||
PathConvention::Posix,
|
||||
"/workspace/src",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:/workspace/src",
|
||||
PathConvention::Posix,
|
||||
"/workspace/src",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file://localhost/workspace/src",
|
||||
PathConvention::Posix,
|
||||
"/workspace/src",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file://LOCALHOST/workspace/src",
|
||||
PathConvention::Posix,
|
||||
"/workspace/src",
|
||||
),
|
||||
// Windows drive paths.
|
||||
RenderCase::round_trips(
|
||||
"file:///C:/Users/Alice%20Smith/src/main.rs",
|
||||
PathConvention::Windows,
|
||||
r"C:\Users\Alice Smith\src\main.rs",
|
||||
),
|
||||
RenderCase::round_trips("file:///C:/", PathConvention::Windows, "C:\\"),
|
||||
RenderCase::renders_lossily("file:///C:", PathConvention::Windows, "C:\\"),
|
||||
RenderCase::round_trips("file:///C:/Users", PathConvention::Windows, r"C:\Users"),
|
||||
RenderCase::round_trips("file:///C:/Windows", PathConvention::Windows, r"C:\Windows"),
|
||||
RenderCase::round_trips(
|
||||
"file:///d:/snowman/%E2%98%83",
|
||||
PathConvention::Windows,
|
||||
r"D:\snowman\☃",
|
||||
),
|
||||
RenderCase::round_trips("file:///C:/tmp/", PathConvention::Windows, "C:\\tmp\\"),
|
||||
RenderCase::round_trips(
|
||||
"file:///C:/test%20with%20%25/path",
|
||||
PathConvention::Windows,
|
||||
r"C:\test with %\path",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///C:/test%20with%20%2525/c%23code",
|
||||
PathConvention::Windows,
|
||||
r"C:\test with %25\c#code",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///C:/Source/Z%C3%BCrich%20or%20Zurich%20(%CB%88zj%CA%8A%C9%99r%C9%AAk,/Code/resources/app/plugins/c%23/plugin.json",
|
||||
PathConvention::Windows,
|
||||
r"C:\Source\Zürich or Zurich (ˈzjʊərɪk,\Code\resources\app\plugins\c#\plugin.json",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///C:/project/owner's_file/database.sqlite",
|
||||
PathConvention::Windows,
|
||||
r"C:\project\owner's_file\database.sqlite",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///C:/project/%25A0.txt",
|
||||
PathConvention::Windows,
|
||||
r"C:\project\%A0.txt",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///C:/project/%252e.txt",
|
||||
PathConvention::Windows,
|
||||
r"C:\project\%2e.txt",
|
||||
),
|
||||
// Windows UNC paths.
|
||||
RenderCase::round_trips(
|
||||
"file://server/share/src/main.rs",
|
||||
PathConvention::Windows,
|
||||
r"\\server\share\src\main.rs",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file://server/share",
|
||||
PathConvention::Windows,
|
||||
r"\\server\share",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file://server/share/",
|
||||
PathConvention::Windows,
|
||||
"\\\\server\\share\\",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file://shares/files/c%23/p.cs",
|
||||
PathConvention::Windows,
|
||||
r"\\shares\files\c#\p.cs",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file://monacotools1/certificates/SSL/",
|
||||
PathConvention::Windows,
|
||||
"\\\\monacotools1\\certificates\\SSL\\",
|
||||
),
|
||||
// Opaque fallbacks rendered according to their source convention.
|
||||
RenderCase::renders_lossily(
|
||||
"file:///%00/bad/path/L3RtcC9udWxsLQAt_y1ieXRl",
|
||||
PathConvention::Posix,
|
||||
"/tmp/null-\0-<2D>-byte",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///%00/bad/path/XABcAC4AXABDAE8ATQAxAFwA",
|
||||
PathConvention::Windows,
|
||||
r"\\.\COM1\",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///%00/bad/path/XABcAD8AXABWAG8AbAB1AG0AZQB7ADAAMAAwADAAMAAwADAAMAAtADAAMAAwADAALQAwADAAMAAwAC0AMAAwADAAMAAtADAAMAAwADAAMAAwADAAMAAwADAAMAAwAH0AXABmAGkAbABlAC4AcgBzAA",
|
||||
PathConvention::Windows,
|
||||
r"\\?\Volume{00000000-0000-0000-0000-000000000000}\file.rs",
|
||||
),
|
||||
// Windows rendering preserves path text without filesystem validation.
|
||||
RenderCase::round_trips("file:///C:/a%3Fb", PathConvention::Windows, "C:\\a?b"),
|
||||
RenderCase::round_trips("file:///C:/a*b", PathConvention::Windows, "C:\\a*b"),
|
||||
RenderCase::round_trips(
|
||||
"file:///C:/trailing.",
|
||||
PathConvention::Windows,
|
||||
"C:\\trailing.",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///C:/trailing%20",
|
||||
PathConvention::Windows,
|
||||
"C:\\trailing ",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///C:/control-%01",
|
||||
PathConvention::Windows,
|
||||
"C:\\control-\u{1}",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file:///C:/file.txt:stream",
|
||||
PathConvention::Windows,
|
||||
"C:\\file.txt:stream",
|
||||
),
|
||||
RenderCase::round_trips(
|
||||
"file://server/sh%3Fare/file.rs",
|
||||
PathConvention::Windows,
|
||||
"\\\\server\\sh?are\\file.rs",
|
||||
),
|
||||
// These renderings intentionally lose URI byte or segment boundaries.
|
||||
RenderCase::renders_lossily(
|
||||
"file:///tmp/non-utf8-%FF",
|
||||
PathConvention::Posix,
|
||||
"/tmp/non-utf8-<2D>",
|
||||
),
|
||||
RenderCase::renders_lossily(
|
||||
"file:///tmp/non-utf8-%A0",
|
||||
PathConvention::Posix,
|
||||
"/tmp/non-utf8-<2D>",
|
||||
),
|
||||
RenderCase::renders_lossily("file:///tmp/a%2Fb", PathConvention::Posix, "/tmp/a/b"),
|
||||
RenderCase::renders_lossily("file:///C:/a%2Fb", PathConvention::Windows, "C:\\a/b"),
|
||||
RenderCase::renders_lossily("file:///C:/a%5Cb", PathConvention::Windows, "C:\\a\\b"),
|
||||
// URI shapes that do not match the requested convention.
|
||||
RenderCase::rejects(
|
||||
"file://server/share/file.txt",
|
||||
PathConvention::Posix,
|
||||
ExpectedError::IncompatibleConvention,
|
||||
),
|
||||
RenderCase::rejects(
|
||||
"file://server/share/file.rs",
|
||||
PathConvention::Posix,
|
||||
ExpectedError::IncompatibleConvention,
|
||||
),
|
||||
RenderCase::rejects(
|
||||
"file:///usr/local/file.txt",
|
||||
PathConvention::Windows,
|
||||
ExpectedError::IncompatibleConvention,
|
||||
),
|
||||
RenderCase::rejects(
|
||||
"file:///home/alice/file.rs",
|
||||
PathConvention::Windows,
|
||||
ExpectedError::IncompatibleConvention,
|
||||
),
|
||||
RenderCase::rejects(
|
||||
"file://server/",
|
||||
PathConvention::Windows,
|
||||
ExpectedError::IncompatibleConvention,
|
||||
),
|
||||
RenderCase::rejects(
|
||||
"file:///_:/path",
|
||||
PathConvention::Windows,
|
||||
ExpectedError::IncompatibleConvention,
|
||||
),
|
||||
// Invalid opaque fallback payloads.
|
||||
RenderCase::rejects(
|
||||
"file:///%00/bad/path/YQ",
|
||||
PathConvention::Posix,
|
||||
ExpectedError::OpaqueFallback,
|
||||
),
|
||||
RenderCase::rejects(
|
||||
"file:///%00/bad/path/L3RtcC9udWxsLQAt_y1ieXRl",
|
||||
PathConvention::Windows,
|
||||
ExpectedError::OpaqueFallback,
|
||||
),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn renders_native_paths_from_shared_cases() {
|
||||
for case in RENDER_CASES {
|
||||
let path = PathUri::parse(case.uri).expect("valid file URI");
|
||||
let expected = match case.expected {
|
||||
RenderExpectation::RoundTrip(rendered) => Ok(LegacyAppPathString(rendered.to_string())),
|
||||
RenderExpectation::RenderOnly(rendered) => {
|
||||
Ok(LegacyAppPathString(rendered.to_string()))
|
||||
}
|
||||
RenderExpectation::Error(ExpectedError::OpaqueFallback) => {
|
||||
Err(LegacyAppPathStringError::OpaqueFallback {
|
||||
path: path.to_string(),
|
||||
})
|
||||
}
|
||||
RenderExpectation::Error(ExpectedError::IncompatibleConvention) => {
|
||||
Err(LegacyAppPathStringError::IncompatibleConvention {
|
||||
path: path.to_string(),
|
||||
convention: case.convention,
|
||||
})
|
||||
}
|
||||
};
|
||||
let actual = LegacyAppPathString::from_path_uri(&path, case.convention);
|
||||
|
||||
assert_eq!(actual, expected, "rendering {case:?}");
|
||||
if let Ok(rendered) = &actual {
|
||||
assert_eq!(
|
||||
rendered.infer_absolute_path_convention(),
|
||||
Some(case.convention),
|
||||
"inferring {case:?}"
|
||||
);
|
||||
}
|
||||
|
||||
if let RenderExpectation::RoundTrip(rendered) = case.expected {
|
||||
let api_path =
|
||||
serde_json::from_value::<LegacyAppPathString>(serde_json::json!(rendered))
|
||||
.expect("native path should deserialize from API text");
|
||||
let reparsed = api_path
|
||||
.to_path_uri(case.convention)
|
||||
.expect("native path should parse using its convention");
|
||||
assert_eq!(reparsed, path, "parsing {case:?}");
|
||||
assert_eq!(
|
||||
LegacyAppPathString::from_path_uri(&reparsed, case.convention),
|
||||
Ok(api_path),
|
||||
"round-tripping {case:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_api_path_serializes_and_deserializes_unchanged() {
|
||||
for raw_path in [".", "subdir", "subdir/file.rs"] {
|
||||
let path = serde_json::from_value::<LegacyAppPathString>(serde_json::json!(raw_path))
|
||||
.expect("relative API path should deserialize");
|
||||
|
||||
assert_eq!(
|
||||
serde_json::to_value(path).expect("relative API path should serialize"),
|
||||
serde_json::json!(raw_path)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_api_path_is_invalid_when_converted_to_a_path_uri() {
|
||||
let raw_path = "subdir";
|
||||
let path = serde_json::from_value::<LegacyAppPathString>(serde_json::json!(raw_path))
|
||||
.expect("relative API path should deserialize");
|
||||
|
||||
assert_eq!(path.infer_absolute_path_convention(), None);
|
||||
assert_eq!(
|
||||
path.to_path_uri(PathConvention::Posix),
|
||||
Err(LegacyAppPathStringError::InvalidNativePath {
|
||||
path: raw_path.to_string(),
|
||||
convention: Some(PathConvention::Posix),
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
PathUri::try_from(path.clone()),
|
||||
Err(LegacyAppPathStringError::InvalidNativePath {
|
||||
path: raw_path.to_string(),
|
||||
convention: None,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
AbsolutePathBuf::try_from(path),
|
||||
Err(LegacyAppPathStringError::InvalidNativePath {
|
||||
path: raw_path.to_string(),
|
||||
convention: None,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_non_absolute_api_paths_cannot_be_converted_to_path_uris() {
|
||||
for (raw_path, convention) in [
|
||||
(r"workspace\file.rs", PathConvention::Windows),
|
||||
(r"C:file.rs", PathConvention::Windows),
|
||||
] {
|
||||
let path = serde_json::from_value::<LegacyAppPathString>(serde_json::json!(raw_path))
|
||||
.expect("API path should deserialize without validation");
|
||||
|
||||
assert_eq!(path.infer_absolute_path_convention(), None);
|
||||
assert_eq!(
|
||||
path.to_path_uri(convention),
|
||||
Err(LegacyAppPathStringError::InvalidNativePath {
|
||||
path: raw_path.to_string(),
|
||||
convention: Some(convention),
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn infers_absolute_path_conventions_from_api_text() {
|
||||
for (raw_path, expected) in [
|
||||
(r"C:\workspace\file.rs", Some(PathConvention::Windows)),
|
||||
("c:/workspace/file.rs", Some(PathConvention::Windows)),
|
||||
(r"\\server\share\file.rs", Some(PathConvention::Windows)),
|
||||
(r"\\?\C:\workspace\file.rs", Some(PathConvention::Windows)),
|
||||
(r"\\.\COM1", Some(PathConvention::Windows)),
|
||||
("/workspace/file.rs", Some(PathConvention::Posix)),
|
||||
("/C:/workspace/file.rs", Some(PathConvention::Posix)),
|
||||
("//server/share/file.rs", Some(PathConvention::Windows)),
|
||||
("", None),
|
||||
(".", None),
|
||||
("subdir/file.rs", None),
|
||||
(r"subdir\file.rs", None),
|
||||
(r"C:file.rs", None),
|
||||
(r"\rooted-without-drive", None),
|
||||
] {
|
||||
let path = serde_json::from_value::<LegacyAppPathString>(serde_json::json!(raw_path))
|
||||
.expect("API path should deserialize without validation");
|
||||
|
||||
assert_eq!(
|
||||
path.infer_absolute_path_convention(),
|
||||
expected,
|
||||
"inferring {raw_path:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_absolute_api_paths_using_the_inferred_convention() {
|
||||
for (raw_path, convention, expected_uri) in [
|
||||
(
|
||||
r"C:\workspace\file.rs",
|
||||
PathConvention::Windows,
|
||||
"file:///C:/workspace/file.rs",
|
||||
),
|
||||
(
|
||||
"/workspace/file.rs",
|
||||
PathConvention::Posix,
|
||||
"file:///workspace/file.rs",
|
||||
),
|
||||
] {
|
||||
let path = serde_json::from_value::<LegacyAppPathString>(serde_json::json!(raw_path))
|
||||
.expect("absolute API path should deserialize");
|
||||
|
||||
assert_eq!(
|
||||
path.to_inferred_path_uri(),
|
||||
Some(PathUri::parse(expected_uri).expect("expected URI should parse")),
|
||||
);
|
||||
assert_eq!(path.render_for_ui(), raw_path);
|
||||
assert_eq!(
|
||||
PathUri::try_from(path.clone()),
|
||||
path.to_path_uri(convention)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_legacy_paths_against_executor_context() {
|
||||
for (cwd, path, user_home_dir, expected) in [
|
||||
(
|
||||
"file:///workspace",
|
||||
"relative.txt",
|
||||
None,
|
||||
"file:///workspace/relative.txt",
|
||||
),
|
||||
(
|
||||
"file:///C:/workspace",
|
||||
"/Windows",
|
||||
None,
|
||||
"file:///C:/Windows",
|
||||
),
|
||||
(
|
||||
"file:///C:/workspace",
|
||||
"//server/share/file.txt",
|
||||
None,
|
||||
"file://server/share/file.txt",
|
||||
),
|
||||
(
|
||||
"file:///workspace",
|
||||
"~//notes",
|
||||
Some("file:///home/executor"),
|
||||
"file:///home/executor/notes",
|
||||
),
|
||||
(
|
||||
"file:///C:/workspace",
|
||||
r"~\\notes",
|
||||
Some("file:///C:/Users/executor"),
|
||||
"file:///C:/Users/executor/notes",
|
||||
),
|
||||
] {
|
||||
let cwd = PathUri::parse(cwd).expect("valid cwd");
|
||||
let user_home_dir = user_home_dir.map(|home| PathUri::parse(home).expect("valid home"));
|
||||
|
||||
assert_eq!(
|
||||
LegacyAppPathString::from_string(path).resolve_against(&cwd, user_home_dir.as_ref()),
|
||||
Ok(PathUri::parse(expected).expect("valid expected path")),
|
||||
"resolving {path:?} against {cwd}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_legacy_paths_without_executor_context() {
|
||||
let cwd = PathUri::parse("file:///workspace").expect("valid cwd");
|
||||
|
||||
assert_eq!(
|
||||
LegacyAppPathString::from_string(r"C:\\tmp")
|
||||
.resolve_against(&cwd, /*user_home_dir*/ None),
|
||||
Err(LegacyAppPathStringError::MismatchedConvention {
|
||||
path: r"C:\\tmp".to_string(),
|
||||
path_convention: PathConvention::Windows,
|
||||
cwd: cwd.to_string(),
|
||||
convention: PathConvention::Posix,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
LegacyAppPathString::from_string("~/secret")
|
||||
.resolve_against(&cwd, /*user_home_dir*/ None),
|
||||
Err(LegacyAppPathStringError::MissingHomeDirectory {
|
||||
path: "~/secret".to_string(),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ambiguous_absolute_api_paths_preserve_their_inferred_convention() {
|
||||
for (raw_path, convention) in [
|
||||
("/C:/secret", PathConvention::Posix),
|
||||
(r"\\localhost\share", PathConvention::Windows),
|
||||
] {
|
||||
let path = LegacyAppPathString::from_string(raw_path);
|
||||
let uri = PathUri::try_from(path.clone()).expect("absolute API path should convert");
|
||||
assert_eq!(uri.infer_path_convention(), Some(convention));
|
||||
assert_eq!(LegacyAppPathString::from(uri), path);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_native_api_path_to_inferred_absolute_path() {
|
||||
#[cfg(windows)]
|
||||
let raw_path = r"C:\workspace\file.rs";
|
||||
#[cfg(not(windows))]
|
||||
let raw_path = "/workspace/file.rs";
|
||||
let path = serde_json::from_value::<LegacyAppPathString>(serde_json::json!(raw_path))
|
||||
.expect("absolute API path should deserialize");
|
||||
let expected = AbsolutePathBuf::try_from(raw_path).expect("native absolute path should parse");
|
||||
|
||||
assert_eq!(
|
||||
AbsolutePathBuf::try_from(path.clone()),
|
||||
Ok(expected.clone())
|
||||
);
|
||||
assert_eq!(path.to_inferred_abs_path(), Some(expected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn foreign_absolute_syntax_deserializes_without_host_interpretation() {
|
||||
for (raw_path, convention) in [
|
||||
(r"C:\workspace\file.rs", PathConvention::Windows),
|
||||
("/workspace/file.rs", PathConvention::Posix),
|
||||
] {
|
||||
let path = serde_json::from_value::<LegacyAppPathString>(serde_json::json!(raw_path))
|
||||
.expect("foreign API path should deserialize");
|
||||
|
||||
assert_eq!(path.as_str(), raw_path);
|
||||
assert_eq!(path.infer_absolute_path_convention(), Some(convention));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_path_preserves_foreign_absolute_path_for_uri_conversion() {
|
||||
#[cfg(not(windows))]
|
||||
let (foreign_path, expected_uri) = (r"C:\Users\openai\share", "file:///C:/Users/openai/share");
|
||||
#[cfg(windows)]
|
||||
let (foreign_path, expected_uri) = ("/home/openai/share", "file:///home/openai/share");
|
||||
|
||||
let path: PathUri = LegacyAppPathString::from_path(std::path::Path::new(foreign_path))
|
||||
.try_into()
|
||||
.expect("foreign absolute path should convert");
|
||||
|
||||
assert_eq!(
|
||||
path,
|
||||
PathUri::parse(expected_uri).expect("valid expected URI")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_an_absolute_path_using_the_host_convention() {
|
||||
#[cfg(unix)]
|
||||
let native_path = "/workspace/a file.rs";
|
||||
#[cfg(windows)]
|
||||
let native_path = r"C:\workspace\a file.rs";
|
||||
let path = AbsolutePathBuf::from_absolute_path_checked(native_path)
|
||||
.expect("native path should be absolute");
|
||||
|
||||
assert_eq!(
|
||||
LegacyAppPathString::from(path),
|
||||
LegacyAppPathString(native_path.to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn renders_native_non_unicode_windows_fallback_lossily() {
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
|
||||
let native_path = std::path::PathBuf::from(std::ffi::OsString::from_wide(
|
||||
&r"C:\bad\"
|
||||
.encode_utf16()
|
||||
.chain([0xd800])
|
||||
.collect::<Vec<_>>(),
|
||||
));
|
||||
let native_path =
|
||||
AbsolutePathBuf::from_absolute_path_checked(native_path).expect("absolute native path");
|
||||
|
||||
assert_eq!(
|
||||
LegacyAppPathString::from_abs_path(&native_path),
|
||||
LegacyAppPathString(r"C:\bad\<5C>".to_string())
|
||||
);
|
||||
|
||||
let path = PathUri::from_abs_path(&native_path);
|
||||
|
||||
assert_eq!(
|
||||
LegacyAppPathString::from_path_uri(&path, PathConvention::Windows),
|
||||
Ok(LegacyAppPathString(r"C:\bad\<5C>".to_string()))
|
||||
);
|
||||
assert_eq!(
|
||||
LegacyAppPathString::from_path_uri(&path, PathConvention::Posix),
|
||||
Err(LegacyAppPathStringError::OpaqueFallback {
|
||||
path: path.to_string(),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serializes_and_deserializes_as_a_string() {
|
||||
let path = PathUri::parse("file:///workspace/src/lib.rs").expect("valid file URI");
|
||||
let rendered = LegacyAppPathString::from_path_uri(&path, PathConvention::Posix)
|
||||
.expect("POSIX URI should render");
|
||||
|
||||
let json = serde_json::to_string(&rendered).expect("rendered path should serialize");
|
||||
assert_eq!(json, r#""/workspace/src/lib.rs""#);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<LegacyAppPathString>(&json)
|
||||
.expect("rendered path should deserialize from a string"),
|
||||
rendered
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inferred_unc_paths_accept_forward_and_mixed_slashes_on_every_host() {
|
||||
for raw in [
|
||||
"//server/share/project",
|
||||
r"//server/share\project",
|
||||
r"/\server/share/project",
|
||||
r"\/server/share/project",
|
||||
r"\\server\share\project",
|
||||
"//wsl.localhost/Ubuntu/home/user/project",
|
||||
"//127.0.0.1/c$/project",
|
||||
"//LOCALHOST/c$/project",
|
||||
"//?/C:/project",
|
||||
] {
|
||||
let path = LegacyAppPathString::from_string(raw);
|
||||
let expected = path.to_path_uri(PathConvention::Windows).expect(raw);
|
||||
let inferred = path.to_inferred_path_uri().expect(raw);
|
||||
assert_eq!(
|
||||
(inferred.clone(), inferred.infer_path_convention()),
|
||||
(expected, Some(PathConvention::Windows)),
|
||||
"{raw}"
|
||||
);
|
||||
let serialized = serde_json::to_string(&inferred).expect("serialize URI");
|
||||
assert_eq!(
|
||||
serde_json::from_str::<PathUri>(&serialized).expect("deserialize URI"),
|
||||
inferred,
|
||||
"{raw}"
|
||||
);
|
||||
}
|
||||
let slash = LegacyAppPathString::from_string("//server/share/project")
|
||||
.to_inferred_path_uri()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
slash,
|
||||
PathUri::parse("file://server/share/project").unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn double_slash_posix_paths_require_an_explicit_convention() {
|
||||
let path = LegacyAppPathString::from_string("//server/share/project");
|
||||
assert_eq!(
|
||||
path.to_path_uri(PathConvention::Posix).unwrap(),
|
||||
PathUri::parse("file:///server/share/project").unwrap()
|
||||
);
|
||||
let cwd = PathUri::parse("file:///workspace").unwrap();
|
||||
assert!(matches!(
|
||||
path.resolve_against(&cwd, /*user_home_dir*/ None),
|
||||
Err(LegacyAppPathStringError::MismatchedConvention { .. })
|
||||
));
|
||||
for raw in ["//", "//server", "//server/", "///server/share"] {
|
||||
assert!(
|
||||
LegacyAppPathString::from_string(raw)
|
||||
.to_inferred_path_uri()
|
||||
.is_none(),
|
||||
"{raw}"
|
||||
);
|
||||
}
|
||||
}
|
||||
177
codex-rs/utils/path-uri/src/config_path.rs
Normal file
177
codex-rs/utils/path-uri/src/config_path.rs
Normal file
@@ -0,0 +1,177 @@
|
||||
//! Resolve filesystem denial paths with the existing URI parser and lexical join.
|
||||
//! Reject ambiguous or lossy representations before rendering security constraints.
|
||||
|
||||
use crate::LegacyAppPathString;
|
||||
use crate::LegacyAppPathStringError;
|
||||
use crate::PathConvention;
|
||||
use crate::PathUri;
|
||||
use crate::PathUriParseError;
|
||||
|
||||
impl PathUri {
|
||||
/// Resolves configuration text using only the supplied convention, base, and home.
|
||||
/// Home-relative inputs require a home; other relative inputs require a base.
|
||||
/// Used facts and results must have an unambiguous, lossless native spelling.
|
||||
pub fn resolve_config_path(
|
||||
input: &str,
|
||||
convention: PathConvention,
|
||||
base: Option<&Self>,
|
||||
user_home_dir: Option<&Self>,
|
||||
) -> Result<String, LegacyAppPathStringError> {
|
||||
Self::resolve_config_path_uri(input, convention, base, user_home_dir)?
|
||||
.to_config_path_string(convention)
|
||||
}
|
||||
|
||||
/// Resolves and validates configuration text as a URI using only supplied path facts.
|
||||
/// Normalizes trailing separators while preserving the path's root.
|
||||
pub fn resolve_config_path_uri(
|
||||
input: &str,
|
||||
convention: PathConvention,
|
||||
base: Option<&Self>,
|
||||
user_home_dir: Option<&Self>,
|
||||
) -> Result<Self, LegacyAppPathStringError> {
|
||||
Self::validate_config_path_text(input, convention)?;
|
||||
let path = LegacyAppPathString::from_string(input);
|
||||
let resolved = if convention.home_relative_suffix(input).is_some() {
|
||||
let home =
|
||||
user_home_dir.ok_or_else(|| LegacyAppPathStringError::MissingHomeDirectory {
|
||||
path: input.to_string(),
|
||||
})?;
|
||||
home.validate_config_path(convention)?;
|
||||
if contains_glob_metacharacter(input) {
|
||||
home.validate_glob_directory(convention)?;
|
||||
}
|
||||
path.resolve_against(home, Some(home))?
|
||||
} else {
|
||||
match path.to_path_uri(convention) {
|
||||
Ok(absolute) => absolute,
|
||||
Err(error) => {
|
||||
let base = base.ok_or(error)?;
|
||||
base.validate_config_path(convention)?;
|
||||
if contains_glob_metacharacter(input) {
|
||||
base.validate_glob_directory(convention)?;
|
||||
}
|
||||
path.resolve_against(base, /*user_home_dir*/ None)?
|
||||
}
|
||||
}
|
||||
};
|
||||
resolved.validate_config_path(convention)?;
|
||||
// Config paths historically omit trailing separators except at a root.
|
||||
Ok(resolved.join(".")?)
|
||||
}
|
||||
|
||||
/// Renders an already resolved configuration path with legacy root separators.
|
||||
/// Use [`Self::resolve_config_path_uri`] to validate and normalize config input first.
|
||||
pub fn to_config_path_string(
|
||||
&self,
|
||||
convention: PathConvention,
|
||||
) -> Result<String, LegacyAppPathStringError> {
|
||||
let mut rendered = LegacyAppPathString::from_path_uri(self, convention)?.into_string();
|
||||
if self.0.host_str().is_some() && self.parent().is_none() {
|
||||
rendered.push('\\');
|
||||
}
|
||||
Ok(rendered)
|
||||
}
|
||||
|
||||
/// Checks that a literal directory can be inserted into a glob unchanged.
|
||||
/// Rejects metacharacters instead of turning directory names into patterns.
|
||||
/// POSIX backslashes would escape the following pattern character.
|
||||
pub fn validate_glob_directory(
|
||||
&self,
|
||||
convention: PathConvention,
|
||||
) -> Result<(), LegacyAppPathStringError> {
|
||||
self.validate_config_path(convention)?;
|
||||
let path = LegacyAppPathString::from_path_uri(self, convention)?.into_string();
|
||||
if contains_glob_metacharacter(&path)
|
||||
|| convention == PathConvention::Posix && path.contains('\\')
|
||||
{
|
||||
return Err(LegacyAppPathStringError::UnsupportedConfigPath { path, convention });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Checks that a resolved configuration URI has a lossless native spelling
|
||||
/// in the owning executor's convention. Opaque and ambiguous paths fail.
|
||||
pub fn validate_config_path(
|
||||
&self,
|
||||
convention: PathConvention,
|
||||
) -> Result<(), LegacyAppPathStringError> {
|
||||
if self.infer_path_convention() != Some(convention) {
|
||||
return Err(LegacyAppPathStringError::IncompatibleConvention {
|
||||
path: self.to_string(),
|
||||
convention,
|
||||
});
|
||||
}
|
||||
let bytes = self.decoded_path_bytes();
|
||||
if self.lexical_depth().is_none()
|
||||
|| bytes.contains(&0)
|
||||
|| std::str::from_utf8(&bytes).is_err()
|
||||
{
|
||||
return Err(PathUriParseError::InvalidFileUriPath {
|
||||
path: self.to_string(),
|
||||
}
|
||||
.into());
|
||||
}
|
||||
Self::validate_config_path_text(
|
||||
LegacyAppPathString::from_path_uri(self, convention)?.as_str(),
|
||||
convention,
|
||||
)
|
||||
}
|
||||
|
||||
/// Validates native configuration text without resolving paths or glob syntax.
|
||||
/// Rejects spellings that could change targets during later native conversion.
|
||||
pub fn validate_config_path_text(
|
||||
input: &str,
|
||||
convention: PathConvention,
|
||||
) -> Result<(), LegacyAppPathStringError> {
|
||||
let namespace_alias = codex_utils_absolute_path::normalize_windows_device_path(input);
|
||||
let native_input = namespace_alias.as_deref().unwrap_or(input);
|
||||
let has_windows_component_colon = convention == PathConvention::Windows
|
||||
&& convention
|
||||
.path_segments(native_input)
|
||||
.enumerate()
|
||||
.any(|(index, segment)| {
|
||||
let segment = if index == 0
|
||||
&& segment
|
||||
.as_bytes()
|
||||
.first()
|
||||
.is_some_and(u8::is_ascii_alphabetic)
|
||||
&& segment.as_bytes().get(/*index*/ 1) == Some(&b':')
|
||||
{
|
||||
&segment[2..]
|
||||
} else {
|
||||
segment
|
||||
};
|
||||
segment.contains(':')
|
||||
});
|
||||
let mixed_home_separators = convention == PathConvention::Windows
|
||||
&& convention
|
||||
.home_relative_suffix(input)
|
||||
.is_some_and(|suffix| {
|
||||
suffix.starts_with('/') && suffix.trim_start_matches('/').starts_with('\\')
|
||||
|| suffix.starts_with('\\')
|
||||
&& suffix.trim_start_matches('\\').starts_with('/')
|
||||
});
|
||||
let bare_windows_drive = convention == PathConvention::Windows
|
||||
&& matches!(native_input.as_bytes(), [drive, b':'] if drive.is_ascii_alphabetic());
|
||||
if input.contains('\0')
|
||||
|| has_windows_component_colon
|
||||
|| mixed_home_separators
|
||||
|| bare_windows_drive
|
||||
{
|
||||
return Err(LegacyAppPathStringError::UnsupportedConfigPath {
|
||||
path: input.to_string(),
|
||||
convention,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn contains_glob_metacharacter(path: &str) -> bool {
|
||||
path.chars()
|
||||
.any(|character| matches!(character, '*' | '?' | '[' | ']' | '{' | '}'))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "config_path_tests.rs"]
|
||||
mod tests;
|
||||
228
codex-rs/utils/path-uri/src/config_path_tests.rs
Normal file
228
codex-rs/utils/path-uri/src/config_path_tests.rs
Normal file
@@ -0,0 +1,228 @@
|
||||
//! The configuration boundary shares URI resolution and rejects lossy denials.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn configuration_paths_resolve_with_the_supplied_platform_and_home() {
|
||||
for (convention, base, home, input, expected, expected_uri) in [
|
||||
(
|
||||
PathConvention::Posix,
|
||||
"file:///work/project",
|
||||
"file:///home/user",
|
||||
"~/a b/雪%/",
|
||||
"/home/user/a b/雪%",
|
||||
"file:///home/user/a%20b/%E9%9B%AA%25",
|
||||
),
|
||||
(
|
||||
PathConvention::Posix,
|
||||
"file:///work/project",
|
||||
"file:///home/user",
|
||||
"/",
|
||||
"/",
|
||||
"file:///",
|
||||
),
|
||||
(
|
||||
PathConvention::Windows,
|
||||
"file:///C:/work/project",
|
||||
"file:///C:/Users/user",
|
||||
r"..\private\",
|
||||
r"C:\work\private",
|
||||
"file:///C:/work/private",
|
||||
),
|
||||
(
|
||||
PathConvention::Windows,
|
||||
"file:///C:/work/project",
|
||||
"file:///C:/Users/user",
|
||||
r"d:\private\*.env\",
|
||||
r"D:\private\*.env",
|
||||
"file:///D:/private/*.env",
|
||||
),
|
||||
(
|
||||
PathConvention::Windows,
|
||||
"file:///C:/work/project",
|
||||
"file:///C:/Users/user",
|
||||
r"D:\",
|
||||
r"D:\",
|
||||
"file:///D:",
|
||||
),
|
||||
(
|
||||
PathConvention::Windows,
|
||||
"file:///C:/work/project",
|
||||
"file:///C:/Users/user",
|
||||
r"~\a b\雪%\",
|
||||
r"C:\Users\user\a b\雪%",
|
||||
"file:///C:/Users/user/a%20b/%E9%9B%AA%25",
|
||||
),
|
||||
(
|
||||
PathConvention::Windows,
|
||||
"file:///C:/work",
|
||||
"file:///C:/Users/user",
|
||||
r"\\SERVER\Share\private\*.env\",
|
||||
r"\\server\Share\private\*.env",
|
||||
"file://server/Share/private/*.env",
|
||||
),
|
||||
(
|
||||
PathConvention::Windows,
|
||||
"file:///C:/work",
|
||||
"file:///C:/Users/user",
|
||||
r"\\server\share",
|
||||
r"\\server\share\",
|
||||
"file://server/share",
|
||||
),
|
||||
] {
|
||||
let base = PathUri::parse(base).unwrap();
|
||||
let home = PathUri::parse(home).unwrap();
|
||||
assert_eq!(
|
||||
PathUri::resolve_config_path_uri(input, convention, Some(&base), Some(&home)),
|
||||
Ok(PathUri::parse(expected_uri).unwrap()),
|
||||
"{input:?}",
|
||||
);
|
||||
assert_eq!(
|
||||
PathUri::resolve_config_path(input, convention, Some(&base), Some(&home)),
|
||||
Ok(expected.to_string()),
|
||||
"{input:?}",
|
||||
);
|
||||
if !input.starts_with('.') && !input.starts_with('\\') || input.starts_with(r"\\") {
|
||||
assert_eq!(
|
||||
PathUri::resolve_config_path(input, convention, /*base*/ None, Some(&home)),
|
||||
Ok(expected.to_string()),
|
||||
"without base: {input:?}",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configuration_paths_reject_ambiguous_or_lossy_denials() {
|
||||
for (convention, base) in [
|
||||
(PathConvention::Posix, "file:///base/%FF"),
|
||||
(PathConvention::Posix, "file:///base/encoded%2Fname"),
|
||||
(PathConvention::Posix, "file:///C:/base"),
|
||||
(PathConvention::Windows, "file:///base"),
|
||||
(PathConvention::Windows, "file:///C:/encoded%5Cname"),
|
||||
(PathConvention::Windows, "file:///C:/%FF"),
|
||||
(PathConvention::Windows, "file:///C:/base/a:b"),
|
||||
] {
|
||||
let base = PathUri::parse(base).unwrap();
|
||||
assert!(base.validate_config_path(convention).is_err());
|
||||
}
|
||||
let base = PathUri::parse("file:///base").unwrap();
|
||||
let opaque = PathUri::from_opaque_path_bytes(b"/base");
|
||||
for input in ["nul\0", "nul\0/../private", "/nul\0", "~/private"] {
|
||||
assert!(
|
||||
PathUri::resolve_config_path(
|
||||
input,
|
||||
PathConvention::Posix,
|
||||
Some(&base),
|
||||
/*user_home_dir*/ None
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
PathUri::resolve_config_path(
|
||||
"child",
|
||||
PathConvention::Posix,
|
||||
Some(&opaque),
|
||||
/*user_home_dir*/ None
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
for input in [
|
||||
r"\\server\.\private",
|
||||
r"\\server\..\private",
|
||||
r"\\.\COM1",
|
||||
r"C:\private\file:stream",
|
||||
r"C:\base\a:b\..\private",
|
||||
] {
|
||||
assert!(
|
||||
PathUri::resolve_config_path(
|
||||
input,
|
||||
PathConvention::Windows,
|
||||
/*base*/ None,
|
||||
/*user_home_dir*/ None
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
let home = PathUri::parse("file:///C:/Users/user").unwrap();
|
||||
for input in [
|
||||
"C:",
|
||||
r"~/\private",
|
||||
r"~\/private",
|
||||
r"\\0x7f000001\share\private",
|
||||
r"\\bücher\share\private",
|
||||
] {
|
||||
assert!(
|
||||
PathUri::resolve_config_path(input, PathConvention::Windows, Some(&home), Some(&home))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
// Unused facts cannot change an already absolute path.
|
||||
assert_eq!(
|
||||
PathUri::resolve_config_path(
|
||||
"/private",
|
||||
PathConvention::Posix,
|
||||
Some(&opaque),
|
||||
Some(&opaque)
|
||||
),
|
||||
Ok("/private".to_string()),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glob_resolution_rejects_metacharacters_in_used_directory_facts() {
|
||||
for (convention, prefix, separator) in [
|
||||
(PathConvention::Posix, "/home/", "/"),
|
||||
(PathConvention::Windows, r"C:\Users\", r"\"),
|
||||
] {
|
||||
let clean = LegacyAppPathString::from_string(format!("{prefix}sam"))
|
||||
.to_path_uri(convention)
|
||||
.unwrap();
|
||||
for name in ["sam[1]", "sam{1,2}"] {
|
||||
let directory = LegacyAppPathString::from_string(format!("{prefix}{name}"))
|
||||
.to_path_uri(convention)
|
||||
.unwrap();
|
||||
// The directory remains valid as a literal path, and unused facts
|
||||
// cannot reject an absolute pattern supplied by the user.
|
||||
let absolute = format!("{prefix}ordinary{separator}*.key");
|
||||
let literal = format!("{prefix}{name}{separator}private{separator}key");
|
||||
for (input, base, home, expected) in [
|
||||
("private/*.key", &directory, None, None),
|
||||
("~/private/*.key", &clean, Some(&directory), None),
|
||||
("private/key", &directory, None, Some(literal.as_str())),
|
||||
(
|
||||
absolute.as_str(),
|
||||
&directory,
|
||||
Some(&directory),
|
||||
Some(absolute.as_str()),
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
PathUri::resolve_config_path(input, convention, Some(base), home)
|
||||
.ok()
|
||||
.as_deref(),
|
||||
expected,
|
||||
"{convention:?}: {name}: {input}",
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
PathUri::resolve_config_path("~/private/*.key", convention, Some(&clean), Some(&clean),),
|
||||
Ok(format!("{prefix}sam{separator}private{separator}*.key")),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glob_directory_validation_rejects_posix_escape_characters() {
|
||||
let directory = LegacyAppPathString::from_string(r"/home/sam\name")
|
||||
.to_path_uri(PathConvention::Posix)
|
||||
.unwrap();
|
||||
assert!(
|
||||
directory
|
||||
.validate_glob_directory(PathConvention::Posix)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
1044
codex-rs/utils/path-uri/src/lib.rs
Normal file
1044
codex-rs/utils/path-uri/src/lib.rs
Normal file
File diff suppressed because it is too large
Load Diff
51
codex-rs/utils/path-uri/src/native_path_bytes.rs
Normal file
51
codex-rs/utils/path-uri/src/native_path_bytes.rs
Normal file
@@ -0,0 +1,51 @@
|
||||
use crate::PathConvention;
|
||||
use crate::PathUri;
|
||||
use crate::PathUriParseError;
|
||||
|
||||
impl PathUri {
|
||||
/// Resolves a native path stored as bytes, using this URI's path convention.
|
||||
///
|
||||
/// UTF-8 paths follow [`Self::join`]. Non-UTF-8 POSIX names are preserved
|
||||
/// losslessly, including when the filesystem is on another host. Invalid
|
||||
/// UTF-8 Windows paths, null bytes, and opaque base URIs are rejected.
|
||||
pub fn join_native_bytes(&self, path: &[u8]) -> Result<Self, PathUriParseError> {
|
||||
if let Ok(path) = std::str::from_utf8(path) {
|
||||
return self.join(path);
|
||||
}
|
||||
if self.infer_path_convention() != Some(PathConvention::Posix)
|
||||
|| self.opaque_fallback_bytes().is_some()
|
||||
|| path.contains(&0)
|
||||
{
|
||||
return Err(PathUriParseError::InvalidFileUriPath {
|
||||
path: self.to_string(),
|
||||
});
|
||||
}
|
||||
let mut segments = if path.starts_with(b"/") {
|
||||
Vec::new()
|
||||
} else {
|
||||
self.encoded_path()
|
||||
.split('/')
|
||||
.filter(|segment| !segment.is_empty())
|
||||
.map(str::to_owned)
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
for component in path.split(|byte| *byte == b'/') {
|
||||
match component {
|
||||
b"" | b"." => {}
|
||||
b".." => {
|
||||
segments.pop();
|
||||
}
|
||||
component => segments.push(urlencoding::encode_binary(component).into_owned()),
|
||||
}
|
||||
}
|
||||
let mut url = self.to_url();
|
||||
url.set_path(&format!("/{}", segments.join("/")));
|
||||
let uri = Self::try_from(url)?;
|
||||
if uri.infer_path_convention() != Some(PathConvention::Posix) {
|
||||
return Err(PathUriParseError::InvalidFileUriPath {
|
||||
path: uri.to_string(),
|
||||
});
|
||||
}
|
||||
Ok(uri)
|
||||
}
|
||||
}
|
||||
51
codex-rs/utils/path-uri/src/platform.rs
Normal file
51
codex-rs/utils/path-uri/src/platform.rs
Normal file
@@ -0,0 +1,51 @@
|
||||
//! Platform identity and its path convention, independent of the resolving host.
|
||||
|
||||
use crate::PathConvention;
|
||||
|
||||
/// Operating system whose paths and execution configuration are being resolved.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Platform {
|
||||
Linux,
|
||||
Macos,
|
||||
Windows,
|
||||
/// Missing or unrecognized platform metadata carries no path convention.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
impl Platform {
|
||||
/// Read platform metadata without substituting the current host's platform.
|
||||
pub fn from_platform_os(platform_os: Option<&str>) -> Self {
|
||||
match platform_os {
|
||||
Some("linux") => Self::Linux,
|
||||
Some("macos") => Self::Macos,
|
||||
Some("windows") => Self::Windows,
|
||||
Some(_) | None => Self::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the platform of the current process.
|
||||
pub const fn native() -> Self {
|
||||
if cfg!(target_os = "linux") {
|
||||
Self::Linux
|
||||
} else if cfg!(target_os = "macos") {
|
||||
Self::Macos
|
||||
} else if cfg!(target_os = "windows") {
|
||||
Self::Windows
|
||||
} else {
|
||||
Self::Unknown
|
||||
}
|
||||
}
|
||||
|
||||
/// Derive path grammar from platform identity while preserving unknown metadata.
|
||||
pub const fn path_convention(self) -> Option<PathConvention> {
|
||||
match self {
|
||||
Self::Linux | Self::Macos => Some(PathConvention::Posix),
|
||||
Self::Windows => Some(PathConvention::Windows),
|
||||
Self::Unknown => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "platform_tests.rs"]
|
||||
mod tests;
|
||||
43
codex-rs/utils/path-uri/src/platform_tests.rs
Normal file
43
codex-rs/utils/path-uri/src/platform_tests.rs
Normal file
@@ -0,0 +1,43 @@
|
||||
//! Coverage for platform metadata and platform-derived path conventions.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn platform_metadata_preserves_missing_and_unrecognized_values() {
|
||||
for (metadata, expected) in [
|
||||
(Some("linux"), Platform::Linux),
|
||||
(Some("macos"), Platform::Macos),
|
||||
(Some("windows"), Platform::Windows),
|
||||
(None, Platform::Unknown),
|
||||
(Some("freebsd"), Platform::Unknown),
|
||||
(Some("Windows"), Platform::Unknown),
|
||||
(Some(""), Platform::Unknown),
|
||||
] {
|
||||
assert_eq!(
|
||||
Platform::from_platform_os(metadata),
|
||||
expected,
|
||||
"{metadata:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_convention_is_derived_from_platform() {
|
||||
for (platform, expected) in [
|
||||
(Platform::Linux, Some(PathConvention::Posix)),
|
||||
(Platform::Macos, Some(PathConvention::Posix)),
|
||||
(Platform::Windows, Some(PathConvention::Windows)),
|
||||
(Platform::Unknown, None),
|
||||
] {
|
||||
assert_eq!(platform.path_convention(), expected, "{platform:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_platform_matches_current_process_metadata() {
|
||||
assert_eq!(
|
||||
Platform::native(),
|
||||
Platform::from_platform_os(Some(std::env::consts::OS)),
|
||||
);
|
||||
}
|
||||
1427
codex-rs/utils/path-uri/src/tests.rs
Normal file
1427
codex-rs/utils/path-uri/src/tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user