Skip to content

Commit

Permalink
std: Move std::env to the new I/O APIs
Browse files Browse the repository at this point in the history
This commit moves `std::env` away from the `std::old_io` error type as well as
the `std::old_path` module. Methods returning an error now return `io::Error`
and methods consuming or returning paths use `std::path` instead of
`std::old_path`. This commit does not yet mark these APIs as `#[stable]`.

This commit also migrates `std::old_io::TempDir` to `std::fs::TempDir` with
essentially the exact same API. This type was added to interoperate with the new
path API and has its own `tempdir` feature.

Finally, this commit reverts the deprecation of `std::os` APIs returning the old
path API types. This deprecation can come back once the entire `std::old_path`
module is deprecated.

[breaking-change]
  • Loading branch information
alexcrichton committed Feb 24, 2015
1 parent f0f7ca2 commit 2d200c9
Show file tree
Hide file tree
Showing 31 changed files with 323 additions and 141 deletions.
1 change: 1 addition & 0 deletions src/librustc/lib.rs
Expand Up @@ -40,6 +40,7 @@
#![feature(staged_api)]
#![feature(std_misc)]
#![feature(unicode)]
#![feature(os)]
#![cfg_attr(test, feature(test))]

extern crate arena;
Expand Down
7 changes: 4 additions & 3 deletions src/librustc/metadata/filesearch.rs
Expand Up @@ -14,6 +14,7 @@ pub use self::FileMatch::*;

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

Expand Down Expand Up @@ -194,7 +195,7 @@ pub fn get_or_default_sysroot() -> Path {
})
}

match canonicalize(env::current_exe().ok()) {
match canonicalize(os::self_exe_name()) {
Some(mut p) => { p.pop(); p.pop(); p }
None => panic!("can't determine value for sysroot")
}
Expand Down Expand Up @@ -224,7 +225,7 @@ pub fn rust_path() -> Vec<Path> {
}
None => Vec::new()
};
let mut cwd = env::current_dir().unwrap();
let mut cwd = os::getcwd().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 +244,7 @@ pub fn rust_path() -> Vec<Path> {
}
cwd.pop();
}
if let Some(h) = env::home_dir() {
if let Some(h) = os::homedir() {
let p = h.join(".rust");
if !env_rust_path.contains(&p) && p.exists() {
env_rust_path.push(p);
Expand Down
4 changes: 2 additions & 2 deletions src/librustc/plugin/load.rs
Expand Up @@ -15,7 +15,7 @@ use metadata::creader::CrateReader;
use plugin::registry::Registry;

use std::mem;
use std::env;
use std::os;
use std::dynamic_lib::DynamicLibrary;
use std::borrow::ToOwned;
use syntax::ast;
Expand Down Expand Up @@ -103,7 +103,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 = env::current_dir().unwrap().join(&path);
let path = os::getcwd().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
Expand Up @@ -27,8 +27,8 @@ use syntax::{ast, codemap};

use rustc_back::target::Target;

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

pub mod config;
pub mod search_paths;
Expand Down Expand Up @@ -347,7 +347,7 @@ pub fn build_session_(sopts: config::Options,
if path.is_absolute() {
path.clone()
} else {
env::current_dir().unwrap().join(&path)
os::getcwd().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: env::current_dir().unwrap(),
working_dir: os::getcwd().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
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::env;
use std::os;
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 = env::current_dir().unwrap().join(&self.archive.dst);
let abs_dst = os::getcwd().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 = env::current_dir().unwrap().join(archive);
let archive = os::getcwd().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
Expand Up @@ -10,13 +10,13 @@

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

/// 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 = try!(env::current_dir()).join(original);
let original = try!(os::getcwd()).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
Expand Up @@ -41,6 +41,7 @@
#![feature(rustc_private)]
#![feature(staged_api)]
#![feature(env)]
#![feature(path)]

extern crate syntax;
extern crate serialize;
Expand Down
6 changes: 3 additions & 3 deletions src/librustc_back/rpath.rs
Expand Up @@ -8,10 +8,10 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.


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

pub struct RPathConfig<F, G> where
Expand Down Expand Up @@ -109,7 +109,7 @@ fn get_rpath_relative_to_output<F, G>(config: &mut RPathConfig<F, G>, lib: &Path
"$ORIGIN"
};

let cwd = env::current_dir().unwrap();
let cwd = os::getcwd().unwrap();
let mut lib = (config.realpath)(&cwd.join(lib)).unwrap();
lib.pop();
let mut output = (config.realpath)(&cwd.join(&config.out_filename)).unwrap();
Expand All @@ -129,7 +129,7 @@ fn get_install_prefix_rpath<F, G>(config: RPathConfig<F, G>) -> String where
let path = (config.get_install_prefix_lib_path)();
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()
path.to_str().expect("non-utf8 component in rpath").to_string()
}

fn minimize_rpaths(rpaths: &[String]) -> Vec<String> {
Expand Down
3 changes: 2 additions & 1 deletion src/librustc_back/target/mod.rs
Expand Up @@ -310,6 +310,7 @@ impl Target {
/// JSON decoding.
pub fn search(target: &str) -> Result<Target, String> {
use std::env;
use std::os;
use std::ffi::OsString;
use std::old_io::File;
use std::old_path::Path;
Expand Down Expand Up @@ -396,7 +397,7 @@ impl Target {

// FIXME 16351: add a sane default search path?

for dir in env::split_paths(&target_path) {
for dir in os::split_paths(target_path.to_str().unwrap()).iter() {
let p = dir.join(path.clone());
if p.is_file() {
return load_file(&p);
Expand Down
5 changes: 3 additions & 2 deletions src/librustc_driver/driver.rs
Expand Up @@ -32,6 +32,7 @@ use super::Compilation;
use serialize::json;

use std::env;
use std::os;
use std::ffi::OsString;
use std::old_io::fs;
use std::old_io;
Expand Down Expand Up @@ -471,7 +472,7 @@ pub fn phase_2_configure_and_expand(sess: &Session,
if cfg!(windows) {
_old_path = env::var_os("PATH").unwrap_or(_old_path);
let mut new_path = sess.host_filesearch(PathKind::All).get_dylib_search_paths();
new_path.extend(env::split_paths(&_old_path));
new_path.extend(os::split_paths(_old_path.to_str().unwrap()).into_iter());
env::set_var("PATH", &env::join_paths(new_path.iter()).unwrap());
}
let features = sess.features.borrow();
Expand Down Expand Up @@ -738,7 +739,7 @@ pub fn phase_6_link_output(sess: &Session,
outputs: &OutputFilenames) {
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();
new_path.extend(env::split_paths(&old_path));
new_path.extend(os::split_paths(old_path.to_str().unwrap()).into_iter());
env::set_var("PATH", &env::join_paths(new_path.iter()).unwrap());

time(sess.time_passes(), "linking", (), |_|
Expand Down
6 changes: 3 additions & 3 deletions src/librustdoc/test.rs
Expand Up @@ -13,7 +13,7 @@ use std::sync::mpsc::channel;
use std::dynamic_lib::DynamicLibrary;
use std::old_io::{Command, TempDir};
use std::old_io;
use std::env;
use std::os;
use std::str;
use std::thread;
use std::thunk::Thunk;
Expand Down Expand Up @@ -46,7 +46,7 @@ pub fn run(input: &str,
let input = config::Input::File(input_path.clone());

let sessopts = config::Options {
maybe_sysroot: Some(env::current_exe().unwrap().dir_path().dir_path()),
maybe_sysroot: Some(os::self_exe_name().unwrap().dir_path().dir_path()),
search_paths: libs.clone(),
crate_types: vec!(config::CrateTypeDylib),
externs: externs.clone(),
Expand Down Expand Up @@ -113,7 +113,7 @@ fn runtest(test: &str, cratename: &str, libs: SearchPaths,
let input = config::Input::Str(test.to_string());

let sessopts = config::Options {
maybe_sysroot: Some(env::current_exe().unwrap().dir_path().dir_path()),
maybe_sysroot: Some(os::self_exe_name().unwrap().dir_path().dir_path()),
search_paths: libs,
crate_types: vec!(config::CrateTypeExecutable),
output_types: vec!(config::OutputTypeExe),
Expand Down
3 changes: 2 additions & 1 deletion src/libstd/dynamic_lib.rs
Expand Up @@ -21,6 +21,7 @@ use ffi::CString;
use mem;
use env;
use str;
use os;

pub struct DynamicLibrary {
handle: *mut u8
Expand Down Expand Up @@ -102,7 +103,7 @@ impl DynamicLibrary {
/// process
pub fn search_path() -> Vec<Path> {
match env::var_os(DynamicLibrary::envvar()) {
Some(var) => env::split_paths(&var).collect(),
Some(var) => os::split_paths(var.to_str().unwrap()),
None => Vec::new(),
}
}
Expand Down
27 changes: 15 additions & 12 deletions src/libstd/env.rs
Expand Up @@ -21,7 +21,8 @@ use prelude::v1::*;
use error::Error;
use ffi::{OsString, AsOsStr};
use fmt;
use old_io::IoResult;
use io;
use path::{AsPath, PathBuf};
use sync::atomic::{AtomicIsize, ATOMIC_ISIZE_INIT, Ordering};
use sync::{StaticMutex, MUTEX_INIT};
use sys::os as os_imp;
Expand All @@ -46,7 +47,7 @@ use sys::os as os_imp;
/// let p = env::current_dir().unwrap();
/// println!("The current directory is {}", p.display());
/// ```
pub fn current_dir() -> IoResult<Path> {
pub fn current_dir() -> io::Result<PathBuf> {
os_imp::getcwd()
}

Expand All @@ -57,14 +58,14 @@ pub fn current_dir() -> IoResult<Path> {
///
/// ```rust
/// use std::env;
/// use std::old_path::Path;
/// use std::path::Path;
///
/// let root = Path::new("/");
/// assert!(env::set_current_dir(&root).is_ok());
/// println!("Successfully changed working directory to {}!", root.display());
/// ```
pub fn set_current_dir(p: &Path) -> IoResult<()> {
os_imp::chdir(p)
pub fn set_current_dir<P: AsPath + ?Sized>(p: &P) -> io::Result<()> {
os_imp::chdir(p.as_path())
}

static ENV_LOCK: StaticMutex = MUTEX_INIT;
Expand Down Expand Up @@ -280,8 +281,8 @@ pub fn split_paths<T: AsOsStr + ?Sized>(unparsed: &T) -> SplitPaths {
}

impl<'a> Iterator for SplitPaths<'a> {
type Item = Path;
fn next(&mut self) -> Option<Path> { self.inner.next() }
type Item = PathBuf;
fn next(&mut self) -> Option<PathBuf> { self.inner.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
}

Expand All @@ -305,10 +306,11 @@ pub struct JoinPathsError {
///
/// ```rust
/// use std::env;
/// use std::path::PathBuf;
///
/// if let Some(path) = env::var_os("PATH") {
/// let mut paths = env::split_paths(&path).collect::<Vec<_>>();
/// paths.push(Path::new("/home/xyz/bin"));
/// paths.push(PathBuf::new("/home/xyz/bin"));
/// let new_path = env::join_paths(paths.iter()).unwrap();
/// env::set_var("PATH", &new_path);
/// }
Expand Down Expand Up @@ -355,7 +357,7 @@ impl Error for JoinPathsError {
/// None => println!("Impossible to get your home dir!")
/// }
/// ```
pub fn home_dir() -> Option<Path> {
pub fn home_dir() -> Option<PathBuf> {
os_imp::home_dir()
}

Expand All @@ -369,7 +371,7 @@ pub fn home_dir() -> Option<Path> {
/// On Windows, returns the value of, in order, the 'TMP', 'TEMP',
/// 'USERPROFILE' environment variable if any are set and not the empty
/// string. Otherwise, tmpdir returns the path to the Windows directory.
pub fn temp_dir() -> Path {
pub fn temp_dir() -> PathBuf {
os_imp::temp_dir()
}

Expand All @@ -396,7 +398,7 @@ pub fn temp_dir() -> Path {
/// Err(e) => println!("failed to get current exe path: {}", e),
/// };
/// ```
pub fn current_exe() -> IoResult<Path> {
pub fn current_exe() -> io::Result<PathBuf> {
os_imp::current_exe()
}

Expand Down Expand Up @@ -825,6 +827,7 @@ mod tests {
use iter::repeat;
use rand::{self, Rng};
use ffi::{OsString, OsStr};
use path::PathBuf;

fn make_rand_name() -> OsString {
let mut rng = rand::thread_rng();
Expand Down Expand Up @@ -944,7 +947,7 @@ mod tests {
fn split_paths_unix() {
fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
split_paths(unparsed).collect::<Vec<_>>() ==
parsed.iter().map(|s| Path::new(*s)).collect::<Vec<_>>()
parsed.iter().map(|s| PathBuf::new(*s)).collect::<Vec<_>>()
}

assert!(check_parse("", &mut [""]));
Expand Down
4 changes: 4 additions & 0 deletions src/libstd/fs.rs → src/libstd/fs/mod.rs
Expand Up @@ -25,6 +25,10 @@ use sys::fs2 as fs_imp;
use sys_common::{AsInnerMut, FromInner, AsInner};
use vec::Vec;

pub use self::tempdir::TempDir;

mod tempdir;

/// A reference to an open file on the filesystem.
///
/// An instance of a `File` can be read and/or written depending on what options
Expand Down

0 comments on commit 2d200c9

Please sign in to comment.