1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
15 /// Returns an absolute path in the filesystem that `path` points to. The
16 /// returned path does not contain any symlinks in its hierarchy.
17 pub fn realpath(original: &Path) -> io::IoResult<Path> {
18 static MAX_LINKS_FOLLOWED: uint = 256;
19 let original = os::make_absolute(original);
21 // Right now lstat on windows doesn't work quite well
26 let result = original.root_path();
27 let mut result = result.expect("make_absolute has no root_path");
30 for part in original.components() {
34 if followed == MAX_LINKS_FOLLOWED {
35 return Err(io::standard_error(io::InvalidInput))
38 match fs::lstat(&result) {
40 Ok(ref stat) if stat.kind != io::TypeSymlink => break,
43 let path = try!(fs::readlink(&result));
54 #[cfg(not(windows), test)]
57 use std::io::fs::{File, symlink, mkdir, mkdir_recursive};
63 let tmpdir = TempDir::new("rustc-fs").unwrap();
64 let tmpdir = realpath(tmpdir.path()).unwrap();
65 let file = tmpdir.join("test");
66 let dir = tmpdir.join("test2");
67 let link = dir.join("link");
68 let linkdir = tmpdir.join("test3");
70 File::create(&file).unwrap();
71 mkdir(&dir, io::UserRWX).unwrap();
72 symlink(&file, &link).unwrap();
73 symlink(&dir, &linkdir).unwrap();
75 assert!(realpath(&tmpdir).unwrap() == tmpdir);
76 assert!(realpath(&file).unwrap() == file);
77 assert!(realpath(&link).unwrap() == file);
78 assert!(realpath(&linkdir).unwrap() == dir);
79 assert!(realpath(&linkdir.join("link")).unwrap() == file);
83 fn realpath_works_tricky() {
84 let tmpdir = TempDir::new("rustc-fs").unwrap();
85 let tmpdir = realpath(tmpdir.path()).unwrap();
87 let a = tmpdir.join("a");
94 mkdir_recursive(&b, io::UserRWX).unwrap();
95 mkdir_recursive(&d, io::UserRWX).unwrap();
96 File::create(&f).unwrap();
97 symlink(&Path::new("../d/e"), &c).unwrap();
98 symlink(&Path::new("../f"), &e).unwrap();
100 assert!(realpath(&c).unwrap() == f);
101 assert!(realpath(&e).unwrap() == f);