Skip to content

Commit 1a07088

Browse files
committed
ensure no trailing slashes
1 parent bd988f2 commit 1a07088

1 file changed

Lines changed: 40 additions & 1 deletion

File tree

src/lib.rs

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
use deno_error::JsError;
99
use std::borrow::Cow;
10+
use std::ffi::OsString;
1011
use std::path::Component;
1112
use std::path::Path;
1213
use std::path::PathBuf;
@@ -221,10 +222,48 @@ pub fn normalize_path(path: Cow<Path>) -> Cow<Path> {
221222
if should_normalize(&path) {
222223
Cow::Owned(inner(&path))
223224
} else {
224-
path
225+
ensure_no_trailing_slash(path)
225226
}
226227
}
227228

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+
228267
#[derive(Debug, Clone, Error, deno_error::JsError, PartialEq, Eq)]
229268
#[class(uri)]
230269
#[error("Could not convert path to URL.\n Path: {0}")]

0 commit comments

Comments
 (0)