deno_runtime/
fs_util.rs

1// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
2
3use deno_core::anyhow::Context;
4use deno_core::error::AnyError;
5use deno_path_util::normalize_path;
6use std::path::Path;
7use std::path::PathBuf;
8
9#[inline]
10pub fn resolve_from_cwd(path: &Path) -> Result<PathBuf, AnyError> {
11  if path.is_absolute() {
12    Ok(normalize_path(path))
13  } else {
14    #[allow(clippy::disallowed_methods)]
15    let cwd = std::env::current_dir()
16      .context("Failed to get current working directory")?;
17    Ok(normalize_path(cwd.join(path)))
18  }
19}
20
21#[cfg(test)]
22mod tests {
23  use super::*;
24
25  fn current_dir() -> PathBuf {
26    #[allow(clippy::disallowed_methods)]
27    std::env::current_dir().unwrap()
28  }
29
30  #[test]
31  fn resolve_from_cwd_child() {
32    let cwd = current_dir();
33    assert_eq!(resolve_from_cwd(Path::new("a")).unwrap(), cwd.join("a"));
34  }
35
36  #[test]
37  fn resolve_from_cwd_dot() {
38    let cwd = current_dir();
39    assert_eq!(resolve_from_cwd(Path::new(".")).unwrap(), cwd);
40  }
41
42  #[test]
43  fn resolve_from_cwd_parent() {
44    let cwd = current_dir();
45    assert_eq!(resolve_from_cwd(Path::new("a/..")).unwrap(), cwd);
46  }
47
48  #[test]
49  fn test_normalize_path() {
50    assert_eq!(normalize_path(Path::new("a/../b")), PathBuf::from("b"));
51    assert_eq!(normalize_path(Path::new("a/./b/")), PathBuf::from("a/b/"));
52    assert_eq!(
53      normalize_path(Path::new("a/./b/../c")),
54      PathBuf::from("a/c")
55    );
56
57    if cfg!(windows) {
58      assert_eq!(
59        normalize_path(Path::new("C:\\a\\.\\b\\..\\c")),
60        PathBuf::from("C:\\a\\c")
61      );
62    }
63  }
64
65  #[test]
66  fn resolve_from_cwd_absolute() {
67    let expected = Path::new("a");
68    let cwd = current_dir();
69    let absolute_expected = cwd.join(expected);
70    assert_eq!(resolve_from_cwd(expected).unwrap(), absolute_expected);
71  }
72}