1use std::{
6 borrow::Cow,
7 path::{Component, Path, PathBuf, MAIN_SEPARATOR, MAIN_SEPARATOR_STR},
8};
9
10use crate::utils::module::{export_default, ModuleInfo};
11use rquickjs::{
12 function::Opt,
13 module::{Declarations, Exports, ModuleDef},
14 prelude::{Func, Rest},
15 Ctx, Object, Result,
16};
17
18pub struct PathModule;
19
20#[cfg(windows)]
21const DELIMITER: char = ';';
22#[cfg(not(windows))]
23const DELIMITER: char = ':';
24
25#[cfg(windows)]
26pub const CURRENT_DIR_STR: &str = ".\\";
27
28#[cfg(windows)]
29const FORWARD_SLASH_STR: &str = "/";
30
31#[cfg(not(windows))]
32pub const CURRENT_DIR_STR: &str = "./";
33
34#[cfg(windows)]
35use memchr::{memchr, memchr2, memchr2_iter};
36
37#[cfg(windows)]
38pub fn replace_backslash(path: impl Into<String>) -> String {
39 let mut path = path.into();
40 let bytes = unsafe { path.as_bytes_mut() };
41
42 let mut start = 0;
43 while let Some(pos) = memchr(b'\\', &bytes[start..]) {
44 bytes[start + pos] = b'/';
45 start += pos + 1;
46 }
47 path
48}
49
50#[cfg(not(windows))]
51pub fn replace_backslash(path: impl Into<String>) -> String {
52 path.into().replace('\\', "/")
53}
54
55#[cfg(windows)]
56fn find_next_separator(s: &str) -> Option<usize> {
57 memchr2(b'\\', b'/', s.as_bytes())
58}
59
60#[cfg(not(windows))]
61fn find_next_separator(s: &str) -> Option<usize> {
62 s.find(MAIN_SEPARATOR)
63}
64
65#[cfg(windows)]
66fn find_last_sep(path: &str) -> Option<usize> {
67 memchr2_iter(b'\\', b'/', path.as_bytes()).next_back()
68}
69
70#[cfg(not(windows))]
71fn find_last_sep(path: &str) -> Option<usize> {
72 path.rfind(MAIN_SEPARATOR)
73}
74
75pub fn dirname<'a, P: Into<Cow<'a, str>>>(path: P) -> String {
76 let path = path.into();
77 let len = path.len();
78
79 if len == 0 {
80 return ".".into();
81 }
82
83 let bytes = path.as_bytes();
84
85 #[cfg(windows)]
86 {
87 if len == 1 {
88 return if is_sep(bytes[0]) {
89 path.into_owned()
90 } else {
91 ".".to_string()
92 };
93 }
94
95 let (root_end, offset) = if is_sep(bytes[0]) {
97 if is_sep(bytes[1]) {
98 parse_unc_root(bytes, len).unwrap_or((1, 1))
100 } else {
101 (1, 1)
102 }
103 } else if bytes.len() > 1 && is_drive_letter(bytes[0]) && bytes[1] == b':' {
104 let r = if len > 2 && is_sep(bytes[2]) { 3 } else { 2 };
105 (r, r)
106 } else {
107 (0, 0)
108 };
109
110 let end = find_dirname_end(bytes, offset);
112
113 match end {
114 Some(e) => &path[..e],
115 None if root_end > 0 => &path[..root_end],
116 None => ".",
117 }
118 .into()
119 }
120
121 #[cfg(not(windows))]
122 {
123 if len == 1 {
124 return if bytes[0] == b'/' {
125 path.into_owned()
126 } else {
127 ".".into()
128 };
129 }
130
131 let has_root = bytes[0] == b'/';
132 let end = find_dirname_end(bytes, 1);
133
134 match end {
135 Some(e) if has_root && e == 1 => "//",
136 Some(e) => &path[..e],
137 None if has_root => "/",
138 None => ".",
139 }
140 .into()
141 }
142}
143
144#[cfg(windows)]
145fn is_sep(c: u8) -> bool {
146 c == b'/' || c == b'\\'
147}
148
149#[cfg(windows)]
150fn is_drive_letter(c: u8) -> bool {
151 c.is_ascii_alphabetic()
152}
153
154#[cfg(windows)]
155fn parse_unc_root(bytes: &[u8], len: usize) -> Option<(usize, usize)> {
156 let mut j = 2;
157 while j < len && !is_sep(bytes[j]) {
159 j += 1;
160 }
161 if j >= len || j == 2 {
162 return None;
163 }
164 while j < len && is_sep(bytes[j]) {
166 j += 1;
167 }
168 if j >= len {
169 return None;
170 }
171 let share_start = j;
172 while j < len && !is_sep(bytes[j]) {
174 j += 1;
175 }
176 if j == share_start {
177 return None;
178 }
179 if j == len {
180 return None;
181 } Some((j + 1, j + 1))
183}
184
185fn find_dirname_end(bytes: &[u8], offset: usize) -> Option<usize> {
186 let mut matched_slash = true;
187 for i in (offset..bytes.len()).rev() {
188 #[cfg(windows)]
189 let is_separator = is_sep(bytes[i]);
190 #[cfg(not(windows))]
191 let is_separator = bytes[i] == b'/';
192
193 if is_separator {
194 if !matched_slash {
195 return Some(i);
196 }
197 } else {
198 matched_slash = false;
199 }
200 }
201 None
202}
203
204pub fn name_extname(path: &str) -> (&str, &str) {
205 let path = strip_last_sep(path);
206 let sep_pos = find_last_sep(path);
207
208 let path = match sep_pos {
209 Some(idx) => &path[idx + 1..],
210 None => path,
211 };
212 if path.starts_with('.') {
213 return (path, "");
214 }
215 match path.rfind('.') {
216 Some(idx) => path.split_at(idx),
217 None => (path, ""),
218 }
219}
220
221fn strip_last_sep(path: &str) -> &str {
222 if ends_with_sep(path) {
223 &path[..path.len() - 1]
224 } else {
225 path
226 }
227}
228
229pub fn basename(path: String, suffix: Opt<String>) -> String {
230 #[cfg(windows)]
231 {
232 if path.is_empty() || path == MAIN_SEPARATOR_STR || path == FORWARD_SLASH_STR {
233 return String::from("");
234 }
235 }
236 #[cfg(not(windows))]
237 {
238 if path.is_empty() || path == MAIN_SEPARATOR_STR {
239 return String::from("");
240 }
241 }
242
243 let (base, ext) = name_extname(&path);
244 let mut name = [base, ext].concat();
245 if let Some(suffix) = suffix.0 {
246 if let Some(location) = name.rfind(&suffix) {
247 name.truncate(location);
248 return name;
249 }
250 }
251 name
252}
253
254fn extname(path: String) -> String {
255 let (_, ext) = name_extname(&path);
256 ext.to_string()
257}
258
259fn format(obj: Object) -> String {
260 let dir: String = obj.get("dir").unwrap_or_default();
261 let root: String = obj.get("root").unwrap_or_default();
262 let base: String = obj.get("base").unwrap_or_default();
263 let name: String = obj.get("name").unwrap_or_default();
264 let ext: String = obj.get("ext").unwrap_or_default();
265
266 let mut path = String::new();
267 if !dir.is_empty() {
268 path.push_str(&dir);
269 if !ends_with_sep(&dir) {
270 path.push(MAIN_SEPARATOR);
271 }
272 } else if !root.is_empty() {
273 path.push_str(&root);
274 if !ends_with_sep(&root) {
275 path.push(MAIN_SEPARATOR);
276 }
277 }
278 if !base.is_empty() {
279 path.push_str(&base);
280 } else {
281 path.push_str(&name);
282 if !ext.is_empty() {
283 if !ext.starts_with('.') {
284 path.push('.');
285 }
286 path.push_str(&ext);
287 }
288 }
289 path
290}
291
292fn parse(ctx: Ctx, path_str: String) -> Result<Object> {
293 let obj = Object::new(ctx)?;
294 let path = Path::new(&path_str);
295 let parent = path
296 .parent()
297 .map(|p| p.to_str().unwrap())
298 .unwrap_or_default();
299 let filename = path
300 .file_name()
301 .map(|n| n.to_str().unwrap())
302 .unwrap_or_default();
303
304 let (name, extension) = name_extname(filename);
305
306 let root = path
307 .components()
308 .next()
309 .and_then(|c| match c {
310 Component::Prefix(prefix) => prefix.as_os_str().to_str(),
311 Component::RootDir => c.as_os_str().to_str(),
312 _ => Some(""),
313 })
314 .unwrap_or_default();
315
316 obj.set("root", root)?;
317 obj.set("dir", parent)?;
318 obj.set("base", [name, extension].concat())?;
319 obj.set("ext", extension)?;
320 obj.set("name", name)?;
321
322 Ok(obj)
323}
324
325fn join(parts: Rest<String>) -> String {
326 join_path(parts.0.iter())
327}
328
329pub fn join_path<S, I>(parts: I) -> String
330where
331 S: AsRef<str>,
332 I: IntoIterator<Item = S>,
333{
334 join_path_with_separator(parts, false)
335}
336
337pub fn join_path_with_separator<S, I>(parts: I, force_posix_sep: bool) -> String
338where
339 S: AsRef<str>,
340 I: IntoIterator<Item = S>,
341{
342 let parts_vec: Vec<S> = parts.into_iter().collect();
344 let likely_max_size = parts_vec
347 .iter()
348 .map(|p| p.as_ref().len() + 1)
349 .sum::<usize>()
350 + 10;
351 let result = String::with_capacity(likely_max_size);
352 join_resolve_path(parts_vec, false, result, PathBuf::new(), force_posix_sep)
353}
354
355pub fn resolve_path<S, I>(parts: I) -> Result<String>
356where
357 S: AsRef<str>,
358 I: IntoIterator<Item = S>,
359{
360 resolve_path_with_separator(parts, false)
361}
362
363pub fn resolve_path_with_separator<S, I>(parts: I, force_posix_sep: bool) -> Result<String>
364where
365 S: AsRef<str>,
366 I: IntoIterator<Item = S>,
367{
368 let cwd = std::env::current_dir()?;
369
370 let mut result = cwd.clone().into_os_string().into_string().unwrap();
371 if !result.ends_with(MAIN_SEPARATOR) {
373 result.push(MAIN_SEPARATOR);
374 }
375 #[cfg(windows)]
376 {
377 if force_posix_sep {
378 result = result.replace(MAIN_SEPARATOR, FORWARD_SLASH_STR);
379 }
380 }
381 Ok(join_resolve_path(parts, true, result, cwd, force_posix_sep))
382}
383
384pub fn relative<F, T>(from: F, to: T) -> Result<String>
385where
386 F: AsRef<str>,
387 T: AsRef<str>,
388{
389 let from_ref = from.as_ref();
390 let to_ref = to.as_ref();
391 if from_ref == to_ref {
392 return Ok("".into());
393 }
394
395 let mut abs_from = None;
396
397 if !is_absolute(from_ref) {
398 abs_from = Some(
399 std::env::current_dir()?.to_string_lossy().to_string() + MAIN_SEPARATOR_STR + from_ref,
400 );
401 }
402
403 let mut abs_to = None;
404
405 if !is_absolute(to_ref) {
406 abs_to = Some(
407 std::env::current_dir()?.to_string_lossy().to_string() + MAIN_SEPARATOR_STR + to_ref,
408 );
409 }
410
411 let from_ref = abs_from.as_deref().unwrap_or(from_ref);
412 let to_ref = abs_to.as_deref().unwrap_or(to_ref);
413
414 let mut from_index = 0;
415 let mut to_index = 0;
416 while from_index < from_ref.len() && to_index < to_ref.len() {
418 let from_next = find_next_separator(&from_ref[from_index..])
419 .unwrap_or(from_ref.len() - from_index)
420 + from_index;
421 let to_next =
422 find_next_separator(&to_ref[to_index..]).unwrap_or(to_ref.len() - to_index) + to_index;
423 if from_ref[from_index..from_next] != to_ref[to_index..to_next] {
424 break;
425 }
426 from_index = from_next + 1; to_index = to_next + 1; }
429 let mut relative = String::new();
430 while from_index < from_ref.len() {
432 let from_next = find_next_separator(&from_ref[from_index..])
433 .unwrap_or(from_ref.len() - from_index)
434 + from_index;
435 if !relative.is_empty() {
436 relative.push(MAIN_SEPARATOR);
437 }
438 relative.push_str("..");
439 from_index = from_next + 1; }
441 while to_index < to_ref.len() {
443 let to_next =
444 find_next_separator(&to_ref[to_index..]).unwrap_or(to_ref.len() - to_index) + to_index;
445 if !relative.is_empty() {
446 relative.push(MAIN_SEPARATOR);
447 }
448 let component = &to_ref[to_index..to_next];
449 if component != "." {
450 relative.push_str(component);
451 }
452 to_index = to_next + 1; }
454 Ok(if relative.is_empty() {
455 ".".into()
456 } else {
457 relative
458 })
459}
460
461fn join_resolve_path<S, I>(
462 parts: I,
463 resolve: bool,
464 mut result: String,
465 cwd: PathBuf,
466 force_posix_sep: bool,
467) -> String
468where
469 S: AsRef<str>,
470 I: IntoIterator<Item = S>,
471{
472 let (sep, sep_str) = if force_posix_sep {
473 ('/', "/")
474 } else {
475 (MAIN_SEPARATOR, MAIN_SEPARATOR_STR)
476 };
477
478 let mut resolve_cow: Cow<str>;
479 let mut empty = true;
480 let mut prefix_len = 0;
481
482 let mut index_stack = Vec::with_capacity(16);
483
484 if ends_with_sep(&result) && result.len() > 1 {
486 result.truncate(result.len() - 1);
487 }
488
489 for part in parts {
490 let mut part_ref: &str = part.as_ref();
491 let mut start = 0;
492 if resolve {
493 if cfg!(not(windows)) {
494 if part_ref.starts_with(MAIN_SEPARATOR) {
495 empty = false;
496 result = MAIN_SEPARATOR.into();
497 start = 1;
498 }
499 } else {
500 let starts_with_sep = starts_with_sep(part_ref);
501 if starts_with_sep {
502 let (prefix, _) = get_path_prefix(&cwd);
503 prefix_len = prefix.len();
504 result = prefix;
505 empty = false;
506 result.push(sep);
507 } else {
508 let path_buf: PathBuf = PathBuf::from(part_ref);
509 if path_buf.is_absolute() {
510 empty = false;
511 let (prefix, mut components) = get_path_prefix(&path_buf);
512 if !prefix.is_empty() {
513 components.next(); }
515 prefix_len = prefix.len();
516 result = prefix;
517 result.push(sep);
518 resolve_cow = components
519 .map(|comp| comp.as_os_str().to_str().unwrap_or_default()) .collect::<Vec<&str>>() .join(sep_str)
522 .into();
523 part_ref = resolve_cow.as_ref();
524 }
525 }
526 }
527 } else if starts_with_sep(part_ref) && empty {
528 empty = false;
529 result.push(sep);
530 start = 1;
531 }
532
533 while start < part_ref.len() {
534 let end = find_next_separator(&part_ref[start..]).map_or(part_ref.len(), |i| i + start);
535 match &part_ref[start..end] {
536 ".." => {
537 if let Some(last_index) = index_stack.pop() {
538 result.truncate(last_index);
539 } else if empty {
540 if let Some(last_index) = find_last_sep(&result) {
541 result.truncate(last_index);
542 }
543 }
544 }
545 "" | "." => {
546 }
548 sub_part => {
549 let len = result.len();
550 if !result.ends_with(sep) && !result.is_empty() {
551 result.push(sep);
552 }
553 result.push_str(sub_part);
554 result.push(sep);
555 index_stack.push(len);
556 }
557 }
558 start = end + 1;
559 }
560 }
561
562 if result.len() > prefix_len + 1 && ends_with_sep(&result) {
563 result.truncate(result.len() - 1);
564 }
565
566 result
567}
568
569pub fn resolve(path: Rest<String>) -> Result<String> {
570 resolve_path(path.iter())
571}
572
573fn get_path_prefix(cwd: &Path) -> (String, std::iter::Peekable<std::path::Components<'_>>) {
574 let mut components = cwd.components().peekable();
575
576 let prefix = if let Some(Component::Prefix(prefix)) = components.peek() {
577 prefix.as_os_str().to_str().unwrap().to_string()
578 } else {
579 "".into()
580 };
581
582 (prefix, components)
583}
584
585pub fn normalize<P: AsRef<str>>(path: P) -> String {
586 join_path([path].iter())
587}
588
589#[allow(dead_code)] fn starts_with_sep(path: &str) -> bool {
591 matches!(path.as_bytes().first().unwrap_or(&0), b'/' | b'\\')
592}
593
594#[cfg(windows)]
595pub fn ends_with_sep(path: &str) -> bool {
596 matches!(path.as_bytes().last().unwrap_or(&0), b'/' | b'\\')
597}
598
599#[cfg(not(windows))]
600pub fn ends_with_sep(path: &str) -> bool {
601 path.ends_with(MAIN_SEPARATOR)
602}
603
604#[cfg(windows)]
605pub fn is_absolute(path: &str) -> bool {
606 starts_with_sep(path) || PathBuf::from(path).is_absolute()
607}
608
609#[cfg(not(windows))]
610pub fn is_absolute(path: &str) -> bool {
611 path.starts_with(MAIN_SEPARATOR)
612}
613
614impl ModuleDef for PathModule {
615 fn declare(declare: &Declarations) -> Result<()> {
616 declare.declare("basename")?;
617 declare.declare("dirname")?;
618 declare.declare("extname")?;
619 declare.declare("format")?;
620 declare.declare("parse")?;
621 declare.declare("join")?;
622 declare.declare("resolve")?;
623 declare.declare("relative")?;
624 declare.declare("normalize")?;
625 declare.declare("isAbsolute")?;
626 declare.declare("delimiter")?;
627 declare.declare("sep")?;
628
629 declare.declare("default")?;
630 Ok(())
631 }
632
633 fn evaluate<'js>(ctx: &Ctx<'js>, exports: &Exports<'js>) -> Result<()> {
634 export_default(ctx, exports, |default| {
635 default.set("dirname", Func::from(dirname::<String>))?;
636 default.set("basename", Func::from(basename))?;
637 default.set("extname", Func::from(extname))?;
638 default.set("format", Func::from(format))?;
639 default.set("parse", Func::from(parse))?;
640 default.set("join", Func::from(join))?;
641 default.set("relative", Func::from(relative::<String, String>))?;
642 default.set("resolve", Func::from(resolve))?;
643 default.set("normalize", Func::from(normalize::<String>))?;
644 default.set("isAbsolute", Func::from(|s: String| is_absolute(&s)))?;
645 default.prop("delimiter", DELIMITER.to_string())?;
646 default.prop("sep", MAIN_SEPARATOR.to_string())?;
647 Ok(())
648 })
649 }
650}
651
652impl From<PathModule> for ModuleInfo<PathModule> {
653 fn from(val: PathModule) -> Self {
654 ModuleInfo {
655 name: "path",
656 module: val,
657 }
658 }
659}
660
661#[cfg(test)]
662mod tests {
663 use std::{env::set_current_dir, sync::Mutex};
664
665 static THREAD_LOCK: Lazy<Mutex<()>> = Lazy::new(Mutex::default);
666
667 use once_cell::sync::Lazy;
668
669 use super::*;
670
671 #[test]
672 fn test_relative() {
673 let _shared = THREAD_LOCK.lock().unwrap();
674 let cwd = std::env::current_dir().expect("unable to get current working directory");
675 set_current_dir("/").expect("unable to set working directory to /");
676
677 assert_eq!(
678 relative("a/b/c", "b/c").unwrap(),
679 "../../../b/c".replace('/', MAIN_SEPARATOR_STR)
680 );
681 assert_eq!(
682 relative("/data/orandea/test/aaa", "/data/orandea/impl/bbb").unwrap(),
683 "../../impl/bbb".replace('/', MAIN_SEPARATOR_STR)
684 );
685 assert_eq!(
686 relative("/a/b/c", "/a/d").unwrap(),
687 "../../d".replace('/', MAIN_SEPARATOR_STR)
688 );
689 assert_eq!(relative("/a/b/c", "/a/b/c/d").unwrap(), "d");
690 assert_eq!(relative("/a/b/c", "/a/b/c").unwrap(), "");
691
692 assert_eq!(
693 relative("a/b", "a/b/c/d").unwrap(),
694 "c/d".replace('/', MAIN_SEPARATOR_STR)
695 );
696 assert_eq!(
697 relative("a/b/c", "b/c").unwrap(),
698 "../../../b/c".replace('/', MAIN_SEPARATOR_STR)
699 );
700
701 set_current_dir(cwd).expect("unable to set working directory back");
702 }
703
704 #[test]
705 fn test_dirname() {
706 assert_eq!(dirname("/usr/local/bin".to_string()), "/usr/local");
707 assert_eq!(dirname("/usr/local/".to_string()), "/usr");
708 assert_eq!(dirname("usr/local/bin".to_string()), "usr/local");
709 assert_eq!(dirname("/".to_string()), "/");
710 assert_eq!(dirname("".to_string()), ".");
711 }
712
713 #[test]
714 fn test_basename() {
715 assert_eq!(basename("/usr/local/bin".to_string(), Opt(None)), "bin");
716 assert_eq!(
717 basename("/usr/local/bin.txt".to_string(), Opt(None)),
718 "bin.txt"
719 );
720 assert_eq!(
721 basename(
722 "/usr/local/bin.txt".to_string(),
723 Opt(Some(".txt".to_string()))
724 ),
725 "bin"
726 );
727 assert_eq!(basename("".to_string(), Opt(None)), "");
728 assert_eq!(basename("/".to_string(), Opt(None)), "");
729 }
730
731 #[test]
732 fn test_extname() {
733 assert_eq!(extname("/usr/local/bin.txt".to_string()), ".txt");
734 assert_eq!(extname("/usr/local/bin".to_string()), "");
735 assert_eq!(extname("file.tar.gz".to_string()), ".gz");
736 assert_eq!(extname(".bashrc".to_string()), "");
737 assert_eq!(extname("".to_string()), "");
738 }
739
740 #[test]
741 fn test_join() {
742 assert_eq!(
744 join_path(["/usr", "local", "bin"].iter()),
745 "/usr/local/bin".replace('/', MAIN_SEPARATOR_STR)
746 );
747 assert_eq!(
748 join_path(["/usr", "/local", "bin"].iter()),
749 "/usr/local/bin".replace('/', MAIN_SEPARATOR_STR)
750 );
751 assert_eq!(
752 join_path(["usr", "local", "bin"].iter()),
753 "usr/local/bin".replace('/', MAIN_SEPARATOR_STR)
754 );
755 assert_eq!(join_path(["", "bin"].iter()), "bin");
756
757 assert_eq!(
759 join_path(["/usr", "..", "local", "bin"].iter()),
760 "/local/bin".replace('/', MAIN_SEPARATOR_STR)
761 ); assert_eq!(
763 join_path([".", "usr", "local"]),
764 "usr/local".replace('/', MAIN_SEPARATOR_STR)
765 ); assert_eq!(
767 join_path(["/usr", ".", "bin"].iter()),
768 "/usr/bin".replace('/', MAIN_SEPARATOR_STR)
769 ); assert_eq!(
771 join_path(["usr", "local", "bin", ".."].iter()),
772 "usr/local".replace('/', MAIN_SEPARATOR_STR)
773 ); assert_eq!(
775 join_path(["/usr", "local", "", "bin"].iter()),
776 "/usr/local/bin".replace('/', MAIN_SEPARATOR_STR)
777 ); assert_eq!(
779 join_path(["/usr", "local", ".hidden"].iter()),
780 "/usr/local/.hidden".replace('/', MAIN_SEPARATOR_STR)
781 ); }
783
784 #[test]
785 fn test_resolve_path() {
786 let _shared = THREAD_LOCK.lock().unwrap();
787 let prefix = if cfg!(windows) {
788 if let Some(Component::Prefix(prefix)) =
789 std::env::current_dir().unwrap().components().next()
790 {
791 prefix.as_os_str().to_str().unwrap().to_string()
792 } else {
793 "".into()
794 }
795 } else {
796 "".into()
797 };
798
799 assert_eq!(
800 resolve_path(["", "foo/bar"].iter()).unwrap(),
801 std::env::current_dir()
802 .unwrap()
803 .join("foo/bar".replace('/', MAIN_SEPARATOR_STR))
804 .to_string_lossy()
805 .to_string()
806 );
807
808 assert_eq!(
810 resolve_path(["/"].iter()).unwrap(),
811 prefix.clone() + MAIN_SEPARATOR_STR
812 );
813
814 assert_eq!(
816 resolve_path(["/foo/bar", "../baz"].iter()).unwrap(),
817 prefix.clone() + &"/foo/baz".replace('/', MAIN_SEPARATOR_STR)
818 );
819 assert_eq!(
820 resolve_path(["/foo/bar", "./baz"].iter()).unwrap(),
821 prefix.clone() + &"/foo/bar/baz".replace('/', MAIN_SEPARATOR_STR)
822 );
823 assert_eq!(
824 resolve_path(["foo/bar", "/baz"].iter()).unwrap(),
825 prefix.clone() + &"/baz".replace('/', MAIN_SEPARATOR_STR)
826 );
827
828 assert_eq!(
830 resolve_path(["/foo", "bar", ".", "baz"].iter()).unwrap(),
831 prefix.clone() + &"/foo/bar/baz".replace('/', MAIN_SEPARATOR_STR)
832 ); assert_eq!(
834 resolve_path(["/foo", "bar", "..", "baz"].iter()).unwrap(),
835 prefix.clone() + &"/foo/baz".replace('/', MAIN_SEPARATOR_STR)
836 ); assert_eq!(
838 resolve_path(["/foo", "bar", "../..", "baz"].iter()).unwrap(),
839 prefix.clone() + &"/baz".replace('/', MAIN_SEPARATOR_STR)
840 ); assert_eq!(
842 resolve_path(["/foo", "bar", ".hidden"].iter()).unwrap(),
843 prefix.clone() + &"/foo/bar/.hidden".replace('/', MAIN_SEPARATOR_STR)
844 ); assert_eq!(
846 resolve_path(["/foo", ".", "bar", "."].iter()).unwrap(),
847 prefix.clone() + &"/foo/bar".replace('/', MAIN_SEPARATOR_STR)
848 ); assert_eq!(
850 resolve_path(["/foo", "..", "..", "bar"].iter()).unwrap(),
851 prefix.clone() + &"/bar".replace('/', MAIN_SEPARATOR_STR)
852 ); assert_eq!(
854 resolve_path(["/foo/bar", "/..", "baz"].iter()).unwrap(),
855 prefix.clone() + &"/baz".replace('/', MAIN_SEPARATOR_STR)
856 ); assert_eq!(
859 resolve_path(["../foo"].iter()).unwrap(),
860 std::env::current_dir()
861 .unwrap()
862 .parent()
863 .unwrap()
864 .join("foo".replace('/', MAIN_SEPARATOR_STR))
865 .to_string_lossy()
866 .to_string()
867 ); assert_eq!(
870 resolve_path(["../".repeat(32)].iter()).unwrap(),
871 prefix.clone()
872 ); }
874
875 #[test]
876 fn test_normalize() {
877 assert_eq!(
878 normalize("/foo//bar//baz"),
879 "/foo/bar/baz".replace('/', MAIN_SEPARATOR_STR)
880 );
881 assert_eq!(
882 normalize("/foo/./bar/../baz"),
883 "/foo/baz".replace('/', MAIN_SEPARATOR_STR)
884 );
885 assert_eq!(
886 normalize("foo/bar/"),
887 "foo/bar".replace('/', MAIN_SEPARATOR_STR)
888 );
889 assert_eq!(normalize("./foo"), "foo");
890 }
891
892 #[test]
893 fn test_is_absolute() {
894 assert!(is_absolute("/usr/local/bin"));
895 assert!(!is_absolute("usr/local/bin"));
896 #[cfg(windows)]
897 assert!(is_absolute("C:\\Program Files")); assert!(!is_absolute("./local/bin"));
899 }
900
901 #[test]
902 fn test_replace_backslash() {
903 assert_eq!(replace_backslash("C:\\Program Files"), "C:/Program Files");
904 assert_eq!(replace_backslash("/usr/local/bin"), "/usr/local/bin");
905 assert_eq!(replace_backslash("C:\\Users\\User\\"), "C:/Users/User/");
906 }
907}