]> git.proxmox.com Git - rustc.git/blob - src/librustc_back/fs.rs
Imported Upstream version 1.0.0~beta.3
[rustc.git] / src / librustc_back / fs.rs
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.
4 //
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.
10
11 use std::io;
12 use std::path::{Path, PathBuf};
13
14 #[cfg(windows)]
15 pub fn realpath(original: &Path) -> io::Result<PathBuf> {
16 Ok(original.to_path_buf())
17 }
18
19 #[cfg(unix)]
20 pub fn realpath(original: &Path) -> io::Result<PathBuf> {
21 use libc;
22 use std::ffi::{OsString, CString};
23 use std::os::unix::prelude::*;
24
25 extern {
26 fn realpath(pathname: *const libc::c_char, resolved: *mut libc::c_char)
27 -> *mut libc::c_char;
28 }
29
30 let path = try!(CString::new(original.as_os_str().as_bytes()));
31 let mut buf = vec![0u8; 16 * 1024];
32 unsafe {
33 let r = realpath(path.as_ptr(), buf.as_mut_ptr() as *mut _);
34 if r.is_null() {
35 return Err(io::Error::last_os_error())
36 }
37 }
38 let p = buf.iter().position(|i| *i == 0).unwrap();
39 buf.truncate(p);
40 Ok(PathBuf::from(OsString::from_vec(buf)))
41 }
42
43 #[cfg(all(not(windows), test))]
44 mod test {
45 use tempdir::TempDir;
46 use std::fs::{self, File};
47 use super::realpath;
48
49 #[test]
50 fn realpath_works() {
51 let tmpdir = TempDir::new("rustc-fs").unwrap();
52 let tmpdir = realpath(tmpdir.path()).unwrap();
53 let file = tmpdir.join("test");
54 let dir = tmpdir.join("test2");
55 let link = dir.join("link");
56 let linkdir = tmpdir.join("test3");
57
58 File::create(&file).unwrap();
59 fs::create_dir(&dir).unwrap();
60 fs::soft_link(&file, &link).unwrap();
61 fs::soft_link(&dir, &linkdir).unwrap();
62
63 assert_eq!(realpath(&tmpdir).unwrap(), tmpdir);
64 assert_eq!(realpath(&file).unwrap(), file);
65 assert_eq!(realpath(&link).unwrap(), file);
66 assert_eq!(realpath(&linkdir).unwrap(), dir);
67 assert_eq!(realpath(&linkdir.join("link")).unwrap(), file);
68 }
69
70 #[test]
71 fn realpath_works_tricky() {
72 let tmpdir = TempDir::new("rustc-fs").unwrap();
73 let tmpdir = realpath(tmpdir.path()).unwrap();
74
75 let a = tmpdir.join("a");
76 let b = a.join("b");
77 let c = b.join("c");
78 let d = a.join("d");
79 let e = d.join("e");
80 let f = a.join("f");
81
82 fs::create_dir_all(&b).unwrap();
83 fs::create_dir_all(&d).unwrap();
84 File::create(&f).unwrap();
85 fs::soft_link("../d/e", &c).unwrap();
86 fs::soft_link("../f", &e).unwrap();
87
88 assert_eq!(realpath(&c).unwrap(), f);
89 assert_eq!(realpath(&e).unwrap(), f);
90 }
91 }