2024-01-01 19:58:21 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2020-12-13 18:45:53 +00:00
|
|
|
|
2021-11-16 14:02:28 +00:00
|
|
|
use deno_core::anyhow::Context;
|
2020-12-13 18:45:53 +00:00
|
|
|
use deno_core::error::AnyError;
|
2024-09-28 11:55:01 +00:00
|
|
|
use deno_path_util::normalize_path;
|
2023-01-15 04:18:58 +00:00
|
|
|
use std::path::Path;
|
|
|
|
use std::path::PathBuf;
|
2020-12-13 18:45:53 +00:00
|
|
|
|
2022-08-27 15:20:05 +00:00
|
|
|
#[inline]
|
2020-12-13 18:45:53 +00:00
|
|
|
pub fn resolve_from_cwd(path: &Path) -> Result<PathBuf, AnyError> {
|
2022-08-27 15:20:05 +00:00
|
|
|
if path.is_absolute() {
|
|
|
|
Ok(normalize_path(path))
|
2020-12-13 18:45:53 +00:00
|
|
|
} else {
|
2023-05-11 00:06:59 +00:00
|
|
|
#[allow(clippy::disallowed_methods)]
|
|
|
|
let cwd = std::env::current_dir()
|
|
|
|
.context("Failed to get current working directory")?;
|
2022-12-17 22:20:15 +00:00
|
|
|
Ok(normalize_path(cwd.join(path)))
|
2022-08-27 15:20:05 +00:00
|
|
|
}
|
2020-12-13 18:45:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
|
2023-05-11 00:06:59 +00:00
|
|
|
fn current_dir() -> PathBuf {
|
|
|
|
#[allow(clippy::disallowed_methods)]
|
|
|
|
std::env::current_dir().unwrap()
|
|
|
|
}
|
|
|
|
|
2020-12-13 18:45:53 +00:00
|
|
|
#[test]
|
|
|
|
fn resolve_from_cwd_child() {
|
2023-05-11 00:06:59 +00:00
|
|
|
let cwd = current_dir();
|
2020-12-13 18:45:53 +00:00
|
|
|
assert_eq!(resolve_from_cwd(Path::new("a")).unwrap(), cwd.join("a"));
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn resolve_from_cwd_dot() {
|
2023-05-11 00:06:59 +00:00
|
|
|
let cwd = current_dir();
|
2020-12-13 18:45:53 +00:00
|
|
|
assert_eq!(resolve_from_cwd(Path::new(".")).unwrap(), cwd);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn resolve_from_cwd_parent() {
|
2023-05-11 00:06:59 +00:00
|
|
|
let cwd = current_dir();
|
2020-12-13 18:45:53 +00:00
|
|
|
assert_eq!(resolve_from_cwd(Path::new("a/..")).unwrap(), cwd);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_normalize_path() {
|
|
|
|
assert_eq!(normalize_path(Path::new("a/../b")), PathBuf::from("b"));
|
|
|
|
assert_eq!(normalize_path(Path::new("a/./b/")), PathBuf::from("a/b/"));
|
|
|
|
assert_eq!(
|
|
|
|
normalize_path(Path::new("a/./b/../c")),
|
|
|
|
PathBuf::from("a/c")
|
|
|
|
);
|
|
|
|
|
|
|
|
if cfg!(windows) {
|
|
|
|
assert_eq!(
|
|
|
|
normalize_path(Path::new("C:\\a\\.\\b\\..\\c")),
|
|
|
|
PathBuf::from("C:\\a\\c")
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn resolve_from_cwd_absolute() {
|
2023-04-12 23:45:53 +00:00
|
|
|
let expected = Path::new("a");
|
2023-05-11 00:06:59 +00:00
|
|
|
let cwd = current_dir();
|
2023-04-12 23:45:53 +00:00
|
|
|
let absolute_expected = cwd.join(expected);
|
|
|
|
assert_eq!(resolve_from_cwd(expected).unwrap(), absolute_expected);
|
2020-12-13 18:45:53 +00:00
|
|
|
}
|
|
|
|
}
|