Skip to content

Commit

Permalink
std: Add a new env module
Browse files Browse the repository at this point in the history
This is an implementation of [RFC 578][rfc] which adds a new `std::env` module
to replace most of the functionality in the current `std::os` module. More
details can be found in the RFC itself, but as a summary the following methods
have all been deprecated:

[rfc]: rust-lang/rfcs#578

* `os::args_as_bytes`   => `env::args`
* `os::args`            => `env::args`
* `os::consts`          => `env::consts`
* `os::dll_filename`    => no replacement, use `env::consts` directly
* `os::page_size`       => `env::page_size`
* `os::make_absolute`   => use `env::current_dir` + `join` instead
* `os::getcwd`          => `env::current_dir`
* `os::change_dir`      => `env::set_current_dir`
* `os::homedir`         => `env::home_dir`
* `os::tmpdir`          => `env::temp_dir`
* `os::join_paths`      => `env::join_paths`
* `os::split_paths`     => `env::split_paths`
* `os::self_exe_name`   => `env::current_exe`
* `os::self_exe_path`   => use `env::current_exe` + `pop`
* `os::set_exit_status` => `env::set_exit_status`
* `os::get_exit_status` => `env::get_exit_status`
* `os::env`             => `env::vars`
* `os::env_as_bytes`    => `env::vars`
* `os::getenv`          => `env::var` or `env::var_string`
* `os::getenv_as_bytes` => `env::var`
* `os::setenv`          => `env::set_var`
* `os::unsetenv`        => `env::remove_var`

Many function signatures have also been tweaked for various purposes, but the
main changes were:

* `Vec`-returning APIs now all return iterators instead
* All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`.
  There is currently on convenience API, `env::var_string`, which can be used to
  get the value of an environment variable as a unicode `String`.

All old APIs are `#[deprecated]` in-place and will remain for some time to allow
for migrations. The semantics of the APIs have been tweaked slightly with regard
to dealing with invalid unicode (panic instead of replacement).

The new `std::env` module is all contained within the `env` feature, so crates
must add the following to access the new APIs:

    #![feature(env)]

[breaking-change]
  • Loading branch information
alexcrichton committed Feb 1, 2015
1 parent f1398d2 commit 70ed3a4
Show file tree
Hide file tree
Showing 66 changed files with 2,175 additions and 782 deletions.
11 changes: 6 additions & 5 deletions src/compiletest/compiletest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
#![feature(std_misc)]
#![feature(test)]
#![feature(unicode)]
#![feature(env)]

#![deny(warnings)]

Expand All @@ -31,7 +32,7 @@ extern crate getopts;
#[macro_use]
extern crate log;

use std::os;
use std::env;
use std::old_io;
use std::old_io::fs;
use std::thunk::Thunk;
Expand All @@ -48,7 +49,7 @@ pub mod common;
pub mod errors;

pub fn main() {
let args = os::args();
let args = env::args().map(|s| s.into_string().unwrap()).collect();;
let config = parse_config(args);

if config.valgrind_path.is_none() && config.force_valgrind {
Expand Down Expand Up @@ -224,15 +225,15 @@ pub fn run_tests(config: &Config) {
//arm-linux-androideabi debug-info test uses remote debugger
//so, we test 1 task at once.
// also trying to isolate problems with adb_run_wrapper.sh ilooping
os::setenv("RUST_TEST_TASKS","1");
env::set_var("RUST_TEST_TASKS","1");
}

match config.mode {
DebugInfoLldb => {
// Some older versions of LLDB seem to have problems with multiple
// instances running in parallel, so only run one test task at a
// time.
os::setenv("RUST_TEST_TASKS", "1");
env::set_var("RUST_TEST_TASKS", "1");
}
_ => { /* proceed */ }
}
Expand All @@ -245,7 +246,7 @@ pub fn run_tests(config: &Config) {
old_io::test::raise_fd_limit();
// Prevent issue #21352 UAC blocking .exe containing 'patch' etc. on Windows
// If #11207 is resolved (adding manifest to .exe) this becomes unnecessary
os::setenv("__COMPAT_LAYER", "RunAsInvoker");
env::set_var("__COMPAT_LAYER", "RunAsInvoker");
let res = test::run_tests_console(&opts, tests.into_iter().collect());
match res {
Ok(true) => {}
Expand Down
6 changes: 3 additions & 3 deletions src/compiletest/runtest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use std::old_io::process::ProcessExit;
use std::old_io::process;
use std::old_io::timer;
use std::old_io;
use std::os;
use std::env;
use std::iter::repeat;
use std::str;
use std::string::String;
Expand Down Expand Up @@ -1298,9 +1298,9 @@ fn make_lib_name(config: &Config, auxfile: &Path, testfile: &Path) -> Path {

fn make_exe_name(config: &Config, testfile: &Path) -> Path {
let mut f = output_base_name(config, testfile);
if !os::consts::EXE_SUFFIX.is_empty() {
if !env::consts::EXE_SUFFIX.is_empty() {
let mut fname = f.filename().unwrap().to_vec();
fname.extend(os::consts::EXE_SUFFIX.bytes());
fname.extend(env::consts::EXE_SUFFIX.bytes());
f.set_filename(fname);
}
f
Expand Down
1 change: 1 addition & 0 deletions src/etc/make-win-dist.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ def make_win_dist(rust_root, gcc_root, target_triple):
"libsetupapi.a",
"libshell32.a",
"libuser32.a",
"libuserenv.a",
"libuuid.a",
"libwinhttp.a",
"libwinmm.a",
Expand Down
10 changes: 5 additions & 5 deletions src/liblog/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,15 +173,15 @@
#![feature(int_uint)]
#![feature(core)]
#![feature(io)]
#![feature(os)]
#![feature(std_misc)]
#![feature(env)]

use std::cell::RefCell;
use std::fmt;
use std::old_io::LineBufferedWriter;
use std::old_io;
use std::mem;
use std::os;
use std::env;
use std::ptr;
use std::rt;
use std::slice;
Expand Down Expand Up @@ -397,9 +397,9 @@ fn enabled(level: u32,
/// This is not threadsafe at all, so initialization is performed through a
/// `Once` primitive (and this function is called from that primitive).
fn init() {
let (mut directives, filter) = match os::getenv("RUST_LOG") {
Some(spec) => directive::parse_logging_spec(&spec[]),
None => (Vec::new(), None),
let (mut directives, filter) = match env::var_string("RUST_LOG") {
Ok(spec) => directive::parse_logging_spec(&spec[]),
Err(..) => (Vec::new(), None),
};

// Sort the provided directives by length of their name, this allows a
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
#![feature(int_uint)]
#![feature(io)]
#![feature(libc)]
#![feature(os)]
#![feature(env)]
#![feature(path)]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
Expand Down
10 changes: 5 additions & 5 deletions src/librustc/metadata/filesearch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@
pub use self::FileMatch::*;

use std::collections::HashSet;
use std::env;
use std::old_io::fs::PathExtensions;
use std::old_io::fs;
use std::os;

use util::fs as myfs;
use session::search_paths::{SearchPaths, PathKind};
Expand Down Expand Up @@ -194,7 +194,7 @@ pub fn get_or_default_sysroot() -> Path {
})
}

match canonicalize(os::self_exe_name()) {
match canonicalize(env::current_exe().ok()) {
Some(mut p) => { p.pop(); p.pop(); p }
None => panic!("can't determine value for sysroot")
}
Expand All @@ -207,7 +207,7 @@ static PATH_ENTRY_SEPARATOR: &'static str = ":";

/// Returns RUST_PATH as a string, without default paths added
pub fn get_rust_path() -> Option<String> {
os::getenv("RUST_PATH").map(|x| x.to_string())
env::var_string("RUST_PATH").ok()
}

/// Returns the value of RUST_PATH, as a list
Expand All @@ -224,7 +224,7 @@ pub fn rust_path() -> Vec<Path> {
}
None => Vec::new()
};
let mut cwd = os::getcwd().unwrap();
let mut cwd = env::current_dir().unwrap();
// now add in default entries
let cwd_dot_rust = cwd.join(".rust");
if !env_rust_path.contains(&cwd_dot_rust) {
Expand All @@ -243,7 +243,7 @@ pub fn rust_path() -> Vec<Path> {
}
cwd.pop();
}
let h = os::homedir();
let h = env::home_dir();
for h in h.iter() {
let p = h.join(".rust");
if !env_rust_path.contains(&p) && p.exists() {
Expand Down
6 changes: 3 additions & 3 deletions src/librustc/middle/infer/region_inference/graphviz.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use util::ppaux::Repr;

use std::collections::hash_map::Entry::Vacant;
use std::old_io::{self, File};
use std::os;
use std::env;
use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT};
use syntax::ast;

Expand Down Expand Up @@ -59,13 +59,13 @@ pub fn maybe_print_constraints_for<'a, 'tcx>(region_vars: &RegionVarBindings<'a,
}

let requested_node : Option<ast::NodeId> =
os::getenv("RUST_REGION_GRAPH_NODE").and_then(|s| s.parse().ok());
env::var_string("RUST_REGION_GRAPH_NODE").ok().and_then(|s| s.parse().ok());

if requested_node.is_some() && requested_node != Some(subject_node) {
return;
}

let requested_output = os::getenv("RUST_REGION_GRAPH");
let requested_output = env::var_string("RUST_REGION_GRAPH").ok();
debug!("requested_output: {:?} requested_node: {:?}",
requested_output, requested_node);

Expand Down
4 changes: 2 additions & 2 deletions src/librustc/plugin/load.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use metadata::creader::{CrateOrString, CrateReader};
use plugin::registry::Registry;

use std::mem;
use std::os;
use std::env;
use std::dynamic_lib::DynamicLibrary;
use std::collections::HashSet;
use syntax::ast;
Expand Down Expand Up @@ -233,7 +233,7 @@ impl<'a> PluginLoader<'a> {
path: Path,
symbol: String) -> PluginRegistrarFun {
// Make sure the path contains a / or the linker will search for it.
let path = os::make_absolute(&path).unwrap();
let path = env::current_dir().unwrap().join(&path);

let lib = match DynamicLibrary::open(Some(&path)) {
Ok(lib) => lib,
Expand Down
6 changes: 3 additions & 3 deletions src/librustc/session/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use syntax::{ast, codemap};

use rustc_back::target::Target;

use std::os;
use std::env;
use std::cell::{Cell, RefCell};

pub mod config;
Expand Down Expand Up @@ -347,7 +347,7 @@ pub fn build_session_(sopts: config::Options,
if path.is_absolute() {
path.clone()
} else {
os::getcwd().unwrap().join(&path)
env::current_dir().unwrap().join(&path)
}
);

Expand All @@ -370,7 +370,7 @@ pub fn build_session_(sopts: config::Options,
plugin_registrar_fn: Cell::new(None),
default_sysroot: default_sysroot,
local_crate_source_file: local_crate_source_file,
working_dir: os::getcwd().unwrap(),
working_dir: env::current_dir().unwrap(),
lint_store: RefCell::new(lint::LintStore::new()),
lints: RefCell::new(NodeMap()),
crate_types: RefCell::new(Vec::new()),
Expand Down
6 changes: 3 additions & 3 deletions src/librustc_back/archive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use std::old_io::fs::PathExtensions;
use std::old_io::process::{Command, ProcessOutput};
use std::old_io::{fs, TempDir};
use std::old_io;
use std::os;
use std::env;
use std::str;
use syntax::diagnostic::Handler as ErrorHandler;

Expand Down Expand Up @@ -224,7 +224,7 @@ impl<'a> ArchiveBuilder<'a> {
pub fn build(self) -> Archive<'a> {
// Get an absolute path to the destination, so `ar` will work even
// though we run it from `self.work_dir`.
let abs_dst = os::getcwd().unwrap().join(&self.archive.dst);
let abs_dst = env::current_dir().unwrap().join(&self.archive.dst);
assert!(!abs_dst.is_relative());
let mut args = vec![&abs_dst];
let mut total_len = abs_dst.as_vec().len();
Expand Down Expand Up @@ -283,7 +283,7 @@ impl<'a> ArchiveBuilder<'a> {
// First, extract the contents of the archive to a temporary directory.
// We don't unpack directly into `self.work_dir` due to the possibility
// of filename collisions.
let archive = os::make_absolute(archive).unwrap();
let archive = env::current_dir().unwrap().join(archive);
run_ar(self.archive.handler, &self.archive.maybe_ar_prog,
"x", Some(loc.path()), &[&archive]);

Expand Down
4 changes: 2 additions & 2 deletions src/librustc_back/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@

use std::old_io;
use std::old_io::fs;
use std::os;
use std::env;

/// Returns an absolute path in the filesystem that `path` points to. The
/// returned path does not contain any symlinks in its hierarchy.
pub fn realpath(original: &Path) -> old_io::IoResult<Path> {
static MAX_LINKS_FOLLOWED: uint = 256;
let original = os::make_absolute(original).unwrap();
let original = try!(env::current_dir()).join(original);

// Right now lstat on windows doesn't work quite well
if cfg!(windows) {
Expand Down
1 change: 1 addition & 0 deletions src/librustc_back/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
#![feature(path)]
#![feature(rustc_private)]
#![feature(staged_api)]
#![feature(env)]

extern crate syntax;
extern crate serialize;
Expand Down
11 changes: 5 additions & 6 deletions src/librustc_back/rpath.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@


use std::collections::HashSet;
use std::os;
use std::env;
use std::old_io::IoError;
use syntax::ast;

Expand Down Expand Up @@ -105,18 +105,17 @@ fn get_rpath_relative_to_output<F, G>(config: &mut RPathConfig<F, G>, lib: &Path
F: FnOnce() -> Path,
G: FnMut(&Path) -> Result<Path, IoError>,
{
use std::os;

// Mac doesn't appear to support $ORIGIN
let prefix = if config.is_like_osx {
"@loader_path"
} else {
"$ORIGIN"
};

let mut lib = (config.realpath)(&os::make_absolute(lib).unwrap()).unwrap();
let cwd = env::current_dir().unwrap();
let mut lib = (config.realpath)(&cwd.join(lib)).unwrap();
lib.pop();
let mut output = (config.realpath)(&os::make_absolute(&config.out_filename).unwrap()).unwrap();
let mut output = (config.realpath)(&cwd.join(&config.out_filename)).unwrap();
output.pop();
let relative = lib.path_relative_from(&output);
let relative = relative.expect("could not create rpath relative to output");
Expand All @@ -131,7 +130,7 @@ fn get_install_prefix_rpath<F, G>(config: RPathConfig<F, G>) -> String where
G: FnMut(&Path) -> Result<Path, IoError>,
{
let path = (config.get_install_prefix_lib_path)();
let path = os::make_absolute(&path).unwrap();
let path = env::current_dir().unwrap().join(&path);
// FIXME (#9639): This needs to handle non-utf8 paths
path.as_str().expect("non-utf8 component in rpath").to_string()
}
Expand Down
9 changes: 5 additions & 4 deletions src/librustc_back/target/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,8 @@ impl Target {
/// The error string could come from any of the APIs called, including filesystem access and
/// JSON decoding.
pub fn search(target: &str) -> Result<Target, String> {
use std::os;
use std::env;
use std::ffi::OsString;
use std::old_io::File;
use std::path::Path;
use serialize::json;
Expand Down Expand Up @@ -379,12 +380,12 @@ impl Target {
Path::new(target)
};

let target_path = os::getenv("RUST_TARGET_PATH").unwrap_or(String::new());
let target_path = env::var("RUST_TARGET_PATH")
.unwrap_or(OsString::from_str(""));

let paths = os::split_paths(&target_path[]);
// FIXME 16351: add a sane default search path?

for dir in paths.iter() {
for dir in env::split_paths(&target_path) {
let p = dir.join(path.clone());
if p.is_file() {
return load_file(&p);
Expand Down
Loading

0 comments on commit 70ed3a4

Please sign in to comment.