提交 a828e794 编写于 作者: A Alex Crichton

std: Tweak the std::env OsString/String interface

This commit tweaks the interface of the `std::env` module to make it more
ergonomic for common usage:

* `env::var` was renamed to `env::var_os`
* `env::var_string` was renamed to `env::var`
* `env::args` was renamed to `env::args_os`
* `env::args` was re-added as a panicking iterator over string values
* `env::vars` was renamed to `env::vars_os`
* `env::vars` was re-added as a panicking iterator over string values.

This should make common usage (e.g. unicode values everywhere) more ergonomic
as well as "the default". This is also a breaking change due to the differences
of what's yielded from each of these functions, but migration should be fairly
easy as the defaults operate over `String` which is a common type to use.

[breaking-change]
上级 446bc899
...@@ -14,7 +14,6 @@ ...@@ -14,7 +14,6 @@
#![feature(collections)] #![feature(collections)]
#![feature(int_uint)] #![feature(int_uint)]
#![feature(io)] #![feature(io)]
#![feature(os)]
#![feature(path)] #![feature(path)]
#![feature(rustc_private)] #![feature(rustc_private)]
#![feature(slicing_syntax, unboxed_closures)] #![feature(slicing_syntax, unboxed_closures)]
...@@ -48,8 +47,7 @@ ...@@ -48,8 +47,7 @@
pub mod errors; pub mod errors;
pub fn main() { pub fn main() {
let args = env::args().map(|s| s.into_string().unwrap()).collect();; let config = parse_config(env::args().collect());
let config = parse_config(args);
if config.valgrind_path.is_none() && config.force_valgrind { if config.valgrind_path.is_none() && config.force_valgrind {
panic!("Can't find Valgrind to run Valgrind tests"); panic!("Can't find Valgrind to run Valgrind tests");
......
...@@ -40,7 +40,7 @@ pub fn make_new_path(path: &str) -> String { ...@@ -40,7 +40,7 @@ pub fn make_new_path(path: &str) -> String {
// Windows just uses PATH as the library search path, so we have to // Windows just uses PATH as the library search path, so we have to
// maintain the current value while adding our own // maintain the current value while adding our own
match env::var_string(lib_path_env_var()) { match env::var(lib_path_env_var()) {
Ok(curr) => { Ok(curr) => {
format!("{}{}{}", path, path_div(), curr) format!("{}{}{}", path, path_div(), curr)
} }
......
...@@ -397,7 +397,7 @@ fn enabled(level: u32, ...@@ -397,7 +397,7 @@ fn enabled(level: u32,
/// This is not threadsafe at all, so initialization is performed through a /// This is not threadsafe at all, so initialization is performed through a
/// `Once` primitive (and this function is called from that primitive). /// `Once` primitive (and this function is called from that primitive).
fn init() { fn init() {
let (mut directives, filter) = match env::var_string("RUST_LOG") { let (mut directives, filter) = match env::var("RUST_LOG") {
Ok(spec) => directive::parse_logging_spec(&spec[]), Ok(spec) => directive::parse_logging_spec(&spec[]),
Err(..) => (Vec::new(), None), Err(..) => (Vec::new(), None),
}; };
......
...@@ -207,7 +207,7 @@ fn canonicalize(path: Option<Path>) -> Option<Path> { ...@@ -207,7 +207,7 @@ fn canonicalize(path: Option<Path>) -> Option<Path> {
/// Returns RUST_PATH as a string, without default paths added /// Returns RUST_PATH as a string, without default paths added
pub fn get_rust_path() -> Option<String> { pub fn get_rust_path() -> Option<String> {
env::var_string("RUST_PATH").ok() env::var("RUST_PATH").ok()
} }
/// Returns the value of RUST_PATH, as a list /// Returns the value of RUST_PATH, as a list
......
...@@ -61,13 +61,13 @@ pub fn maybe_print_constraints_for<'a, 'tcx>(region_vars: &RegionVarBindings<'a, ...@@ -61,13 +61,13 @@ pub fn maybe_print_constraints_for<'a, 'tcx>(region_vars: &RegionVarBindings<'a,
} }
let requested_node : Option<ast::NodeId> = let requested_node : Option<ast::NodeId> =
env::var_string("RUST_REGION_GRAPH_NODE").ok().and_then(|s| s.parse().ok()); env::var("RUST_REGION_GRAPH_NODE").ok().and_then(|s| s.parse().ok());
if requested_node.is_some() && requested_node != Some(subject_node) { if requested_node.is_some() && requested_node != Some(subject_node) {
return; return;
} }
let requested_output = env::var_string("RUST_REGION_GRAPH").ok(); let requested_output = env::var("RUST_REGION_GRAPH").ok();
debug!("requested_output: {:?} requested_node: {:?}", debug!("requested_output: {:?} requested_node: {:?}",
requested_output, requested_node); requested_output, requested_node);
......
...@@ -1052,7 +1052,7 @@ pub fn get_unstable_features_setting() -> UnstableFeatures { ...@@ -1052,7 +1052,7 @@ pub fn get_unstable_features_setting() -> UnstableFeatures {
// subverting the unstable features lints // subverting the unstable features lints
let bootstrap_secret_key = option_env!("CFG_BOOTSTRAP_KEY"); let bootstrap_secret_key = option_env!("CFG_BOOTSTRAP_KEY");
// The matching key to the above, only known by the build system // The matching key to the above, only known by the build system
let bootstrap_provided_key = env::var_string("RUSTC_BOOTSTRAP_KEY").ok(); let bootstrap_provided_key = env::var("RUSTC_BOOTSTRAP_KEY").ok();
match (disable_unstable_features, bootstrap_secret_key, bootstrap_provided_key) { match (disable_unstable_features, bootstrap_secret_key, bootstrap_provided_key) {
(_, Some(ref s), Some(ref p)) if s == p => UnstableFeatures::Cheat, (_, Some(ref s), Some(ref p)) if s == p => UnstableFeatures::Cheat,
(true, _, _) => UnstableFeatures::Disallow, (true, _, _) => UnstableFeatures::Disallow,
......
...@@ -384,7 +384,7 @@ fn load_file(path: &Path) -> Result<Target, String> { ...@@ -384,7 +384,7 @@ fn load_file(path: &Path) -> Result<Target, String> {
Path::new(target) Path::new(target)
}; };
let target_path = env::var("RUST_TARGET_PATH") let target_path = env::var_os("RUST_TARGET_PATH")
.unwrap_or(OsString::from_str("")); .unwrap_or(OsString::from_str(""));
// FIXME 16351: add a sane default search path? // FIXME 16351: add a sane default search path?
......
...@@ -464,7 +464,7 @@ pub fn phase_2_configure_and_expand(sess: &Session, ...@@ -464,7 +464,7 @@ pub fn phase_2_configure_and_expand(sess: &Session,
// compiler, not for the target. // compiler, not for the target.
let mut _old_path = OsString::from_str(""); let mut _old_path = OsString::from_str("");
if cfg!(windows) { if cfg!(windows) {
_old_path = env::var("PATH").unwrap_or(_old_path); _old_path = env::var_os("PATH").unwrap_or(_old_path);
let mut new_path = sess.host_filesearch(PathKind::All).get_dylib_search_paths(); let mut new_path = sess.host_filesearch(PathKind::All).get_dylib_search_paths();
new_path.extend(env::split_paths(&_old_path)); new_path.extend(env::split_paths(&_old_path));
env::set_var("PATH", &env::join_paths(new_path.iter()).unwrap()); env::set_var("PATH", &env::join_paths(new_path.iter()).unwrap());
...@@ -737,7 +737,7 @@ pub fn phase_5_run_llvm_passes(sess: &Session, ...@@ -737,7 +737,7 @@ pub fn phase_5_run_llvm_passes(sess: &Session,
pub fn phase_6_link_output(sess: &Session, pub fn phase_6_link_output(sess: &Session,
trans: &trans::CrateTranslation, trans: &trans::CrateTranslation,
outputs: &OutputFilenames) { outputs: &OutputFilenames) {
let old_path = env::var("PATH").unwrap_or(OsString::from_str("")); let old_path = env::var_os("PATH").unwrap_or(OsString::from_str(""));
let mut new_path = sess.host_filesearch(PathKind::All).get_tools_search_paths(); let mut new_path = sess.host_filesearch(PathKind::All).get_tools_search_paths();
new_path.extend(env::split_paths(&old_path)); new_path.extend(env::split_paths(&old_path));
env::set_var("PATH", &env::join_paths(new_path.iter()).unwrap()); env::set_var("PATH", &env::join_paths(new_path.iter()).unwrap());
......
...@@ -771,7 +771,7 @@ pub fn monitor<F:FnOnce()+Send>(f: F) { ...@@ -771,7 +771,7 @@ pub fn monitor<F:FnOnce()+Send>(f: F) {
// FIXME: Hacks on hacks. If the env is trying to override the stack size // FIXME: Hacks on hacks. If the env is trying to override the stack size
// then *don't* set it explicitly. // then *don't* set it explicitly.
if env::var("RUST_MIN_STACK").is_none() { if env::var_os("RUST_MIN_STACK").is_none() {
cfg = cfg.stack_size(STACK_SIZE); cfg = cfg.stack_size(STACK_SIZE);
} }
...@@ -835,8 +835,7 @@ pub fn diagnostics_registry() -> diagnostics::registry::Registry { ...@@ -835,8 +835,7 @@ pub fn diagnostics_registry() -> diagnostics::registry::Registry {
} }
pub fn main() { pub fn main() {
let args = env::args().map(|s| s.into_string().unwrap()); let result = run(env::args().collect());
let result = run(args.collect());
std::env::set_exit_status(result as i32); std::env::set_exit_status(result as i32);
} }
...@@ -1551,7 +1551,7 @@ pub fn process_crate(sess: &Session, ...@@ -1551,7 +1551,7 @@ pub fn process_crate(sess: &Session,
info!("Dumping crate {}", cratename); info!("Dumping crate {}", cratename);
// find a path to dump our data to // find a path to dump our data to
let mut root_path = match env::var_string("DXR_RUST_TEMP_FOLDER") { let mut root_path = match env::var("DXR_RUST_TEMP_FOLDER") {
Ok(val) => Path::new(val), Ok(val) => Path::new(val),
Err(..) => match odir { Err(..) => match odir {
Some(val) => val.join("dxr"), Some(val) => val.join("dxr"),
......
...@@ -122,10 +122,10 @@ struct Output { ...@@ -122,10 +122,10 @@ struct Output {
} }
pub fn main() { pub fn main() {
static STACK_SIZE: uint = 32000000; // 32MB const STACK_SIZE: usize = 32000000; // 32MB
let res = std::thread::Builder::new().stack_size(STACK_SIZE).scoped(move || { let res = std::thread::Builder::new().stack_size(STACK_SIZE).scoped(move || {
let s = env::args().map(|s| s.into_string().unwrap()); let s = env::args().collect::<Vec<_>>();
main_args(&s.collect::<Vec<_>>()) main_args(&s)
}).join(); }).join();
env::set_exit_status(res.ok().unwrap() as i32); env::set_exit_status(res.ok().unwrap() as i32);
} }
......
...@@ -101,7 +101,7 @@ fn separator() -> u8 { ...@@ -101,7 +101,7 @@ fn separator() -> u8 {
/// Returns the current search path for dynamic libraries being used by this /// Returns the current search path for dynamic libraries being used by this
/// process /// process
pub fn search_path() -> Vec<Path> { pub fn search_path() -> Vec<Path> {
match env::var(DynamicLibrary::envvar()) { match env::var_os(DynamicLibrary::envvar()) {
Some(var) => env::split_paths(&var).collect(), Some(var) => env::split_paths(&var).collect(),
None => Vec::new(), None => Vec::new(),
} }
......
...@@ -71,17 +71,29 @@ pub fn set_current_dir(p: &Path) -> IoResult<()> { ...@@ -71,17 +71,29 @@ pub fn set_current_dir(p: &Path) -> IoResult<()> {
/// An iterator over a snapshot of the environment variables of this process. /// An iterator over a snapshot of the environment variables of this process.
/// ///
/// This iterator is created through `std::env::vars()` and yields `(OsString, /// This iterator is created through `std::env::vars()` and yields `(String,
/// OsString)` pairs. /// String)` pairs.
pub struct Vars { inner: os_imp::Env } pub struct Vars { inner: VarsOs }
/// Returns an iterator of (variable, value) pairs, for all the environment /// An iterator over a snapshot of the environment variables of this process.
/// variables of the current process. ///
/// This iterator is created through `std::env::vars_os()` and yields
/// `(OsString, OsString)` pairs.
pub struct VarsOs { inner: os_imp::Env }
/// Returns an iterator of (variable, value) pairs of strings, for all the
/// environment variables of the current process.
/// ///
/// The returned iterator contains a snapshot of the process's environment /// The returned iterator contains a snapshot of the process's environment
/// variables at the time of this invocation, modifications to environment /// variables at the time of this invocation, modifications to environment
/// variables afterwards will not be reflected in the returned iterator. /// variables afterwards will not be reflected in the returned iterator.
/// ///
/// # Panics
///
/// While iterating, the returned iterator will panic if any key or value in the
/// environment is not valid unicode. If this is not desired, consider using the
/// `env::vars_os` function.
///
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
...@@ -90,37 +102,50 @@ pub struct Vars { inner: os_imp::Env } ...@@ -90,37 +102,50 @@ pub struct Vars { inner: os_imp::Env }
/// // We will iterate through the references to the element returned by /// // We will iterate through the references to the element returned by
/// // env::vars(); /// // env::vars();
/// for (key, value) in env::vars() { /// for (key, value) in env::vars() {
/// println!("{:?}: {:?}", key, value); /// println!("{}: {}", key, value);
/// } /// }
/// ``` /// ```
pub fn vars() -> Vars { pub fn vars() -> Vars {
let _g = ENV_LOCK.lock(); Vars { inner: vars_os() }
Vars { inner: os_imp::env() }
}
impl Iterator for Vars {
type Item = (OsString, OsString);
fn next(&mut self) -> Option<(OsString, OsString)> { self.inner.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
} }
/// Fetches the environment variable `key` from the current process, returning /// Returns an iterator of (variable, value) pairs of OS strings, for all the
/// None if the variable isn't set. /// environment variables of the current process.
///
/// The returned iterator contains a snapshot of the process's environment
/// variables at the time of this invocation, modifications to environment
/// variables afterwards will not be reflected in the returned iterator.
/// ///
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
/// use std::env; /// use std::env;
/// ///
/// let key = "HOME"; /// // We will iterate through the references to the element returned by
/// match env::var(key) { /// // env::vars_os();
/// Some(val) => println!("{}: {:?}", key, val), /// for (key, value) in env::vars_os() {
/// None => println!("{} is not defined in the environment.", key) /// println!("{:?}: {:?}", key, value);
/// } /// }
/// ``` /// ```
pub fn var<K: ?Sized>(key: &K) -> Option<OsString> where K: AsOsStr { pub fn vars_os() -> VarsOs {
let _g = ENV_LOCK.lock(); let _g = ENV_LOCK.lock();
os_imp::getenv(key.as_os_str()) VarsOs { inner: os_imp::env() }
}
impl Iterator for Vars {
type Item = (String, String);
fn next(&mut self) -> Option<(String, String)> {
self.inner.next().map(|(a, b)| {
(a.into_string().unwrap(), b.into_string().unwrap())
})
}
fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
}
impl Iterator for VarsOs {
type Item = (OsString, OsString);
fn next(&mut self) -> Option<(OsString, OsString)> { self.inner.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
} }
/// Fetches the environment variable `key` from the current process. /// Fetches the environment variable `key` from the current process.
...@@ -135,18 +160,37 @@ pub fn var<K: ?Sized>(key: &K) -> Option<OsString> where K: AsOsStr { ...@@ -135,18 +160,37 @@ pub fn var<K: ?Sized>(key: &K) -> Option<OsString> where K: AsOsStr {
/// use std::env; /// use std::env;
/// ///
/// let key = "HOME"; /// let key = "HOME";
/// match env::var_string(key) { /// match env::var(key) {
/// Ok(val) => println!("{}: {:?}", key, val), /// Ok(val) => println!("{}: {:?}", key, val),
/// Err(e) => println!("couldn't interpret {}: {}", key, e), /// Err(e) => println!("couldn't interpret {}: {}", key, e),
/// } /// }
/// ``` /// ```
pub fn var_string<K: ?Sized>(key: &K) -> Result<String, VarError> where K: AsOsStr { pub fn var<K: ?Sized>(key: &K) -> Result<String, VarError> where K: AsOsStr {
match var(key) { match var_os(key) {
Some(s) => s.into_string().map_err(VarError::NotUnicode), Some(s) => s.into_string().map_err(VarError::NotUnicode),
None => Err(VarError::NotPresent) None => Err(VarError::NotPresent)
} }
} }
/// Fetches the environment variable `key` from the current process, returning
/// None if the variable isn't set.
///
/// # Example
///
/// ```rust
/// use std::env;
///
/// let key = "HOME";
/// match env::var_os(key) {
/// Some(val) => println!("{}: {:?}", key, val),
/// None => println!("{} is not defined in the environment.", key)
/// }
/// ```
pub fn var_os<K: ?Sized>(key: &K) -> Option<OsString> where K: AsOsStr {
let _g = ENV_LOCK.lock();
os_imp::getenv(key.as_os_str())
}
/// Possible errors from the `env::var` method. /// Possible errors from the `env::var` method.
#[derive(Debug, PartialEq, Eq, Clone)] #[derive(Debug, PartialEq, Eq, Clone)]
pub enum VarError { pub enum VarError {
...@@ -190,7 +234,7 @@ fn description(&self) -> &str { ...@@ -190,7 +234,7 @@ fn description(&self) -> &str {
/// ///
/// let key = "KEY"; /// let key = "KEY";
/// env::set_var(key, "VALUE"); /// env::set_var(key, "VALUE");
/// assert_eq!(env::var_string(key), Ok("VALUE".to_string())); /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
/// ``` /// ```
pub fn set_var<K: ?Sized, V: ?Sized>(k: &K, v: &V) pub fn set_var<K: ?Sized, V: ?Sized>(k: &K, v: &V)
where K: AsOsStr, V: AsOsStr where K: AsOsStr, V: AsOsStr
...@@ -222,7 +266,7 @@ pub struct SplitPaths<'a> { inner: os_imp::SplitPaths<'a> } ...@@ -222,7 +266,7 @@ pub struct SplitPaths<'a> { inner: os_imp::SplitPaths<'a> }
/// use std::env; /// use std::env;
/// ///
/// let key = "PATH"; /// let key = "PATH";
/// match env::var(key) { /// match env::var_os(key) {
/// Some(paths) => { /// Some(paths) => {
/// for path in env::split_paths(&paths) { /// for path in env::split_paths(&paths) {
/// println!("'{}'", path.display()); /// println!("'{}'", path.display());
...@@ -262,7 +306,7 @@ pub struct JoinPathsError { ...@@ -262,7 +306,7 @@ pub struct JoinPathsError {
/// ```rust /// ```rust
/// use std::env; /// use std::env;
/// ///
/// if let Some(path) = env::var("PATH") { /// if let Some(path) = env::var_os("PATH") {
/// let mut paths = env::split_paths(&path).collect::<Vec<_>>(); /// let mut paths = env::split_paths(&path).collect::<Vec<_>>();
/// paths.push(Path::new("/home/xyz/bin")); /// paths.push(Path::new("/home/xyz/bin"));
/// let new_path = env::join_paths(paths.iter()).unwrap(); /// let new_path = env::join_paths(paths.iter()).unwrap();
...@@ -376,11 +420,17 @@ pub fn get_exit_status() -> i32 { ...@@ -376,11 +420,17 @@ pub fn get_exit_status() -> i32 {
EXIT_STATUS.load(Ordering::SeqCst) as i32 EXIT_STATUS.load(Ordering::SeqCst) as i32
} }
/// An iterator over the arguments of a process, yielding an `OsString` value /// An iterator over the arguments of a process, yielding an `String` value
/// for each argument. /// for each argument.
/// ///
/// This structure is created through the `std::env::args` method. /// This structure is created through the `std::env::args` method.
pub struct Args { inner: os_imp::Args } pub struct Args { inner: ArgsOs }
/// An iterator over the arguments of a process, yielding an `OsString` value
/// for each argument.
///
/// This structure is created through the `std::env::args_os` method.
pub struct ArgsOs { inner: os_imp::Args }
/// Returns the arguments which this program was started with (normally passed /// Returns the arguments which this program was started with (normally passed
/// via the command line). /// via the command line).
...@@ -389,6 +439,12 @@ pub struct Args { inner: os_imp::Args } ...@@ -389,6 +439,12 @@ pub struct Args { inner: os_imp::Args }
/// set to arbitrary text, and it may not even exist, so this property should /// set to arbitrary text, and it may not even exist, so this property should
/// not be relied upon for security purposes. /// not be relied upon for security purposes.
/// ///
/// # Panics
///
/// The returned iterator will panic during iteration if any argument to the
/// process is not valid unicode. If this is not desired it is recommended to
/// use the `args_os` function instead.
///
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
...@@ -396,14 +452,43 @@ pub struct Args { inner: os_imp::Args } ...@@ -396,14 +452,43 @@ pub struct Args { inner: os_imp::Args }
/// ///
/// // Prints each argument on a separate line /// // Prints each argument on a separate line
/// for argument in env::args() { /// for argument in env::args() {
/// println!("{:?}", argument); /// println!("{}", argument);
/// } /// }
/// ``` /// ```
pub fn args() -> Args { pub fn args() -> Args {
Args { inner: os_imp::args() } Args { inner: args_os() }
}
/// Returns the arguments which this program was started with (normally passed
/// via the command line).
///
/// The first element is traditionally the path to the executable, but it can be
/// set to arbitrary text, and it may not even exist, so this property should
/// not be relied upon for security purposes.
///
/// # Example
///
/// ```rust
/// use std::env;
///
/// // Prints each argument on a separate line
/// for argument in env::args_os() {
/// println!("{:?}", argument);
/// }
/// ```
pub fn args_os() -> ArgsOs {
ArgsOs { inner: os_imp::args() }
} }
impl Iterator for Args { impl Iterator for Args {
type Item = String;
fn next(&mut self) -> Option<String> {
self.inner.next().map(|s| s.into_string().unwrap())
}
fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
}
impl Iterator for ArgsOs {
type Item = OsString; type Item = OsString;
fn next(&mut self) -> Option<OsString> { self.inner.next() } fn next(&mut self) -> Option<OsString> { self.inner.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() } fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
...@@ -706,7 +791,7 @@ fn make_rand_name() -> OsString { ...@@ -706,7 +791,7 @@ fn make_rand_name() -> OsString {
let n = format!("TEST{}", rng.gen_ascii_chars().take(10) let n = format!("TEST{}", rng.gen_ascii_chars().take(10)
.collect::<String>()); .collect::<String>());
let n = OsString::from_string(n); let n = OsString::from_string(n);
assert!(var(&n).is_none()); assert!(var_os(&n).is_none());
n n
} }
...@@ -718,7 +803,7 @@ fn eq(a: Option<OsString>, b: Option<&str>) { ...@@ -718,7 +803,7 @@ fn eq(a: Option<OsString>, b: Option<&str>) {
fn test_set_var() { fn test_set_var() {
let n = make_rand_name(); let n = make_rand_name();
set_var(&n, "VALUE"); set_var(&n, "VALUE");
eq(var(&n), Some("VALUE")); eq(var_os(&n), Some("VALUE"));
} }
#[test] #[test]
...@@ -726,7 +811,7 @@ fn test_remove_var() { ...@@ -726,7 +811,7 @@ fn test_remove_var() {
let n = make_rand_name(); let n = make_rand_name();
set_var(&n, "VALUE"); set_var(&n, "VALUE");
remove_var(&n); remove_var(&n);
eq(var(&n), None); eq(var_os(&n), None);
} }
#[test] #[test]
...@@ -734,9 +819,9 @@ fn test_set_var_overwrite() { ...@@ -734,9 +819,9 @@ fn test_set_var_overwrite() {
let n = make_rand_name(); let n = make_rand_name();
set_var(&n, "1"); set_var(&n, "1");
set_var(&n, "2"); set_var(&n, "2");
eq(var(&n), Some("2")); eq(var_os(&n), Some("2"));
set_var(&n, ""); set_var(&n, "");
eq(var(&n), Some("")); eq(var_os(&n), Some(""));
} }
#[test] #[test]
...@@ -749,7 +834,7 @@ fn test_var_big() { ...@@ -749,7 +834,7 @@ fn test_var_big() {
} }
let n = make_rand_name(); let n = make_rand_name();
set_var(&n, s.as_slice()); set_var(&n, s.as_slice());
eq(var(&n), Some(s.as_slice())); eq(var_os(&n), Some(s.as_slice()));
} }
#[test] #[test]
...@@ -767,22 +852,22 @@ fn test_env_set_get_huge() { ...@@ -767,22 +852,22 @@ fn test_env_set_get_huge() {
let n = make_rand_name(); let n = make_rand_name();
let s = repeat("x").take(10000).collect::<String>(); let s = repeat("x").take(10000).collect::<String>();
set_var(&n, &s); set_var(&n, &s);
eq(var(&n), Some(s.as_slice())); eq(var_os(&n), Some(s.as_slice()));
remove_var(&n); remove_var(&n);
eq(var(&n), None); eq(var_os(&n), None);
} }
#[test] #[test]
fn test_env_set_var() { fn test_env_set_var() {
let n = make_rand_name(); let n = make_rand_name();
let mut e = vars(); let mut e = vars_os();
set_var(&n, "VALUE"); set_var(&n, "VALUE");
assert!(!e.any(|(k, v)| { assert!(!e.any(|(k, v)| {
&*k == &*n && &*v == "VALUE" &*k == &*n && &*v == "VALUE"
})); }));
assert!(vars().any(|(k, v)| { assert!(vars_os().any(|(k, v)| {
&*k == &*n && &*v == "VALUE" &*k == &*n && &*v == "VALUE"
})); }));
} }
......
...@@ -125,7 +125,7 @@ pub fn getcwd() -> IoResult<Path> { ...@@ -125,7 +125,7 @@ pub fn getcwd() -> IoResult<Path> {
#[deprecated(since = "1.0.0", reason = "use env::vars instead")] #[deprecated(since = "1.0.0", reason = "use env::vars instead")]
#[unstable(feature = "os")] #[unstable(feature = "os")]
pub fn env() -> Vec<(String,String)> { pub fn env() -> Vec<(String,String)> {
env::vars().map(|(k, v)| { env::vars_os().map(|(k, v)| {
(k.to_string_lossy().into_owned(), v.to_string_lossy().into_owned()) (k.to_string_lossy().into_owned(), v.to_string_lossy().into_owned())
}).collect() }).collect()
} }
...@@ -135,7 +135,7 @@ pub fn env() -> Vec<(String,String)> { ...@@ -135,7 +135,7 @@ pub fn env() -> Vec<(String,String)> {
#[deprecated(since = "1.0.0", reason = "use env::vars instead")] #[deprecated(since = "1.0.0", reason = "use env::vars instead")]
#[unstable(feature = "os")] #[unstable(feature = "os")]
pub fn env_as_bytes() -> Vec<(Vec<u8>, Vec<u8>)> { pub fn env_as_bytes() -> Vec<(Vec<u8>, Vec<u8>)> {
env::vars().map(|(k, v)| (byteify(k), byteify(v))).collect() env::vars_os().map(|(k, v)| (byteify(k), byteify(v))).collect()
} }
/// Fetches the environment variable `n` from the current process, returning /// Fetches the environment variable `n` from the current process, returning
...@@ -159,10 +159,10 @@ pub fn env_as_bytes() -> Vec<(Vec<u8>, Vec<u8>)> { ...@@ -159,10 +159,10 @@ pub fn env_as_bytes() -> Vec<(Vec<u8>, Vec<u8>)> {
/// None => println!("{} is not defined in the environment.", key) /// None => println!("{} is not defined in the environment.", key)
/// } /// }
/// ``` /// ```
#[deprecated(since = "1.0.0", reason = "use env::var or env::var_string instead")] #[deprecated(since = "1.0.0", reason = "use env::var or env::var_os instead")]
#[unstable(feature = "os")] #[unstable(feature = "os")]
pub fn getenv(n: &str) -> Option<String> { pub fn getenv(n: &str) -> Option<String> {
env::var_string(n).ok() env::var(n).ok()
} }
/// Fetches the environment variable `n` byte vector from the current process, /// Fetches the environment variable `n` byte vector from the current process,
...@@ -174,7 +174,7 @@ pub fn getenv(n: &str) -> Option<String> { ...@@ -174,7 +174,7 @@ pub fn getenv(n: &str) -> Option<String> {
#[deprecated(since = "1.0.0", reason = "use env::var instead")] #[deprecated(since = "1.0.0", reason = "use env::var instead")]
#[unstable(feature = "os")] #[unstable(feature = "os")]
pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> { pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
env::var(n).map(byteify) env::var_os(n).map(byteify)
} }
#[cfg(unix)] #[cfg(unix)]
......
...@@ -29,7 +29,7 @@ pub fn log_enabled() -> bool { ...@@ -29,7 +29,7 @@ pub fn log_enabled() -> bool {
_ => {} _ => {}
} }
let val = match env::var("RUST_BACKTRACE") { let val = match env::var_os("RUST_BACKTRACE") {
Some(..) => 2, Some(..) => 2,
None => 1, None => 1,
}; };
......
...@@ -52,7 +52,7 @@ pub fn min_stack() -> uint { ...@@ -52,7 +52,7 @@ pub fn min_stack() -> uint {
0 => {} 0 => {}
n => return n - 1, n => return n - 1,
} }
let amt = env::var_string("RUST_MIN_STACK").ok().and_then(|s| s.parse().ok()); let amt = env::var("RUST_MIN_STACK").ok().and_then(|s| s.parse().ok());
let amt = amt.unwrap_or(2 * 1024 * 1024); let amt = amt.unwrap_or(2 * 1024 * 1024);
// 0 is our sentinel value, so ensure that we'll never see 0 after // 0 is our sentinel value, so ensure that we'll never see 0 after
// initialization has run // initialization has run
...@@ -63,7 +63,7 @@ pub fn min_stack() -> uint { ...@@ -63,7 +63,7 @@ pub fn min_stack() -> uint {
/// Get's the number of scheduler threads requested by the environment /// Get's the number of scheduler threads requested by the environment
/// either `RUST_THREADS` or `num_cpus`. /// either `RUST_THREADS` or `num_cpus`.
pub fn default_sched_threads() -> uint { pub fn default_sched_threads() -> uint {
match env::var_string("RUST_THREADS") { match env::var("RUST_THREADS") {
Ok(nstr) => { Ok(nstr) => {
let opt_n: Option<uint> = nstr.parse().ok(); let opt_n: Option<uint> = nstr.parse().ok();
match opt_n { match opt_n {
......
...@@ -30,7 +30,7 @@ pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenT ...@@ -30,7 +30,7 @@ pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenT
Some(v) => v Some(v) => v
}; };
let e = match env::var_string(&var[]) { let e = match env::var(&var[]) {
Err(..) => { Err(..) => {
cx.expr_path(cx.path_all(sp, cx.expr_path(cx.path_all(sp,
true, true,
...@@ -101,7 +101,7 @@ pub fn expand_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) ...@@ -101,7 +101,7 @@ pub fn expand_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
} }
} }
let e = match env::var_string(&var[]) { let e = match env::var(&var[]) {
Err(_) => { Err(_) => {
cx.span_err(sp, &msg); cx.span_err(sp, &msg);
cx.expr_usize(sp, 0) cx.expr_usize(sp, 0)
......
...@@ -172,7 +172,7 @@ impl<T: Writer+Send> TerminfoTerminal<T> { ...@@ -172,7 +172,7 @@ impl<T: Writer+Send> TerminfoTerminal<T> {
/// Returns `None` whenever the terminal cannot be created for some /// Returns `None` whenever the terminal cannot be created for some
/// reason. /// reason.
pub fn new(out: T) -> Option<Box<Terminal<T>+Send+'static>> { pub fn new(out: T) -> Option<Box<Terminal<T>+Send+'static>> {
let term = match env::var_string("TERM") { let term = match env::var("TERM") {
Ok(t) => t, Ok(t) => t,
Err(..) => { Err(..) => {
debug!("TERM environment variable not defined"); debug!("TERM environment variable not defined");
...@@ -182,7 +182,7 @@ pub fn new(out: T) -> Option<Box<Terminal<T>+Send+'static>> { ...@@ -182,7 +182,7 @@ pub fn new(out: T) -> Option<Box<Terminal<T>+Send+'static>> {
let entry = open(&term[]); let entry = open(&term[]);
if entry.is_err() { if entry.is_err() {
if env::var_string("MSYSCON").ok().map_or(false, |s| { if env::var("MSYSCON").ok().map_or(false, |s| {
"mintty.exe" == s "mintty.exe" == s
}) { }) {
// msys terminal // msys terminal
......
...@@ -28,14 +28,14 @@ pub fn get_dbpath_for_term(term: &str) -> Option<Box<Path>> { ...@@ -28,14 +28,14 @@ pub fn get_dbpath_for_term(term: &str) -> Option<Box<Path>> {
let first_char = term.char_at(0); let first_char = term.char_at(0);
// Find search directory // Find search directory
match env::var_string("TERMINFO") { match env::var("TERMINFO") {
Ok(dir) => dirs_to_search.push(Path::new(dir)), Ok(dir) => dirs_to_search.push(Path::new(dir)),
Err(..) => { Err(..) => {
if homedir.is_some() { if homedir.is_some() {
// ncurses compatibility; // ncurses compatibility;
dirs_to_search.push(homedir.unwrap().join(".terminfo")) dirs_to_search.push(homedir.unwrap().join(".terminfo"))
} }
match env::var_string("TERMINFO_DIRS") { match env::var("TERMINFO_DIRS") {
Ok(dirs) => for i in dirs.split(':') { Ok(dirs) => for i in dirs.split(':') {
if i == "" { if i == "" {
dirs_to_search.push(Path::new("/usr/share/terminfo")); dirs_to_search.push(Path::new("/usr/share/terminfo"));
......
...@@ -385,7 +385,7 @@ pub fn parse_opts(args: &[String]) -> Option<OptRes> { ...@@ -385,7 +385,7 @@ pub fn parse_opts(args: &[String]) -> Option<OptRes> {
let mut nocapture = matches.opt_present("nocapture"); let mut nocapture = matches.opt_present("nocapture");
if !nocapture { if !nocapture {
nocapture = env::var("RUST_TEST_NOCAPTURE").is_some(); nocapture = env::var("RUST_TEST_NOCAPTURE").is_ok();
} }
let color = match matches.opt_str("color").as_ref().map(|s| &**s) { let color = match matches.opt_str("color").as_ref().map(|s| &**s) {
...@@ -811,7 +811,7 @@ fn run_tests<F>(opts: &TestOpts, ...@@ -811,7 +811,7 @@ fn run_tests<F>(opts: &TestOpts,
fn get_concurrency() -> uint { fn get_concurrency() -> uint {
use std::rt; use std::rt;
match env::var_string("RUST_TEST_TASKS") { match env::var("RUST_TEST_TASKS") {
Ok(s) => { Ok(s) => {
let opt_n: Option<uint> = s.parse().ok(); let opt_n: Option<uint> = s.parse().ok();
match opt_n { match opt_n {
......
...@@ -11,8 +11,8 @@ ...@@ -11,8 +11,8 @@
use std::env::*; use std::env::*;
fn main() { fn main() {
for (k, v) in vars() { for (k, v) in vars_os() {
let v2 = var(&k); let v2 = var_os(&k);
// MingW seems to set some funky environment variables like // MingW seems to set some funky environment variables like
// "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
// from vars() but not visible from var(). // from vars() but not visible from var().
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册