Skip to content

Commit 8e51321

Browse files
committed
Fix minor formatting issue with as_posix.
Previously, it would double the `//root` path, since it would add a `/` for the root, and an additional one for the first path afterwards. Also added unittests to ensure `as_posix` works as expected with drive letters and normal paths.
1 parent 0741969 commit 8e51321

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

src/file.rs

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ pub trait PathExt {
2828
}
2929

3030
fn push_posix_path(path: &mut String, component: &str) {
31-
if !path.is_empty() {
31+
if !path.is_empty() && path != "/" {
3232
path.push('/');
3333
}
3434
path.push_str(component);
@@ -163,6 +163,35 @@ pub fn write_file(path: impl AsRef<Path>, overwrite: bool) -> Result<File> {
163163
#[cfg(test)]
164164
mod tests {
165165
use super::*;
166+
use std::fmt::Debug;
167+
168+
fn result_eq<T: PartialEq + Eq + Debug>(x: Result<T>, y: Result<T>) {
169+
match (x, y) {
170+
(Ok(x), Ok(y)) => assert_eq!(x, y),
171+
(x, y) => panic!("assertion failed: `(left == right)`\nleft: {x:?}\nright: {y:?}"),
172+
}
173+
}
174+
175+
#[test]
176+
fn as_posix() {
177+
result_eq(Path::new(".").join("..").as_posix(), Ok("./..".to_string()));
178+
result_eq(Path::new(".").join("/").as_posix(), Ok("/".to_string()));
179+
result_eq(
180+
Path::new("foo").join("bar").as_posix(),
181+
Ok("foo/bar".to_string()),
182+
);
183+
result_eq(
184+
Path::new("/foo").join("bar").as_posix(),
185+
Ok("/foo/bar".to_string()),
186+
);
187+
}
188+
189+
#[test]
190+
#[cfg(target_family = "windows")]
191+
fn as_posix_prefix() {
192+
assert_eq!(Path::new("C:").join(".."), Path::new("C:.."));
193+
assert!(Path::new("C:").join("..").as_posix().is_err());
194+
}
166195

167196
#[test]
168197
#[cfg(target_family = "windows")]

0 commit comments

Comments
 (0)