Skip to content

Commit 2d200c9

Browse files
committed
std: Move std::env to the new I/O APIs
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]
1 parent f0f7ca2 commit 2d200c9

File tree

31 files changed

+323
-141
lines changed

31 files changed

+323
-141
lines changed

src/librustc/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
#![feature(staged_api)]
4141
#![feature(std_misc)]
4242
#![feature(unicode)]
43+
#![feature(os)]
4344
#![cfg_attr(test, feature(test))]
4445

4546
extern crate arena;

src/librustc/metadata/filesearch.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ pub use self::FileMatch::*;
1414

1515
use std::collections::HashSet;
1616
use std::env;
17+
use std::os;
1718
use std::old_io::fs::PathExtensions;
1819
use std::old_io::fs;
1920

@@ -194,7 +195,7 @@ pub fn get_or_default_sysroot() -> Path {
194195
})
195196
}
196197

197-
match canonicalize(env::current_exe().ok()) {
198+
match canonicalize(os::self_exe_name()) {
198199
Some(mut p) => { p.pop(); p.pop(); p }
199200
None => panic!("can't determine value for sysroot")
200201
}
@@ -224,7 +225,7 @@ pub fn rust_path() -> Vec<Path> {
224225
}
225226
None => Vec::new()
226227
};
227-
let mut cwd = env::current_dir().unwrap();
228+
let mut cwd = os::getcwd().unwrap();
228229
// now add in default entries
229230
let cwd_dot_rust = cwd.join(".rust");
230231
if !env_rust_path.contains(&cwd_dot_rust) {
@@ -243,7 +244,7 @@ pub fn rust_path() -> Vec<Path> {
243244
}
244245
cwd.pop();
245246
}
246-
if let Some(h) = env::home_dir() {
247+
if let Some(h) = os::homedir() {
247248
let p = h.join(".rust");
248249
if !env_rust_path.contains(&p) && p.exists() {
249250
env_rust_path.push(p);

src/librustc/plugin/load.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use metadata::creader::CrateReader;
1515
use plugin::registry::Registry;
1616

1717
use std::mem;
18-
use std::env;
18+
use std::os;
1919
use std::dynamic_lib::DynamicLibrary;
2020
use std::borrow::ToOwned;
2121
use syntax::ast;
@@ -103,7 +103,7 @@ impl<'a> PluginLoader<'a> {
103103
path: Path,
104104
symbol: String) -> PluginRegistrarFun {
105105
// Make sure the path contains a / or the linker will search for it.
106-
let path = env::current_dir().unwrap().join(&path);
106+
let path = os::getcwd().unwrap().join(&path);
107107

108108
let lib = match DynamicLibrary::open(Some(&path)) {
109109
Ok(lib) => lib,

src/librustc/session/mod.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,8 @@ use syntax::{ast, codemap};
2727

2828
use rustc_back::target::Target;
2929

30-
use std::env;
3130
use std::cell::{Cell, RefCell};
31+
use std::os;
3232

3333
pub mod config;
3434
pub mod search_paths;
@@ -347,7 +347,7 @@ pub fn build_session_(sopts: config::Options,
347347
if path.is_absolute() {
348348
path.clone()
349349
} else {
350-
env::current_dir().unwrap().join(&path)
350+
os::getcwd().unwrap().join(&path)
351351
}
352352
);
353353

@@ -370,7 +370,7 @@ pub fn build_session_(sopts: config::Options,
370370
plugin_registrar_fn: Cell::new(None),
371371
default_sysroot: default_sysroot,
372372
local_crate_source_file: local_crate_source_file,
373-
working_dir: env::current_dir().unwrap(),
373+
working_dir: os::getcwd().unwrap(),
374374
lint_store: RefCell::new(lint::LintStore::new()),
375375
lints: RefCell::new(NodeMap()),
376376
crate_types: RefCell::new(Vec::new()),

src/librustc_back/archive.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use std::old_io::fs::PathExtensions;
1414
use std::old_io::process::{Command, ProcessOutput};
1515
use std::old_io::{fs, TempDir};
1616
use std::old_io;
17-
use std::env;
17+
use std::os;
1818
use std::str;
1919
use syntax::diagnostic::Handler as ErrorHandler;
2020

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

src/librustc_back/fs.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,13 @@
1010

1111
use std::old_io;
1212
use std::old_io::fs;
13-
use std::env;
13+
use std::os;
1414

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

2121
// Right now lstat on windows doesn't work quite well
2222
if cfg!(windows) {

src/librustc_back/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
#![feature(rustc_private)]
4242
#![feature(staged_api)]
4343
#![feature(env)]
44+
#![feature(path)]
4445

4546
extern crate syntax;
4647
extern crate serialize;

src/librustc_back/rpath.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,10 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010

11-
1211
use std::collections::HashSet;
1312
use std::env;
1413
use std::old_io::IoError;
14+
use std::os;
1515
use syntax::ast;
1616

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

112-
let cwd = env::current_dir().unwrap();
112+
let cwd = os::getcwd().unwrap();
113113
let mut lib = (config.realpath)(&cwd.join(lib)).unwrap();
114114
lib.pop();
115115
let mut output = (config.realpath)(&cwd.join(&config.out_filename)).unwrap();
@@ -129,7 +129,7 @@ fn get_install_prefix_rpath<F, G>(config: RPathConfig<F, G>) -> String where
129129
let path = (config.get_install_prefix_lib_path)();
130130
let path = env::current_dir().unwrap().join(&path);
131131
// FIXME (#9639): This needs to handle non-utf8 paths
132-
path.as_str().expect("non-utf8 component in rpath").to_string()
132+
path.to_str().expect("non-utf8 component in rpath").to_string()
133133
}
134134

135135
fn minimize_rpaths(rpaths: &[String]) -> Vec<String> {

src/librustc_back/target/mod.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,7 @@ impl Target {
310310
/// JSON decoding.
311311
pub fn search(target: &str) -> Result<Target, String> {
312312
use std::env;
313+
use std::os;
313314
use std::ffi::OsString;
314315
use std::old_io::File;
315316
use std::old_path::Path;
@@ -396,7 +397,7 @@ impl Target {
396397

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

399-
for dir in env::split_paths(&target_path) {
400+
for dir in os::split_paths(target_path.to_str().unwrap()).iter() {
400401
let p = dir.join(path.clone());
401402
if p.is_file() {
402403
return load_file(&p);

src/librustc_driver/driver.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ use super::Compilation;
3232
use serialize::json;
3333

3434
use std::env;
35+
use std::os;
3536
use std::ffi::OsString;
3637
use std::old_io::fs;
3738
use std::old_io;
@@ -471,7 +472,7 @@ pub fn phase_2_configure_and_expand(sess: &Session,
471472
if cfg!(windows) {
472473
_old_path = env::var_os("PATH").unwrap_or(_old_path);
473474
let mut new_path = sess.host_filesearch(PathKind::All).get_dylib_search_paths();
474-
new_path.extend(env::split_paths(&_old_path));
475+
new_path.extend(os::split_paths(_old_path.to_str().unwrap()).into_iter());
475476
env::set_var("PATH", &env::join_paths(new_path.iter()).unwrap());
476477
}
477478
let features = sess.features.borrow();
@@ -738,7 +739,7 @@ pub fn phase_6_link_output(sess: &Session,
738739
outputs: &OutputFilenames) {
739740
let old_path = env::var_os("PATH").unwrap_or(OsString::from_str(""));
740741
let mut new_path = sess.host_filesearch(PathKind::All).get_tools_search_paths();
741-
new_path.extend(env::split_paths(&old_path));
742+
new_path.extend(os::split_paths(old_path.to_str().unwrap()).into_iter());
742743
env::set_var("PATH", &env::join_paths(new_path.iter()).unwrap());
743744

744745
time(sess.time_passes(), "linking", (), |_|

src/librustdoc/test.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use std::sync::mpsc::channel;
1313
use std::dynamic_lib::DynamicLibrary;
1414
use std::old_io::{Command, TempDir};
1515
use std::old_io;
16-
use std::env;
16+
use std::os;
1717
use std::str;
1818
use std::thread;
1919
use std::thunk::Thunk;
@@ -46,7 +46,7 @@ pub fn run(input: &str,
4646
let input = config::Input::File(input_path.clone());
4747

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

115115
let sessopts = config::Options {
116-
maybe_sysroot: Some(env::current_exe().unwrap().dir_path().dir_path()),
116+
maybe_sysroot: Some(os::self_exe_name().unwrap().dir_path().dir_path()),
117117
search_paths: libs,
118118
crate_types: vec!(config::CrateTypeExecutable),
119119
output_types: vec!(config::OutputTypeExe),

src/libstd/dynamic_lib.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ use ffi::CString;
2121
use mem;
2222
use env;
2323
use str;
24+
use os;
2425

2526
pub struct DynamicLibrary {
2627
handle: *mut u8
@@ -102,7 +103,7 @@ impl DynamicLibrary {
102103
/// process
103104
pub fn search_path() -> Vec<Path> {
104105
match env::var_os(DynamicLibrary::envvar()) {
105-
Some(var) => env::split_paths(&var).collect(),
106+
Some(var) => os::split_paths(var.to_str().unwrap()),
106107
None => Vec::new(),
107108
}
108109
}

src/libstd/env.rs

+15-12
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@ use prelude::v1::*;
2121
use error::Error;
2222
use ffi::{OsString, AsOsStr};
2323
use fmt;
24-
use old_io::IoResult;
24+
use io;
25+
use path::{AsPath, PathBuf};
2526
use sync::atomic::{AtomicIsize, ATOMIC_ISIZE_INIT, Ordering};
2627
use sync::{StaticMutex, MUTEX_INIT};
2728
use sys::os as os_imp;
@@ -46,7 +47,7 @@ use sys::os as os_imp;
4647
/// let p = env::current_dir().unwrap();
4748
/// println!("The current directory is {}", p.display());
4849
/// ```
49-
pub fn current_dir() -> IoResult<Path> {
50+
pub fn current_dir() -> io::Result<PathBuf> {
5051
os_imp::getcwd()
5152
}
5253

@@ -57,14 +58,14 @@ pub fn current_dir() -> IoResult<Path> {
5758
///
5859
/// ```rust
5960
/// use std::env;
60-
/// use std::old_path::Path;
61+
/// use std::path::Path;
6162
///
6263
/// let root = Path::new("/");
6364
/// assert!(env::set_current_dir(&root).is_ok());
6465
/// println!("Successfully changed working directory to {}!", root.display());
6566
/// ```
66-
pub fn set_current_dir(p: &Path) -> IoResult<()> {
67-
os_imp::chdir(p)
67+
pub fn set_current_dir<P: AsPath + ?Sized>(p: &P) -> io::Result<()> {
68+
os_imp::chdir(p.as_path())
6869
}
6970

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

282283
impl<'a> Iterator for SplitPaths<'a> {
283-
type Item = Path;
284-
fn next(&mut self) -> Option<Path> { self.inner.next() }
284+
type Item = PathBuf;
285+
fn next(&mut self) -> Option<PathBuf> { self.inner.next() }
285286
fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
286287
}
287288

@@ -305,10 +306,11 @@ pub struct JoinPathsError {
305306
///
306307
/// ```rust
307308
/// use std::env;
309+
/// use std::path::PathBuf;
308310
///
309311
/// if let Some(path) = env::var_os("PATH") {
310312
/// let mut paths = env::split_paths(&path).collect::<Vec<_>>();
311-
/// paths.push(Path::new("/home/xyz/bin"));
313+
/// paths.push(PathBuf::new("/home/xyz/bin"));
312314
/// let new_path = env::join_paths(paths.iter()).unwrap();
313315
/// env::set_var("PATH", &new_path);
314316
/// }
@@ -355,7 +357,7 @@ impl Error for JoinPathsError {
355357
/// None => println!("Impossible to get your home dir!")
356358
/// }
357359
/// ```
358-
pub fn home_dir() -> Option<Path> {
360+
pub fn home_dir() -> Option<PathBuf> {
359361
os_imp::home_dir()
360362
}
361363

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

@@ -396,7 +398,7 @@ pub fn temp_dir() -> Path {
396398
/// Err(e) => println!("failed to get current exe path: {}", e),
397399
/// };
398400
/// ```
399-
pub fn current_exe() -> IoResult<Path> {
401+
pub fn current_exe() -> io::Result<PathBuf> {
400402
os_imp::current_exe()
401403
}
402404

@@ -825,6 +827,7 @@ mod tests {
825827
use iter::repeat;
826828
use rand::{self, Rng};
827829
use ffi::{OsString, OsStr};
830+
use path::PathBuf;
828831

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

950953
assert!(check_parse("", &mut [""]));

src/libstd/fs.rs renamed to src/libstd/fs/mod.rs

+4
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,10 @@ use sys::fs2 as fs_imp;
2525
use sys_common::{AsInnerMut, FromInner, AsInner};
2626
use vec::Vec;
2727

28+
pub use self::tempdir::TempDir;
29+
30+
mod tempdir;
31+
2832
/// A reference to an open file on the filesystem.
2933
///
3034
/// An instance of a `File` can be read and/or written depending on what options

0 commit comments

Comments
 (0)