fs.rs 18.1 KB
Newer Older
1 2 3 4 5
/*
Module: fs

File system manipulation
*/
6

7
import core::ctypes;
8 9
import core::vec;
import core::option;
10
import os;
11
import os::getcwd;
12
import os_fs;
13

14 15
#[abi = "cdecl"]
native mod rustrt {
16 17
    fn rust_path_is_dir(path: str::sbuf) -> ctypes::c_int;
    fn rust_path_exists(path: str::sbuf) -> ctypes::c_int;
18 19
}

20 21 22 23 24
/*
Function: path_sep

Get the default path separator for the host platform
*/
B
Brian Anderson 已提交
25
fn path_sep() -> str { ret str::from_char(os_fs::path_sep); }
26

27 28 29 30 31 32
// FIXME: This type should probably be constrained
/*
Type: path

A path or fragment of a filesystem path
*/
B
Brian Anderson 已提交
33
type path = str;
34

K
Kevin Cantu 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47
fn splitDirnameBasename (pp: path) -> {dirname: str, basename: str} {
    let ii;
    alt str::rindex(pp, os_fs::path_sep) {
        option::some(xx) { ii = xx; }
        option::none {
            alt str::rindex(pp, os_fs::alt_path_sep) {
                option::some(xx) { ii = xx; }
                option::none { ret {dirname: ".", basename: pp}; }
            }
        }
    }

    ret {dirname: str::slice(pp, 0u, ii),
48
         basename: str::slice(pp, ii + 1u, str::len_chars(pp))};
K
Kevin Cantu 已提交
49 50
}

51 52 53 54 55 56 57 58 59 60 61
/*
Function: dirname

Get the directory portion of a path

Returns all of the path up to, but excluding, the final path separator.
The dirname of "/usr/share" will be "/usr", but the dirname of
"/usr/share/" is "/usr/share".

If the path is not prefixed with a directory, then "." is returned.
*/
K
Kevin Cantu 已提交
62 63
fn dirname(pp: path) -> path {
    ret splitDirnameBasename(pp).dirname;
64 65
}

66 67 68 69 70 71 72 73 74 75 76
/*
Function: basename

Get the file name portion of a path

Returns the portion of the path after the final path separator.
The basename of "/usr/share" will be "share". If there are no
path separators in the path then the returned path is identical to
the provided path. If an empty path is provided or the path ends
with a path separator then an empty path is returned.
*/
K
Kevin Cantu 已提交
77 78
fn basename(pp: path) -> path {
    ret splitDirnameBasename(pp).basename;
79 80
}

81
// FIXME: Need some typestate to avoid bounds check when len(pre) == 0
82 83 84 85 86
/*
Function: connect

Connects to path segments

G
Graydon Hoare 已提交
87 88 89
Given paths `pre` and `post, removes any trailing path separator on `pre` and
any leading path separator on `post`, and returns the concatenation of the two
with a single path separator between them.
90
*/
M
Marijn Haverbeke 已提交
91

92
fn connect(pre: path, post: path) -> path unsafe {
G
Graydon Hoare 已提交
93 94 95
    let pre_ = pre;
    let post_ = post;
    let sep = os_fs::path_sep as u8;
96 97
    let pre_len = str::len_bytes(pre);
    let post_len = str::len_bytes(post);
98 99
    if pre_len > 1u && pre[pre_len-1u] == sep { str::unsafe::pop_byte(pre_); }
    if post_len > 1u && post[0] == sep { str::unsafe::shift_byte(post_); }
G
Graydon Hoare 已提交
100
    ret pre_ + path_sep() + post_;
101 102
}

103 104 105 106 107 108 109
/*
Function: connect_many

Connects a vector of path segments into a single path.

Inserts path separators as needed.
*/
110
fn connect_many(paths: [path]) -> path {
111 112 113 114 115 116 117 118
    ret if vec::len(paths) == 1u {
        paths[0]
    } else {
        let rest = vec::slice(paths, 1u, vec::len(paths));
        connect(paths[0], connect_many(rest))
    }
}

119
/*
120
Function: path_is_dir
121 122 123

Indicates whether a path represents a directory.
*/
124
fn path_is_dir(p: path) -> bool {
125
    ret str::as_buf(p, {|buf|
126
        rustrt::rust_path_is_dir(buf) != 0 as ctypes::c_int
127
    });
128 129 130 131 132 133 134 135
}

/*
Function: path_exists

Indicates whether a path exists.
*/
fn path_exists(p: path) -> bool {
136 137 138
    ret str::as_buf(p, {|buf|
        rustrt::rust_path_exists(buf) != 0 as ctypes::c_int
    });
139
}
140

141 142 143
/*
Function: make_dir

144
Creates a directory at the specified path.
145
*/
146
fn make_dir(p: path, mode: ctypes::c_int) -> bool {
147 148 149
    ret mkdir(p, mode);

    #[cfg(target_os = "win32")]
150
    fn mkdir(_p: path, _mode: ctypes::c_int) -> bool unsafe {
151
        // FIXME: turn mode into something useful?
E
Elly Jones 已提交
152
        ret str::as_buf(_p, {|buf|
153 154
            os::kernel32::CreateDirectoryA(
                buf, unsafe::reinterpret_cast(0))
E
Elly Jones 已提交
155
        });
156 157 158 159
    }

    #[cfg(target_os = "linux")]
    #[cfg(target_os = "macos")]
U
User Jyyou 已提交
160
    #[cfg(target_os = "freebsd")]
161 162
    fn mkdir(_p: path, _mode: ctypes::c_int) -> bool {
        ret str::as_buf(_p, {|buf| os::libc::mkdir(buf, _mode) == 0i32 });
163 164 165
    }
}

166 167 168 169 170
/*
Function: list_dir

Lists the contents of a directory.
*/
171
fn list_dir(p: path) -> [str] {
172
    let p = p;
173
    let pl = str::len_bytes(p);
B
Brian Anderson 已提交
174
    if pl == 0u || p[pl - 1u] as char != os_fs::path_sep { p += path_sep(); }
B
Brian Anderson 已提交
175 176 177 178
    let full_paths: [str] = [];
    for filename: str in os_fs::list_dir(p) {
        if !str::eq(filename, ".") {
            if !str::eq(filename, "..") { full_paths += [p + filename]; }
179 180 181
        }
    }
    ret full_paths;
182
}
183

184 185 186 187 188 189 190 191 192 193
/*
Function: remove_dir

Removes a directory at the specified path.
*/
fn remove_dir(p: path) -> bool {
   ret rmdir(p);

    #[cfg(target_os = "win32")]
    fn rmdir(_p: path) -> bool {
194
        ret str::as_buf(_p, {|buf| os::kernel32::RemoveDirectoryA(buf)});
195 196 197 198
    }

    #[cfg(target_os = "linux")]
    #[cfg(target_os = "macos")]
U
User Jyyou 已提交
199
    #[cfg(target_os = "freebsd")]
200
    fn rmdir(_p: path) -> bool {
201
        ret str::as_buf(_p, {|buf| os::libc::rmdir(buf) == 0i32 });
202 203 204
    }
}

E
Elly Jones 已提交
205 206 207 208 209
fn change_dir(p: path) -> bool {
    ret chdir(p);

    #[cfg(target_os = "win32")]
    fn chdir(_p: path) -> bool {
N
Niko Matsakis 已提交
210
        ret str::as_buf(_p, {|buf| os::kernel32::SetCurrentDirectoryA(buf)});
E
Elly Jones 已提交
211 212 213 214
    }

    #[cfg(target_os = "linux")]
    #[cfg(target_os = "macos")]
U
User Jyyou 已提交
215
    #[cfg(target_os = "freebsd")]
E
Elly Jones 已提交
216 217 218 219 220
    fn chdir(_p: path) -> bool {
        ret str::as_buf(_p, {|buf| os::libc::chdir(buf) == 0i32 });
    }
}

221 222 223 224 225 226 227 228
/*
Function: path_is_absolute

Indicates whether a path is absolute.

A path is considered absolute if it begins at the filesystem root ("/") or,
on Windows, begins with a drive letter.
*/
229
fn path_is_absolute(p: path) -> bool { ret os_fs::path_is_absolute(p); }
230

231 232
// FIXME: under Windows, we should prepend the current drive letter to paths
// that start with a slash.
233 234 235 236 237 238 239 240 241
/*
Function: make_absolute

Convert a relative path to an absolute path

If the given path is relative, return it prepended with the current working
directory. If the given path is already an absolute path, return it
as is.
*/
242
fn make_absolute(p: path) -> path {
B
Brian Anderson 已提交
243
    if path_is_absolute(p) { ret p; } else { ret connect(getcwd(), p); }
244 245
}

246 247 248 249 250 251 252 253 254 255
/*
Function: split

Split a path into it's individual components

Splits a given path by path separators and returns a vector containing
each piece of the path. On Windows, if the path is absolute then
the first element of the returned vector will be the drive letter
followed by a colon.
*/
B
Brian Anderson 已提交
256
fn split(p: path) -> [path] {
K
Kevin Cantu 已提交
257 258
    // FIXME: use UTF-8 safe str, and/or various other string formats
    let split1 = str::split_byte(p, os_fs::path_sep as u8);
B
Brian Anderson 已提交
259 260
    let split2 = [];
    for s in split1 {
K
Kevin Cantu 已提交
261
        split2 += str::split_byte(s, os_fs::alt_path_sep as u8);
B
Brian Anderson 已提交
262
    }
K
Kevin Cantu 已提交
263 264 265 266

    // filter out ""
    let split3 = vec::filter(split2, {|seg| "" != seg});
    ret split3;
B
Brian Anderson 已提交
267 268
}

B
Brian Anderson 已提交
269 270 271 272 273 274 275 276 277 278
/*
Function: splitext

Split a path into a pair of strings with the first element being the filename
without the extension and the second being either empty or the file extension
including the period. Leading periods in the basename are ignored.  If the
path includes directory components then they are included in the filename part
of the result pair.
*/
fn splitext(p: path) -> (str, str) {
K
Kevin Cantu 已提交
279
    // FIXME: use UTF-8 safe str, and/or various other string formats
B
Brian Anderson 已提交
280 281
    if str::is_empty(p) { ("", "") }
    else {
K
Kevin Cantu 已提交
282
        let parts = str::split_byte(p, '.' as u8);
B
Brian Anderson 已提交
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
        if vec::len(parts) > 1u {
            let base = str::connect(vec::init(parts), ".");
            let ext = "." + option::get(vec::last(parts));

            fn is_dotfile(base: str) -> bool {
                str::is_empty(base)
                    || str::ends_with(
                        base, str::from_char(os_fs::path_sep))
                    || str::ends_with(
                        base, str::from_char(os_fs::alt_path_sep))
            }

            fn ext_contains_sep(ext: str) -> bool {
                vec::len(split(ext)) > 1u
            }

            fn no_basename(ext: str) -> bool {
                str::ends_with(
                    ext, str::from_char(os_fs::path_sep))
                    || str::ends_with(
                        ext, str::from_char(os_fs::alt_path_sep))
            }

            if is_dotfile(base)
                || ext_contains_sep(ext)
                || no_basename(ext) {
                (p, "")
            } else {
                (base, ext)
            }
        } else {
            (p, "")
        }
    }
}

319 320 321 322 323 324 325
/*
Function: normalize

Removes extra "." and ".." entries from paths.

Does not follow symbolic links.
*/
B
Brian Anderson 已提交
326 327 328 329 330 331 332 333 334 335 336 337 338
fn normalize(p: path) -> path {
    let s = split(p);
    let s = strip_dots(s);
    let s = rollup_doubledots(s);

    let s = if check vec::is_not_empty(s) {
        connect_many(s)
    } else {
        ""
    };
    let s = reabsolute(p, s);
    let s = reterminate(p, s);

339
    let s = if str::len_bytes(s) == 0u {
B
Brian Anderson 已提交
340 341 342 343 344 345 346 347
        "."
    } else {
        s
    };

    ret s;

    fn strip_dots(s: [path]) -> [path] {
348
        vec::filter_map(s, { |elem|
B
Brian Anderson 已提交
349 350 351 352 353
            if elem == "." {
                option::none
            } else {
                option::some(elem)
            }
354
        })
B
Brian Anderson 已提交
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
    }

    fn rollup_doubledots(s: [path]) -> [path] {
        if vec::is_empty(s) {
            ret [];
        }

        let t = [];
        let i = vec::len(s);
        let skip = 0;
        do {
            i -= 1u;
            if s[i] == ".." {
                skip += 1;
            } else {
                if skip == 0 {
                    t += [s[i]];
                } else {
                    skip -= 1;
                }
            }
        } while i != 0u;
        let t = vec::reversed(t);
        while skip > 0 {
            t += [".."];
            skip -= 1;
        }
        ret t;
    }

385 386
    #[cfg(target_os = "linux")]
    #[cfg(target_os = "macos")]
U
User Jyyou 已提交
387
    #[cfg(target_os = "freebsd")]
B
Brian Anderson 已提交
388 389 390 391 392 393 394 395
    fn reabsolute(orig: path, new: path) -> path {
        if path_is_absolute(orig) {
            path_sep() + new
        } else {
            new
        }
    }

396 397 398 399 400 401 402 403 404
    #[cfg(target_os = "win32")]
    fn reabsolute(orig: path, new: path) -> path {
       if path_is_absolute(orig) && orig[0] == os_fs::path_sep as u8 {
           str::from_char(os_fs::path_sep) + new
       } else {
           new
       }
    }

B
Brian Anderson 已提交
405
    fn reterminate(orig: path, new: path) -> path {
406
        let last = orig[str::len_bytes(orig) - 1u];
B
Brian Anderson 已提交
407 408 409 410 411 412 413 414 415
        if last == os_fs::path_sep as u8
            || last == os_fs::path_sep as u8 {
            ret new + path_sep();
        } else {
            ret new;
        }
    }
}

B
Brian Anderson 已提交
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
/*
Function: homedir

Returns the path to the user's home directory, if known.

On Unix, returns the value of the "HOME" environment variable if it is set and
not equal to the empty string.

On Windows, returns the value of the "HOME" environment variable if it is set
and not equal to the empty string. Otherwise, returns the value of the
"USERPROFILE" environment variable if it is set and not equal to the empty
string.

Otherwise, homedir returns option::none.
*/
fn homedir() -> option<path> {
    ret alt generic_os::getenv("HOME") {
        some(p) {
B
Brian Anderson 已提交
434
            if !str::is_empty(p) {
B
Brian Anderson 已提交
435 436
                some(p)
            } else {
B
Brian Anderson 已提交
437 438 439
                secondary()
            }
        }
440
        none {
B
Brian Anderson 已提交
441 442
            secondary()
        }
B
Brian Anderson 已提交
443 444 445 446 447 448 449 450 451 452 453 454 455 456
    };

    #[cfg(target_os = "linux")]
    #[cfg(target_os = "macos")]
    #[cfg(target_os = "freebsd")]
    fn secondary() -> option<path> {
        none
    }

    #[cfg(target_os = "win32")]
    fn secondary() -> option<path> {
        option::maybe(none, generic_os::getenv("USERPROFILE")) {|p|
            if !str::is_empty(p) {
                some(p)
B
Brian Anderson 已提交
457 458 459
            } else {
                none
            }
B
Brian Anderson 已提交
460 461 462 463
        }
    }
}

464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
#[cfg(test)]
mod tests {
    #[test]
    fn test_connect() {
        let slash = fs::path_sep();
        log(error, fs::connect("a", "b"));
        assert (fs::connect("a", "b") == "a" + slash + "b");
        assert (fs::connect("a" + slash, "b") == "a" + slash + "b");
    }

    // Issue #712
    #[test]
    fn test_list_dir_no_invalid_memory_access() { fs::list_dir("."); }

    #[test]
    fn list_dir() {
        let dirs = fs::list_dir(".");
        // Just assuming that we've got some contents in the current directory
        assert (vec::len(dirs) > 0u);

        for dir in dirs { log(debug, dir); }
    }

    #[test]
    fn path_is_dir() {
        assert (fs::path_is_dir("."));
        assert (!fs::path_is_dir("test/stdtest/fs.rs"));
    }

    #[test]
    fn path_exists() {
        assert (fs::path_exists("."));
        assert (!fs::path_exists("test/nonexistent-bogus-path"));
    }

    fn ps() -> str {
        fs::path_sep()
    }

    fn aps() -> str {
        "/"
    }

    #[test]
    fn split1() {
        let actual = fs::split("a" + ps() + "b");
        let expected = ["a", "b"];
        assert actual == expected;
    }

    #[test]
    fn split2() {
        let actual = fs::split("a" + aps() + "b");
        let expected = ["a", "b"];
        assert actual == expected;
    }

    #[test]
    fn split3() {
        let actual = fs::split(ps() + "a" + ps() + "b");
        let expected = ["a", "b"];
        assert actual == expected;
    }

    #[test]
    fn split4() {
        let actual = fs::split("a" + ps() + "b" + aps() + "c");
        let expected = ["a", "b", "c"];
        assert actual == expected;
    }

    #[test]
    fn normalize1() {
        let actual = fs::normalize("a/b/..");
        let expected = "a";
        assert actual == expected;
    }

    #[test]
    fn normalize2() {
        let actual = fs::normalize("/a/b/..");
        let expected = "/a";
        assert actual == expected;
    }

    #[test]
    fn normalize3() {
        let actual = fs::normalize("a/../b");
        let expected = "b";
        assert actual == expected;
    }

    #[test]
    fn normalize4() {
        let actual = fs::normalize("/a/../b");
        let expected = "/b";
        assert actual == expected;
    }

    #[test]
    fn normalize5() {
        let actual = fs::normalize("a/.");
        let expected = "a";
        assert actual == expected;
    }

    #[test]
    fn normalize6() {
        let actual = fs::normalize("a/./b/");
        let expected = "a/b/";
        assert actual == expected;
    }

    #[test]
    fn normalize7() {
        let actual = fs::normalize("a/..");
        let expected = ".";
        assert actual == expected;
    }

    #[test]
    fn normalize8() {
        let actual = fs::normalize("../../..");
        let expected = "../../..";
        assert actual == expected;
    }

    #[test]
    fn normalize9() {
        let actual = fs::normalize("a/b/../../..");
        let expected = "..";
        assert actual == expected;
    }

    #[test]
    fn normalize10() {
        let actual = fs::normalize("/a/b/c/../d/./../../e/");
        let expected = "/a/e/";
        log(error, actual);
        assert actual == expected;
    }

    #[test]
    fn normalize11() {
        let actual = fs::normalize("/a/..");
        let expected = "/";
        assert actual == expected;
    }

    #[test]
    #[cfg(target_os = "win32")]
    fn normalize12() {
        let actual = fs::normalize("C:/whatever");
        let expected = "C:/whatever";
        log(error, actual);
        assert actual == expected;
    }

    #[test]
    #[cfg(target_os = "win32")]
    fn path_is_absolute_win32() {
        assert fs::path_is_absolute("C:/whatever");
    }

    #[test]
    fn splitext_empty() {
        let (base, ext) = fs::splitext("");
        assert base == "";
        assert ext == "";
    }

    #[test]
    fn splitext_ext() {
        let (base, ext) = fs::splitext("grum.exe");
        assert base == "grum";
        assert ext == ".exe";
    }

    #[test]
    fn splitext_noext() {
        let (base, ext) = fs::splitext("grum");
        assert base == "grum";
        assert ext == "";
    }

    #[test]
    fn splitext_dotfile() {
        let (base, ext) = fs::splitext(".grum");
        assert base == ".grum";
        assert ext == "";
    }

    #[test]
    fn splitext_path_ext() {
        let (base, ext) = fs::splitext("oh/grum.exe");
        assert base == "oh/grum";
        assert ext == ".exe";
    }

    #[test]
    fn splitext_path_noext() {
        let (base, ext) = fs::splitext("oh/grum");
        assert base == "oh/grum";
        assert ext == "";
    }

    #[test]
    fn splitext_dot_in_path() {
        let (base, ext) = fs::splitext("oh.my/grum");
        assert base == "oh.my/grum";
        assert ext == "";
    }

    #[test]
    fn splitext_nobasename() {
        let (base, ext) = fs::splitext("oh.my/");
        assert base == "oh.my/";
        assert ext == "";
    }

    #[test]
    #[cfg(target_os = "linux")]
    #[cfg(target_os = "macos")]
    #[cfg(target_os = "freebsd")]
    fn homedir() {
        import getenv = generic_os::getenv;
        import setenv = generic_os::setenv;

        let oldhome = getenv("HOME");

        setenv("HOME", "/home/MountainView");
        assert fs::homedir() == some("/home/MountainView");

        setenv("HOME", "");
        assert fs::homedir() == none;

        option::may(oldhome, {|s| setenv("HOME", s)});
    }

    #[test]
    #[cfg(target_os = "win32")]
    fn homedir() {
        import getenv = generic_os::getenv;
        import setenv = generic_os::setenv;

        let oldhome = getenv("HOME");
        let olduserprofile = getenv("USERPROFILE");

        setenv("HOME", "");
        setenv("USERPROFILE", "");

        assert fs::homedir() == none;

        setenv("HOME", "/home/MountainView");
        assert fs::homedir() == some("/home/MountainView");

        setenv("HOME", "");

        setenv("USERPROFILE", "/home/MountainView");
        assert fs::homedir() == some("/home/MountainView");

        setenv("USERPROFILE", "/home/MountainView");
        assert fs::homedir() == some("/home/MountainView");

        setenv("HOME", "/home/MountainView");
        setenv("USERPROFILE", "/home/PaloAlto");
        assert fs::homedir() == some("/home/MountainView");

        option::may(oldhome, {|s| setenv("HOME", s)});
        option::may(olduserprofile, {|s| setenv("USERPROFILE", s)});
    }
}


#[test]
fn test() {
    assert (!fs::path_is_absolute("test-path"));

    log(debug, "Current working directory: " + os::getcwd());

    log(debug, fs::make_absolute("test-path"));
    log(debug, fs::make_absolute("/usr/bin"));
}


749 750 751 752 753 754 755
// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End: