rolldown_utils/
node_path.rs1use std::{
2 borrow::Cow,
3 path::{Path, PathBuf},
4};
5
6use rolldown_std_utils::PathExt;
7
8use crate::concat_string;
9
10pub fn node_style_absolute<'a>(path: &'a Path, cwd: &Path) -> Option<Cow<'a, Path>> {
28 if path.is_absolute() {
29 return Some(Cow::Borrowed(path));
30 }
31 if !path.has_root() {
32 return None;
33 }
34 let std::path::Component::Prefix(prefix) = cwd.components().next()? else {
35 return None;
36 };
37 let path = path.expect_to_str();
38 let glued = match prefix.kind() {
43 std::path::Prefix::Disk(drive) | std::path::Prefix::VerbatimDisk(drive) => {
44 concat_string!(char::from(drive).to_string(), ":", path)
45 }
46 std::path::Prefix::UNC(server, share) | std::path::Prefix::VerbatimUNC(server, share) => {
47 concat_string!(r"\\", server.to_str()?, r"\", share.to_str()?, path)
48 }
49 _ => return None,
50 };
51 Some(Cow::Owned(PathBuf::from(glued)))
52}
53
54#[test]
55fn test_node_style_absolute() {
56 assert_eq!(node_style_absolute(Path::new("src/a.js"), Path::new("/cwd")), None);
58 assert_eq!(node_style_absolute(Path::new("react"), Path::new("/cwd")), None);
59
60 #[cfg(not(target_os = "windows"))]
62 {
63 let p = Path::new("/favicon");
65 assert!(matches!(node_style_absolute(p, Path::new("/cwd")), Some(Cow::Borrowed(_))));
66 }
67
68 #[cfg(target_os = "windows")]
69 {
70 let p = Path::new(r"E:\proj\a.js");
71 assert!(matches!(node_style_absolute(p, Path::new(r"C:\cwd")), Some(Cow::Borrowed(_))));
72
73 assert_eq!(
75 node_style_absolute(Path::new("/favicon"), Path::new(r"E:\proj")).as_deref(),
76 Some(Path::new("E:/favicon"))
77 );
78 assert_eq!(
79 node_style_absolute(Path::new(r"\a\b"), Path::new(r"C:\x")).as_deref(),
80 Some(Path::new(r"C:\a\b"))
81 );
82
83 assert_eq!(
86 node_style_absolute(Path::new("/favicon"), Path::new(r"\\server\share\project")).as_deref(),
87 Some(Path::new(r"\\server\share/favicon"))
88 );
89 assert_eq!(
90 node_style_absolute(Path::new(r"\favicon"), Path::new(r"\\server\share\project")).as_deref(),
91 Some(Path::new(r"\\server\share\favicon"))
92 );
93
94 assert_eq!(node_style_absolute(Path::new("/favicon"), Path::new("relative")), None);
96 }
97}