|
7 | 7 |
|
8 | 8 | use deno_error::JsError; |
9 | 9 | use std::borrow::Cow; |
| 10 | +use std::ffi::OsString; |
10 | 11 | use std::path::Component; |
11 | 12 | use std::path::Path; |
12 | 13 | use std::path::PathBuf; |
@@ -221,10 +222,48 @@ pub fn normalize_path(path: Cow<Path>) -> Cow<Path> { |
221 | 222 | if should_normalize(&path) { |
222 | 223 | Cow::Owned(inner(&path)) |
223 | 224 | } else { |
224 | | - path |
| 225 | + ensure_no_trailing_slash(path) |
225 | 226 | } |
226 | 227 | } |
227 | 228 |
|
| 229 | +fn ensure_no_trailing_slash(path: Cow<Path>) -> Cow<Path> { |
| 230 | + let is_windows = sys_traits::impls::is_windows(); |
| 231 | + let mut bytes = path.as_os_str().as_encoded_bytes(); |
| 232 | + let start_len = bytes.len(); |
| 233 | + while bytes.len() > 1 |
| 234 | + && (is_windows && bytes.ends_with(b"\\") || bytes.ends_with(b"/")) |
| 235 | + { |
| 236 | + bytes = &bytes[..bytes.len() - 1]; |
| 237 | + } |
| 238 | + |
| 239 | + if bytes.len() == start_len |
| 240 | + || bytes.ends_with(b".") |
| 241 | + || is_windows && bytes.ends_with(b":") |
| 242 | + { |
| 243 | + return path; |
| 244 | + } |
| 245 | + |
| 246 | + let new_len = bytes.len(); |
| 247 | + let os_string = path.into_owned().into_os_string(); |
| 248 | + Cow::Owned(PathBuf::from(truncate_os_string(os_string, new_len))) |
| 249 | +} |
| 250 | + |
| 251 | +#[cfg(unix)] |
| 252 | +fn truncate_os_string(mut os: OsString, n: usize) -> OsString { |
| 253 | + use std::os::unix::ffi::OsStringExt; |
| 254 | + let mut bytes = os.into_vec(); |
| 255 | + bytes.truncate(n); |
| 256 | + OsString::from_vec(bytes) |
| 257 | +} |
| 258 | + |
| 259 | +#[cfg(windows)] |
| 260 | +fn truncate_os_string(os: OsString, n: usize) -> OsString { |
| 261 | + use std::os::windows::ffi::OsStrExt; |
| 262 | + use std::os::windows::ffi::OsStringExt; |
| 263 | + let wide: Vec<u16> = os.encode_wide().take(n).collect(); |
| 264 | + OsString::from_wide(&wide) |
| 265 | +} |
| 266 | + |
228 | 267 | #[derive(Debug, Clone, Error, deno_error::JsError, PartialEq, Eq)] |
229 | 268 | #[class(uri)] |
230 | 269 | #[error("Could not convert path to URL.\n Path: {0}")] |
|
0 commit comments