path.rs 33.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

11 12 13 14 15 16
/*!

Cross-platform file path handling

*/

17 18
#[allow(missing_doc)];

19
use container::Container;
20
use cmp::Eq;
21
use libc;
22
use option::{None, Option, Some};
23
use str;
24
use str::StrSlice;
25
use to_str::ToStr;
26
use ascii::{AsciiCast, AsciiStr};
27 28
use old_iter::BaseIter;
use vec::OwnedVector;
29

30 31 32 33 34
#[cfg(windows)]
pub use Path = self::WindowsPath;
#[cfg(unix)]
pub use Path = self::PosixPath;

35
#[deriving(Clone, Eq)]
36
pub struct WindowsPath {
37 38 39 40
    host: Option<~str>,
    device: Option<~str>,
    is_absolute: bool,
    components: ~[~str],
41 42
}

43
pub fn WindowsPath(s: &str) -> WindowsPath {
44
    GenericPath::from_str(s)
45 46
}

47
#[deriving(Clone, Eq)]
48
pub struct PosixPath {
49 50
    is_absolute: bool,
    components: ~[~str],
51 52
}

53
pub fn PosixPath(s: &str) -> PosixPath {
54
    GenericPath::from_str(s)
55 56
}

57
pub trait GenericPath {
58
    /// Converts a string to a Path
59
    fn from_str(&str) -> Self;
60

61
    /// Returns the directory component of `self`, as a string
62
    fn dirname(&self) -> ~str;
63 64
    /// Returns the file component of `self`, as a string option.
    /// Returns None if `self` names a directory.
65
    fn filename(&self) -> Option<~str>;
66 67 68 69
    /// Returns the stem of the file component of `self`, as a string option.
    /// The stem is the slice of a filename starting at 0 and ending just before
    /// the last '.' in the name.
    /// Returns None if `self` names a directory.
70
    fn filestem(&self) -> Option<~str>;
71 72 73 74
    /// Returns the type of the file component of `self`, as a string option.
    /// The file type is the slice of a filename starting just after the last
    /// '.' in the name and ending at the last index in the filename.
    /// Returns None if `self` names a directory.
75
    fn filetype(&self) -> Option<~str>;
76

77 78
    /// Returns a new path consisting of `self` with the parent directory component replaced
    /// with the given string.
79
    fn with_dirname(&self, (&str)) -> Self;
80 81
    /// Returns a new path consisting of `self` with the file component replaced
    /// with the given string.
82
    fn with_filename(&self, (&str)) -> Self;
83 84
    /// Returns a new path consisting of `self` with the file stem replaced
    /// with the given string.
85
    fn with_filestem(&self, (&str)) -> Self;
86 87
    /// Returns a new path consisting of `self` with the file type replaced
    /// with the given string.
88
    fn with_filetype(&self, (&str)) -> Self;
89

90 91
    /// Returns the directory component of `self`, as a new path.
    /// If `self` has no parent, returns `self`.
92
    fn dir_path(&self) -> Self;
93 94
    /// Returns the file component of `self`, as a new path.
    /// If `self` names a directory, returns the empty path.
95
    fn file_path(&self) -> Self;
96

97 98
    /// Returns a new Path whose parent directory is `self` and whose
    /// file component is the given string.
99
    fn push(&self, (&str)) -> Self;
100
    /// Returns a new Path consisting of the given path, made relative to `self`.
101
    fn push_rel(&self, (&Self)) -> Self;
102 103
    /// Returns a new Path consisting of the path given by the given vector
    /// of strings, relative to `self`.
104
    fn push_many(&self, (&[~str])) -> Self;
105 106
    /// Identical to `dir_path` except in the case where `self` has only one
    /// component. In this case, `pop` returns the empty path.
107
    fn pop(&self) -> Self;
108

109 110
    /// The same as `push_rel`, except that the directory argument must not
    /// contain directory separators in any of its components.
111
    fn unsafe_join(&self, (&Self)) -> Self;
112 113 114
    /// On Unix, always returns false. On Windows, returns true iff `self`'s
    /// file stem is one of: `con` `aux` `com1` `com2` `com3` `com4`
    /// `lpt1` `lpt2` `lpt3` `prn` `nul`
115
    fn is_restricted(&self) -> bool;
116

117 118 119
    /// Returns a new path that names the same file as `self`, without containing
    /// any '.', '..', or empty components. On Windows, uppercases the drive letter
    /// as well.
120
    fn normalize(&self) -> Self;
121

122
    /// Returns `true` if `self` is an absolute path.
123
    fn is_absolute(&self) -> bool;
124 125
}

126
#[cfg(target_os = "linux")]
K
kyeongwoon 已提交
127
#[cfg(target_os = "android")]
128 129
mod stat {
    #[cfg(target_arch = "x86")]
K
kyeongwoon 已提交
130
    #[cfg(target_arch = "arm")]
131
    pub mod arch {
132 133
        use libc;

134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
        pub fn default_stat() -> libc::stat {
            libc::stat {
                st_dev: 0,
                __pad1: 0,
                st_ino: 0,
                st_mode: 0,
                st_nlink: 0,
                st_uid: 0,
                st_gid: 0,
                st_rdev: 0,
                __pad2: 0,
                st_size: 0,
                st_blksize: 0,
                st_blocks: 0,
                st_atime: 0,
                st_atime_nsec: 0,
                st_mtime: 0,
                st_mtime_nsec: 0,
                st_ctime: 0,
                st_ctime_nsec: 0,
                __unused4: 0,
                __unused5: 0,
            }
        }
    }

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
    #[cfg(target_arch = "mips")]
    pub mod arch {
        use libc;

        pub fn default_stat() -> libc::stat {
            libc::stat {
                st_dev: 0,
                st_pad1: [0, ..3],
                st_ino: 0,
                st_mode: 0,
                st_nlink: 0,
                st_uid: 0,
                st_gid: 0,
                st_rdev: 0,
                st_pad2: [0, ..2],
                st_size: 0,
                st_pad3: 0,
                st_atime: 0,
                st_atime_nsec: 0,
                st_mtime: 0,
                st_mtime_nsec: 0,
                st_ctime: 0,
                st_ctime_nsec: 0,
                st_blksize: 0,
                st_blocks: 0,
                st_pad5: [0, ..14],
            }
        }
    }

190 191
    #[cfg(target_arch = "x86_64")]
    pub mod arch {
192 193
        use libc;

194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
        pub fn default_stat() -> libc::stat {
            libc::stat {
                st_dev: 0,
                st_ino: 0,
                st_nlink: 0,
                st_mode: 0,
                st_uid: 0,
                st_gid: 0,
                __pad0: 0,
                st_rdev: 0,
                st_size: 0,
                st_blksize: 0,
                st_blocks: 0,
                st_atime: 0,
                st_atime_nsec: 0,
                st_mtime: 0,
                st_mtime_nsec: 0,
                st_ctime: 0,
                st_ctime_nsec: 0,
                __unused: [0, 0, 0],
            }
        }
    }
}

#[cfg(target_os = "freebsd")]
mod stat {
    #[cfg(target_arch = "x86_64")]
    pub mod arch {
223 224
        use libc;

225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
        pub fn default_stat() -> libc::stat {
            libc::stat {
                st_dev: 0,
                st_ino: 0,
                st_mode: 0,
                st_nlink: 0,
                st_uid: 0,
                st_gid: 0,
                st_rdev: 0,
                st_atime: 0,
                st_atime_nsec: 0,
                st_mtime: 0,
                st_mtime_nsec: 0,
                st_ctime: 0,
                st_ctime_nsec: 0,
                st_size: 0,
                st_blocks: 0,
                st_blksize: 0,
                st_flags: 0,
                st_gen: 0,
                st_lspare: 0,
                st_birthtime: 0,
                st_birthtime_nsec: 0,
                __unused: [0, 0],
            }
        }
    }
}

#[cfg(target_os = "macos")]
mod stat {
    pub mod arch {
257 258
        use libc;

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
        pub fn default_stat() -> libc::stat {
            libc::stat {
                st_dev: 0,
                st_mode: 0,
                st_nlink: 0,
                st_ino: 0,
                st_uid: 0,
                st_gid: 0,
                st_rdev: 0,
                st_atime: 0,
                st_atime_nsec: 0,
                st_mtime: 0,
                st_mtime_nsec: 0,
                st_ctime: 0,
                st_ctime_nsec: 0,
                st_birthtime: 0,
                st_birthtime_nsec: 0,
                st_size: 0,
                st_blocks: 0,
                st_blksize: 0,
                st_flags: 0,
                st_gen: 0,
                st_lspare: 0,
                st_qspare: [0, 0],
            }
        }
    }
}

288
#[cfg(target_os = "win32")]
289 290
mod stat {
    pub mod arch {
291
        use libc;
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
        pub fn default_stat() -> libc::stat {
            libc::stat {
                st_dev: 0,
                st_ino: 0,
                st_mode: 0,
                st_nlink: 0,
                st_uid: 0,
                st_gid: 0,
                st_rdev: 0,
                st_size: 0,
                st_atime: 0,
                st_mtime: 0,
                st_ctime: 0,
            }
        }
    }
}


311 312
impl Path {
    pub fn stat(&self) -> Option<libc::stat> {
313 314 315
        unsafe {
             do str::as_c_str(self.to_str()) |buf| {
                let mut st = stat::arch::default_stat();
316 317 318 319
                match libc::stat(buf, &mut st) {
                    0 => Some(st),
                    _ => None,
                }
320
            }
321 322 323
        }
    }

324
    #[cfg(unix)]
325
    pub fn lstat(&self) -> Option<libc::stat> {
326 327 328
        unsafe {
            do str::as_c_str(self.to_str()) |buf| {
                let mut st = stat::arch::default_stat();
329 330 331 332
                match libc::lstat(buf, &mut st) {
                    0 => Some(st),
                    _ => None,
                }
333
            }
334 335 336
        }
    }

337
    pub fn exists(&self) -> bool {
338 339 340 341 342 343
        match self.stat() {
            None => false,
            Some(_) => true,
        }
    }

344
    pub fn get_size(&self) -> Option<i64> {
345 346 347 348 349 350
        match self.stat() {
            None => None,
            Some(ref st) => Some(st.st_size as i64),
        }
    }

351
    pub fn get_mode(&self) -> Option<uint> {
352 353 354 355 356 357 358 359 360 361
        match self.stat() {
            None => None,
            Some(ref st) => Some(st.st_mode as uint),
        }
    }
}

#[cfg(target_os = "freebsd")]
#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
362 363
impl Path {
    pub fn get_atime(&self) -> Option<(i64, int)> {
364 365 366 367 368 369 370 371 372
        match self.stat() {
            None => None,
            Some(ref st) => {
                Some((st.st_atime as i64,
                      st.st_atime_nsec as int))
            }
        }
    }

373
    pub fn get_mtime(&self) -> Option<(i64, int)> {
374 375 376 377 378 379 380 381 382
        match self.stat() {
            None => None,
            Some(ref st) => {
                Some((st.st_mtime as i64,
                      st.st_mtime_nsec as int))
            }
        }
    }

383
    pub fn get_ctime(&self) -> Option<(i64, int)> {
384 385 386 387 388 389 390 391 392 393 394 395
        match self.stat() {
            None => None,
            Some(ref st) => {
                Some((st.st_ctime as i64,
                      st.st_ctime_nsec as int))
            }
        }
    }
}

#[cfg(target_os = "freebsd")]
#[cfg(target_os = "macos")]
396 397
impl Path {
    pub fn get_birthtime(&self) -> Option<(i64, int)> {
398 399 400 401 402 403 404 405 406 407 408
        match self.stat() {
            None => None,
            Some(ref st) => {
                Some((st.st_birthtime as i64,
                      st.st_birthtime_nsec as int))
            }
        }
    }
}

#[cfg(target_os = "win32")]
409 410
impl Path {
    pub fn get_atime(&self) -> Option<(i64, int)> {
411 412 413 414 415 416 417 418
        match self.stat() {
            None => None,
            Some(ref st) => {
                Some((st.st_atime as i64, 0))
            }
        }
    }

419
    pub fn get_mtime(&self) -> Option<(i64, int)> {
420 421 422 423 424 425 426 427
        match self.stat() {
            None => None,
            Some(ref st) => {
                Some((st.st_mtime as i64, 0))
            }
        }
    }

428
    pub fn get_ctime(&self) -> Option<(i64, int)> {
429 430 431 432 433 434 435 436 437
        match self.stat() {
            None => None,
            Some(ref st) => {
                Some((st.st_ctime as i64, 0))
            }
        }
    }
}

438
impl ToStr for PosixPath {
439
    fn to_str(&self) -> ~str {
440 441 442
        let mut s = ~"";
        if self.is_absolute {
            s += "/";
443
        }
444
        s + str::connect(self.components, "/")
445
    }
446 447
}

448 449
// FIXME (#3227): when default methods in traits are working, de-duplicate
// PosixPath and WindowsPath, most of their methods are common.
450
impl GenericPath for PosixPath {
451
    fn from_str(s: &str) -> PosixPath {
452
        let mut components = ~[];
453 454 455
        for str::each_split_nonempty(s, |c| c == '/') |s| {
            components.push(s.to_owned())
        }
456
        let is_absolute = (s.len() != 0 && s[0] == '/' as u8);
457 458 459 460
        PosixPath {
            is_absolute: is_absolute,
            components: components,
        }
461
    }
462

463
    fn dirname(&self) -> ~str {
464
        let s = self.dir_path().to_str();
465 466 467
        match s.len() {
            0 => ~".",
            _ => s,
468 469
        }
    }
470

471
    fn filename(&self) -> Option<~str> {
472
        match self.components.len() {
473 474
            0 => None,
            n => Some(copy self.components[n - 1]),
475 476
        }
    }
477

478
    fn filestem(&self) -> Option<~str> {
479
        match self.filename() {
480 481 482 483 484 485
            None => None,
            Some(ref f) => {
                match str::rfind_char(*f, '.') {
                    Some(p) => Some(f.slice(0, p).to_owned()),
                    None => Some(copy *f),
                }
486
            }
487 488
        }
    }
489

490
    fn filetype(&self) -> Option<~str> {
491
        match self.filename() {
492 493 494 495 496 497
            None => None,
            Some(ref f) => {
                match str::rfind_char(*f, '.') {
                    Some(p) if p < f.len() => Some(f.slice(p, f.len()).to_owned()),
                    _ => None,
                }
498 499 500 501
            }
        }
    }

502
    fn with_dirname(&self, d: &str) -> PosixPath {
503
        let dpath = PosixPath(d);
504
        match self.filename() {
505 506
            Some(ref f) => dpath.push(*f),
            None => dpath,
507
        }
508 509
    }

510
    fn with_filename(&self, f: &str) -> PosixPath {
511 512
        assert!(! str::any(f, |c| windows::is_sep(c as u8)));
        self.dir_path().push(f)
513
    }
514

515
    fn with_filestem(&self, s: &str) -> PosixPath {
516
        match self.filetype() {
517 518
            None => self.with_filename(s),
            Some(ref t) => self.with_filename(str::to_owned(s) + *t),
519
        }
520 521
    }

522
    fn with_filetype(&self, t: &str) -> PosixPath {
523 524 525 526 527
        match (t.len(), self.filestem()) {
            (0, None)        => copy *self,
            (0, Some(ref s)) => self.with_filename(*s),
            (_, None)        => self.with_filename(fmt!(".%s", t)),
            (_, Some(ref s)) => self.with_filename(fmt!("%s.%s", *s, t)),
528 529 530
        }
    }

531
    fn dir_path(&self) -> PosixPath {
532 533 534
        match self.components.len() {
            0 => copy *self,
            _ => self.pop(),
535 536 537
        }
    }

538
    fn file_path(&self) -> PosixPath {
539 540 541 542
        let cs = match self.filename() {
          None => ~[],
          Some(ref f) => ~[copy *f]
        };
543 544 545 546
        PosixPath {
            is_absolute: false,
            components: cs,
        }
547 548
    }

549
    fn push_rel(&self, other: &PosixPath) -> PosixPath {
P
Patrick Walton 已提交
550
        assert!(!other.is_absolute);
551
        self.push_many(other.components)
552 553
    }

554
    fn unsafe_join(&self, other: &PosixPath) -> PosixPath {
555
        if other.is_absolute {
556 557 558 559
            PosixPath {
                is_absolute: true,
                components: copy other.components,
            }
560 561 562 563 564
        } else {
            self.push_rel(other)
        }
    }

565
    fn is_restricted(&self) -> bool {
A
Armin Ronacher 已提交
566 567 568
        false
    }

569
    fn push_many(&self, cs: &[~str]) -> PosixPath {
570 571
        let mut v = copy self.components;
        for cs.each |e| {
572 573 574 575
            let mut ss = ~[];
            for str::each_split_nonempty(*e, |c| windows::is_sep(c as u8)) |s| {
                ss.push(s.to_owned())
            }
576
            v.push_all_move(ss);
577
        }
578 579 580 581
        PosixPath {
            is_absolute: self.is_absolute,
            components: v,
        }
582 583
    }

584
    fn push(&self, s: &str) -> PosixPath {
585
        let mut v = copy self.components;
586 587 588 589
        let mut ss = ~[];
        for str::each_split_nonempty(s, |c| windows::is_sep(c as u8)) |s| {
            ss.push(s.to_owned())
        }
590
        v.push_all_move(ss);
B
Ben Striegel 已提交
591
        PosixPath { components: v, ..copy *self }
592 593
    }

594
    fn pop(&self) -> PosixPath {
595 596
        let mut cs = copy self.components;
        if cs.len() != 0 {
597
            cs.pop();
598
        }
599
        PosixPath {
T
Tim Chevalier 已提交
600
            is_absolute: self.is_absolute,
601 602
            components: cs,
        } //..self }
603
    }
604

605
    fn normalize(&self) -> PosixPath {
606
        PosixPath {
T
Tim Chevalier 已提交
607
            is_absolute: self.is_absolute,
608 609
            components: normalize(self.components),
        } // ..self }
610
    }
611 612 613 614

    fn is_absolute(&self) -> bool {
        self.is_absolute
    }
615
}
616

617

618
impl ToStr for WindowsPath {
619
    fn to_str(&self) -> ~str {
620 621
        let mut s = ~"";
        match self.host {
B
Brian Anderson 已提交
622
          Some(ref h) => { s += "\\\\"; s += *h; }
623 624 625
          None => { }
        }
        match self.device {
B
Brian Anderson 已提交
626
          Some(ref d) => { s += *d; s += ":"; }
627 628 629 630 631 632
          None => { }
        }
        if self.is_absolute {
            s += "\\";
        }
        s + str::connect(self.components, "\\")
633
    }
634
}
635

636

637
impl GenericPath for WindowsPath {
638
    fn from_str(s: &str) -> WindowsPath {
639 640 641 642
        let host;
        let device;
        let rest;

643 644 645 646 647 648 649 650 651 652
        match (
            windows::extract_drive_prefix(s),
            windows::extract_unc_prefix(s),
        ) {
            (Some((ref d, ref r)), _) => {
                host = None;
                device = Some(copy *d);
                rest = copy *r;
            }
            (None, Some((ref h, ref r))) => {
653 654 655
                host = Some(copy *h);
                device = None;
                rest = copy *r;
656 657
            }
            (None, None) => {
658 659
                host = None;
                device = None;
660
                rest = str::to_owned(s);
661 662 663
            }
        }

664 665 666 667
        let mut components = ~[];
        for str::each_split_nonempty(rest, |c| windows::is_sep(c as u8)) |s| {
            components.push(s.to_owned())
        }
668
        let is_absolute = (rest.len() != 0 && windows::is_sep(rest[0]));
669 670 671 672 673 674
        WindowsPath {
            host: host,
            device: device,
            is_absolute: is_absolute,
            components: components,
        }
675 676
    }

677
    fn dirname(&self) -> ~str {
678
        let s = self.dir_path().to_str();
679 680 681
        match s.len() {
            0 => ~".",
            _ => s,
682
        }
683 684
    }

685
    fn filename(&self) -> Option<~str> {
686
        match self.components.len() {
687 688
            0 => None,
            n => Some(copy self.components[n - 1]),
689
        }
690 691
    }

692
    fn filestem(&self) -> Option<~str> {
693
        match self.filename() {
694 695 696 697 698 699
            None => None,
            Some(ref f) => {
                match str::rfind_char(*f, '.') {
                    Some(p) => Some(f.slice(0, p).to_owned()),
                    None => Some(copy *f),
                }
700 701
            }
        }
702 703
    }

704
    fn filetype(&self) -> Option<~str> {
705 706 707 708
        match self.filename() {
          None => None,
          Some(ref f) => {
            match str::rfind_char(*f, '.') {
709 710
                Some(p) if p < f.len() => Some(f.slice(p, f.len()).to_owned()),
                _ => None,
711 712 713
            }
          }
        }
714 715
    }

716
    fn with_dirname(&self, d: &str) -> WindowsPath {
717
        let dpath = WindowsPath(d);
718
        match self.filename() {
719 720
            Some(ref f) => dpath.push(*f),
            None => dpath,
721
        }
722 723
    }

724
    fn with_filename(&self, f: &str) -> WindowsPath {
P
Patrick Walton 已提交
725
        assert!(! str::any(f, |c| windows::is_sep(c as u8)));
726
        self.dir_path().push(f)
727 728
    }

729
    fn with_filestem(&self, s: &str) -> WindowsPath {
730
        match self.filetype() {
731 732
            None => self.with_filename(s),
            Some(ref t) => self.with_filename(str::to_owned(s) + *t),
733
        }
734 735
    }

736
    fn with_filetype(&self, t: &str) -> WindowsPath {
737 738 739 740 741
        match (t.len(), self.filestem()) {
            (0, None)        => copy *self,
            (0, Some(ref s)) => self.with_filename(*s),
            (_, None)        => self.with_filename(fmt!(".%s", t)),
            (_, Some(ref s)) => self.with_filename(fmt!("%s.%s", *s, t)),
742
        }
743 744
    }

745
    fn dir_path(&self) -> WindowsPath {
746 747 748
        match self.components.len() {
            0 => copy *self,
            _ => self.pop(),
749
        }
750 751
    }

752
    fn file_path(&self) -> WindowsPath {
753 754 755 756 757 758 759 760 761
        WindowsPath {
            host: None,
            device: None,
            is_absolute: false,
            components: match self.filename() {
                None => ~[],
                Some(ref f) => ~[copy *f],
            }
        }
762 763
    }

764
    fn push_rel(&self, other: &WindowsPath) -> WindowsPath {
P
Patrick Walton 已提交
765
        assert!(!other.is_absolute);
766
        self.push_many(other.components)
767 768
    }

769
    fn unsafe_join(&self, other: &WindowsPath) -> WindowsPath {
770
        /* rhs not absolute is simple push */
771
        if !other.is_absolute {
772 773 774 775 776
            return self.push_many(other.components);
        }

        /* if rhs has a host set, then the whole thing wins */
        match other.host {
777
            Some(ref host) => {
778
                return WindowsPath {
779
                    host: Some(copy *host),
780 781
                    device: copy other.device,
                    is_absolute: true,
782
                    components: copy other.components,
783 784 785 786 787 788 789
                };
            }
            _ => {}
        }

        /* if rhs has a device set, then a part wins */
        match other.device {
790
            Some(ref device) => {
791 792
                return WindowsPath {
                    host: None,
793
                    device: Some(copy *device),
794
                    is_absolute: true,
795
                    components: copy other.components,
796
                };
797
            }
798 799 800 801 802 803 804 805 806
            _ => {}
        }

        /* fallback: host and device of lhs win, but the
           whole path of the right */
        WindowsPath {
            host: copy self.host,
            device: copy self.device,
            is_absolute: self.is_absolute || other.is_absolute,
807
            components: copy other.components,
808 809 810
        }
    }

811
    fn is_restricted(&self) -> bool {
A
Armin Ronacher 已提交
812 813
        match self.filestem() {
            Some(stem) => {
814 815
                // FIXME: #4318 Instead of to_ascii and to_str_ascii, could use
                // to_ascii_consume and to_str_consume to not do a unnecessary copy.
816
                match stem.to_ascii().to_lower().to_str_ascii() {
A
Armin Ronacher 已提交
817 818 819 820 821 822 823 824 825
                    ~"con" | ~"aux" | ~"com1" | ~"com2" | ~"com3" | ~"com4" |
                    ~"lpt1" | ~"lpt2" | ~"lpt3" | ~"prn" | ~"nul" => true,
                    _ => false
                }
            },
            None => false
        }
    }

826
    fn push_many(&self, cs: &[~str]) -> WindowsPath {
827 828
        let mut v = copy self.components;
        for cs.each |e| {
829 830 831 832
            let mut ss = ~[];
            for str::each_split_nonempty(*e, |c| windows::is_sep(c as u8)) |s| {
                ss.push(s.to_owned())
            }
833
            v.push_all_move(ss);
834
        }
T
Tim Chevalier 已提交
835
        // tedious, but as-is, we can't use ..self
836
        WindowsPath {
T
Tim Chevalier 已提交
837 838 839
            host: copy self.host,
            device: copy self.device,
            is_absolute: self.is_absolute,
L
Luqman Aden 已提交
840
            components: v
T
Tim Chevalier 已提交
841
        }
842 843
    }

844
    fn push(&self, s: &str) -> WindowsPath {
845
        let mut v = copy self.components;
846 847 848 849
        let mut ss = ~[];
        for str::each_split_nonempty(s, |c| windows::is_sep(c as u8)) |s| {
            ss.push(s.to_owned())
        }
850
        v.push_all_move(ss);
851
        WindowsPath { components: v, ..copy *self }
852 853
    }

854
    fn pop(&self) -> WindowsPath {
855 856
        let mut cs = copy self.components;
        if cs.len() != 0 {
857
            cs.pop();
858
        }
859
        WindowsPath {
T
Tim Chevalier 已提交
860 861 862
            host: copy self.host,
            device: copy self.device,
            is_absolute: self.is_absolute,
863
            components: cs,
T
Tim Chevalier 已提交
864
        }
865
    }
866

867
    fn normalize(&self) -> WindowsPath {
868
        WindowsPath {
T
Tim Chevalier 已提交
869
            host: copy self.host,
870 871
            device: match self.device {
                None => None,
872

873 874
                // FIXME: #4318 Instead of to_ascii and to_str_ascii, could use
                // to_ascii_consume and to_str_consume to not do a unnecessary copy.
875
                Some(ref device) => Some(device.to_ascii().to_upper().to_str_ascii())
876
            },
T
Tim Chevalier 已提交
877 878
            is_absolute: self.is_absolute,
            components: normalize(self.components)
879 880
        }
    }
881 882 883 884

    fn is_absolute(&self) -> bool {
        self.is_absolute
    }
885
}
886

887

888
pub fn normalize(components: &[~str]) -> ~[~str] {
889
    let mut cs = ~[];
890 891 892 893 894 895 896 897
    for components.each |c| {
        if *c == ~"." && components.len() > 1 { loop; }
        if *c == ~"" { loop; }
        if *c == ~".." && cs.len() != 0 {
            cs.pop();
            loop;
        }
        cs.push(copy *c);
898
    }
L
Luqman Aden 已提交
899
    cs
900 901
}

E
Erick Tryzelaar 已提交
902
// Various windows helpers, and tests for the impl.
903
pub mod windows {
904
    use libc;
905
    use option::{None, Option, Some};
906

E
Erick Tryzelaar 已提交
907
    #[inline(always)]
908
    pub fn is_sep(u: u8) -> bool {
E
Erick Tryzelaar 已提交
909 910
        u == '/' as u8 || u == '\\' as u8
    }
911

912
    pub fn extract_unc_prefix(s: &str) -> Option<(~str,~str)> {
E
Erick Tryzelaar 已提交
913
        if (s.len() > 1 &&
914 915
            (s[0] == '\\' as u8 || s[0] == '/' as u8) &&
            s[0] == s[1]) {
E
Erick Tryzelaar 已提交
916 917
            let mut i = 2;
            while i < s.len() {
918
                if is_sep(s[i]) {
919
                    let pre = s.slice(2, i).to_owned();
920
                    let rest = s.slice(i, s.len()).to_owned();
L
Luqman Aden 已提交
921
                    return Some((pre, rest));
E
Erick Tryzelaar 已提交
922 923 924 925 926 927
                }
                i += 1;
            }
        }
        None
    }
928

929
    pub fn extract_drive_prefix(s: &str) -> Option<(~str,~str)> {
E
Erick Tryzelaar 已提交
930 931 932 933 934 935 936
        unsafe {
            if (s.len() > 1 &&
                libc::isalpha(s[0] as libc::c_int) != 0 &&
                s[1] == ':' as u8) {
                let rest = if s.len() == 2 {
                    ~""
                } else {
937
                    s.slice(2, s.len()).to_owned()
E
Erick Tryzelaar 已提交
938
                };
939
                return Some((s.slice(0,1).to_owned(), rest));
E
Erick Tryzelaar 已提交
940 941
            }
            None
942
        }
943
    }
E
Erick Tryzelaar 已提交
944 945
}

946
#[cfg(test)]
E
Erick Tryzelaar 已提交
947
mod tests {
948 949
    use option::{None, Some};
    use path::{PosixPath, WindowsPath, windows};
950 951
    use str;

E
Erick Tryzelaar 已提交
952 953 954 955 956
    #[test]
    fn test_double_slash_collapsing() {
        let path = PosixPath("tmp/");
        let path = path.push("/hmm");
        let path = path.normalize();
957
        assert_eq!(~"tmp/hmm", path.to_str());
E
Erick Tryzelaar 已提交
958 959 960 961

        let path = WindowsPath("tmp/");
        let path = path.push("/hmm");
        let path = path.normalize();
962
        assert_eq!(~"tmp\\hmm", path.to_str());
E
Erick Tryzelaar 已提交
963
    }
964

965 966
    #[test]
    fn test_filetype_foo_bar() {
E
Erick Tryzelaar 已提交
967
        let wp = PosixPath("foo.bar");
968
        assert_eq!(wp.filetype(), Some(~".bar"));
E
Erick Tryzelaar 已提交
969 970

        let wp = WindowsPath("foo.bar");
971
        assert_eq!(wp.filetype(), Some(~".bar"));
972 973 974 975
    }

    #[test]
    fn test_filetype_foo() {
E
Erick Tryzelaar 已提交
976
        let wp = PosixPath("foo");
977
        assert_eq!(wp.filetype(), None);
E
Erick Tryzelaar 已提交
978 979

        let wp = WindowsPath("foo");
980
        assert_eq!(wp.filetype(), None);
981 982
    }

983 984
    #[test]
    fn test_posix_paths() {
E
Erick Tryzelaar 已提交
985 986
        fn t(wp: &PosixPath, s: &str) {
            let ss = wp.to_str();
987
            let sss = str::to_owned(s);
E
Erick Tryzelaar 已提交
988 989 990
            if (ss != sss) {
                debug!("got %s", ss);
                debug!("expected %s", sss);
991
                assert_eq!(ss, sss);
E
Erick Tryzelaar 已提交
992 993 994 995 996 997 998
            }
        }

        t(&(PosixPath("hi")), "hi");
        t(&(PosixPath("/lib")), "/lib");
        t(&(PosixPath("hi/there")), "hi/there");
        t(&(PosixPath("hi/there.txt")), "hi/there.txt");
999

E
Erick Tryzelaar 已提交
1000 1001
        t(&(PosixPath("hi/there.txt")), "hi/there.txt");
        t(&(PosixPath("hi/there.txt")
1002 1003
           .with_filetype("")), "hi/there");

E
Erick Tryzelaar 已提交
1004
        t(&(PosixPath("/a/b/c/there.txt")
1005 1006
            .with_dirname("hi")), "hi/there.txt");

E
Erick Tryzelaar 已提交
1007
        t(&(PosixPath("hi/there.txt")
1008
            .with_dirname(".")), "./there.txt");
1009

E
Erick Tryzelaar 已提交
1010
        t(&(PosixPath("a/b/c")
1011
            .push("..")), "a/b/c/..");
1012

E
Erick Tryzelaar 已提交
1013
        t(&(PosixPath("there.txt")
1014 1015
            .with_filetype("o")), "there.o");

E
Erick Tryzelaar 已提交
1016
        t(&(PosixPath("hi/there.txt")
1017 1018
            .with_filetype("o")), "hi/there.o");

E
Erick Tryzelaar 已提交
1019
        t(&(PosixPath("hi/there.txt")
1020 1021 1022 1023
            .with_filetype("o")
            .with_dirname("/usr/lib")),
          "/usr/lib/there.o");

E
Erick Tryzelaar 已提交
1024
        t(&(PosixPath("hi/there.txt")
1025 1026 1027 1028
            .with_filetype("o")
            .with_dirname("/usr/lib/")),
          "/usr/lib/there.o");

E
Erick Tryzelaar 已提交
1029
        t(&(PosixPath("hi/there.txt")
1030 1031 1032 1033
            .with_filetype("o")
            .with_dirname("/usr//lib//")),
            "/usr/lib/there.o");

E
Erick Tryzelaar 已提交
1034
        t(&(PosixPath("/usr/bin/rust")
1035 1036 1037 1038
            .push_many([~"lib", ~"thingy.so"])
            .with_filestem("librustc")),
          "/usr/bin/rust/lib/librustc.so");

1039 1040
    }

1041 1042
    #[test]
    fn test_normalize() {
E
Erick Tryzelaar 已提交
1043 1044
        fn t(wp: &PosixPath, s: &str) {
            let ss = wp.to_str();
1045
            let sss = str::to_owned(s);
E
Erick Tryzelaar 已提交
1046 1047 1048
            if (ss != sss) {
                debug!("got %s", ss);
                debug!("expected %s", sss);
1049
                assert_eq!(ss, sss);
E
Erick Tryzelaar 已提交
1050 1051 1052 1053
            }
        }

        t(&(PosixPath("hi/there.txt")
1054 1055
            .with_dirname(".").normalize()), "there.txt");

E
Erick Tryzelaar 已提交
1056
        t(&(PosixPath("a/b/../c/././/../foo.txt/").normalize()),
1057 1058
          "a/foo.txt");

E
Erick Tryzelaar 已提交
1059
        t(&(PosixPath("a/b/c")
1060 1061
            .push("..").normalize()), "a/b");
    }
1062 1063

    #[test]
1064
    fn test_extract_unc_prefixes() {
P
Patrick Walton 已提交
1065 1066 1067 1068 1069
        assert!(windows::extract_unc_prefix("\\\\").is_none());
        assert!(windows::extract_unc_prefix("//").is_none());
        assert!(windows::extract_unc_prefix("\\\\hi").is_none());
        assert!(windows::extract_unc_prefix("//hi").is_none());
        assert!(windows::extract_unc_prefix("\\\\hi\\") ==
1070
            Some((~"hi", ~"\\")));
P
Patrick Walton 已提交
1071
        assert!(windows::extract_unc_prefix("//hi\\") ==
1072
            Some((~"hi", ~"\\")));
P
Patrick Walton 已提交
1073
        assert!(windows::extract_unc_prefix("\\\\hi\\there") ==
1074
            Some((~"hi", ~"\\there")));
P
Patrick Walton 已提交
1075
        assert!(windows::extract_unc_prefix("//hi/there") ==
1076
            Some((~"hi", ~"/there")));
P
Patrick Walton 已提交
1077
        assert!(windows::extract_unc_prefix(
1078 1079
            "\\\\hi\\there\\friends.txt") ==
            Some((~"hi", ~"\\there\\friends.txt")));
P
Patrick Walton 已提交
1080
        assert!(windows::extract_unc_prefix(
1081 1082
            "//hi\\there\\friends.txt") ==
            Some((~"hi", ~"\\there\\friends.txt")));
1083 1084 1085
    }

    #[test]
1086
    fn test_extract_drive_prefixes() {
P
Patrick Walton 已提交
1087 1088
        assert!(windows::extract_drive_prefix("c").is_none());
        assert!(windows::extract_drive_prefix("c:") ==
1089
                     Some((~"c", ~"")));
P
Patrick Walton 已提交
1090
        assert!(windows::extract_drive_prefix("d:") ==
1091
                     Some((~"d", ~"")));
P
Patrick Walton 已提交
1092
        assert!(windows::extract_drive_prefix("z:") ==
1093
                     Some((~"z", ~"")));
P
Patrick Walton 已提交
1094
        assert!(windows::extract_drive_prefix("c:\\hi") ==
1095
                     Some((~"c", ~"\\hi")));
P
Patrick Walton 已提交
1096
        assert!(windows::extract_drive_prefix("d:hi") ==
1097
                     Some((~"d", ~"hi")));
P
Patrick Walton 已提交
1098
        assert!(windows::extract_drive_prefix("c:hi\\there.txt") ==
1099
                     Some((~"c", ~"hi\\there.txt")));
P
Patrick Walton 已提交
1100
        assert!(windows::extract_drive_prefix("c:\\hi\\there.txt") ==
1101
                     Some((~"c", ~"\\hi\\there.txt")));
1102 1103 1104
    }

    #[test]
1105 1106 1107
    fn test_windows_paths() {
        fn t(wp: &WindowsPath, s: &str) {
            let ss = wp.to_str();
1108
            let sss = str::to_owned(s);
1109 1110 1111
            if (ss != sss) {
                debug!("got %s", ss);
                debug!("expected %s", sss);
1112
                assert_eq!(ss, sss);
1113 1114 1115
            }
        }

E
Erick Tryzelaar 已提交
1116 1117 1118
        t(&(WindowsPath("hi")), "hi");
        t(&(WindowsPath("hi/there")), "hi\\there");
        t(&(WindowsPath("hi/there.txt")), "hi\\there.txt");
1119

E
Erick Tryzelaar 已提交
1120
        t(&(WindowsPath("there.txt")
1121 1122
            .with_filetype("o")), "there.o");

E
Erick Tryzelaar 已提交
1123
        t(&(WindowsPath("hi/there.txt")
1124 1125
            .with_filetype("o")), "hi\\there.o");

E
Erick Tryzelaar 已提交
1126
        t(&(WindowsPath("hi/there.txt")
1127 1128 1129 1130
            .with_filetype("o")
            .with_dirname("c:\\program files A")),
          "c:\\program files A\\there.o");

E
Erick Tryzelaar 已提交
1131
        t(&(WindowsPath("hi/there.txt")
1132 1133 1134 1135
            .with_filetype("o")
            .with_dirname("c:\\program files B\\")),
          "c:\\program files B\\there.o");

E
Erick Tryzelaar 已提交
1136
        t(&(WindowsPath("hi/there.txt")
1137 1138 1139 1140
            .with_filetype("o")
            .with_dirname("c:\\program files C\\/")),
            "c:\\program files C\\there.o");

E
Erick Tryzelaar 已提交
1141
        t(&(WindowsPath("c:\\program files (x86)\\rust")
1142 1143 1144
            .push_many([~"lib", ~"thingy.dll"])
            .with_filename("librustc.dll")),
          "c:\\program files (x86)\\rust\\lib\\librustc.dll");
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192

        t(&(WindowsPath("\\\\computer\\share")
            .unsafe_join(&WindowsPath("\\a"))),
          "\\\\computer\\a");

        t(&(WindowsPath("//computer/share")
            .unsafe_join(&WindowsPath("\\a"))),
          "\\\\computer\\a");

        t(&(WindowsPath("//computer/share")
            .unsafe_join(&WindowsPath("\\\\computer\\share"))),
          "\\\\computer\\share");

        t(&(WindowsPath("C:/whatever")
            .unsafe_join(&WindowsPath("//computer/share/a/b"))),
          "\\\\computer\\share\\a\\b");

        t(&(WindowsPath("C:")
            .unsafe_join(&WindowsPath("D:/foo"))),
          "D:\\foo");

        t(&(WindowsPath("C:")
            .unsafe_join(&WindowsPath("B"))),
          "C:B");

        t(&(WindowsPath("C:")
            .unsafe_join(&WindowsPath("/foo"))),
          "C:\\foo");

        t(&(WindowsPath("C:\\")
            .unsafe_join(&WindowsPath("\\bar"))),
          "C:\\bar");

        t(&(WindowsPath("")
            .unsafe_join(&WindowsPath(""))),
          "");

        t(&(WindowsPath("")
            .unsafe_join(&WindowsPath("a"))),
          "a");

        t(&(WindowsPath("")
            .unsafe_join(&WindowsPath("C:\\a"))),
          "C:\\a");

        t(&(WindowsPath("c:\\foo")
            .normalize()),
          "C:\\foo");
1193
    }
A
Armin Ronacher 已提交
1194 1195 1196

    #[test]
    fn test_windows_path_restrictions() {
1197 1198 1199 1200
        assert_eq!(WindowsPath("hi").is_restricted(), false);
        assert_eq!(WindowsPath("C:\\NUL").is_restricted(), true);
        assert_eq!(WindowsPath("C:\\COM1.TXT").is_restricted(), true);
        assert_eq!(WindowsPath("c:\\prn.exe").is_restricted(), true);
A
Armin Ronacher 已提交
1201
    }
1202
}