std: Add fs::homedir

Returns the home directory of the user as appropriate for the platform.

Issue #1359
This commit is contained in:
Brian Anderson 2012-01-06 11:55:43 -08:00
parent 2f4c9315af
commit 74c825e385
2 changed files with 100 additions and 0 deletions

View File

@ -399,6 +399,54 @@ fn normalize(p: path) -> path {
}
}
/*
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) {
if !str::is_empty(p) {
some(p)
} else {
secondary()
}
}
none. {
secondary()
}
};
#[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)
} else {
none
}
}
}
}
// Local Variables:
// mode: rust;
// fill-column: 78;

View File

@ -221,3 +221,55 @@ fn splitext_nobasename() {
assert base == "oh.my/";
assert ext == "";
}
#[test]
#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
fn homedir() {
import getenv = std::generic_os::getenv;
import setenv = std::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 = std::generic_os::getenv;
import setenv = std::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)});
}