1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Inspection and manipulation of the process's environment.
13 //! This module contains methods to inspect various aspects such as
14 //! environment varibles, process arguments, the current directory, and various
15 //! other important directories.
17 #![stable(feature = "env", since = "1.0.0")]
22 use ffi::{OsStr, OsString};
25 use path::{Path, PathBuf};
26 use sync::atomic::{AtomicIsize, Ordering};
27 use sync::StaticMutex;
28 use sys::os as os_imp;
30 /// Returns the current working directory as a `PathBuf`.
34 /// Returns an `Err` if the current working directory value is invalid.
37 /// * Current directory does not exist.
38 /// * There are insufficient permissions to access the current directory.
39 /// * The internal buffer is not large enough to hold the path.
46 /// // We assume that we are in a valid directory.
47 /// let p = env::current_dir().unwrap();
48 /// println!("The current directory is {}", p.display());
50 #[stable(feature = "env", since = "1.0.0")]
51 pub fn current_dir() -> io::Result<PathBuf> {
55 /// Changes the current working directory to the specified path, returning
56 /// whether the change was completed successfully or not.
62 /// use std::path::Path;
64 /// let root = Path::new("/");
65 /// assert!(env::set_current_dir(&root).is_ok());
66 /// println!("Successfully changed working directory to {}!", root.display());
68 #[stable(feature = "env", since = "1.0.0")]
69 pub fn set_current_dir<P: AsRef<Path>>(p: P) -> io::Result<()> {
70 os_imp::chdir(p.as_ref())
73 static ENV_LOCK: StaticMutex = StaticMutex::new();
75 /// An iterator over a snapshot of the environment variables of this process.
77 /// This iterator is created through `std::env::vars()` and yields `(String,
79 #[stable(feature = "env", since = "1.0.0")]
80 pub struct Vars { inner: VarsOs }
82 /// An iterator over a snapshot of the environment variables of this process.
84 /// This iterator is created through `std::env::vars_os()` and yields
85 /// `(OsString, OsString)` pairs.
86 #[stable(feature = "env", since = "1.0.0")]
87 pub struct VarsOs { inner: os_imp::Env }
89 /// Returns an iterator of (variable, value) pairs of strings, for all the
90 /// environment variables of the current process.
92 /// The returned iterator contains a snapshot of the process's environment
93 /// variables at the time of this invocation, modifications to environment
94 /// variables afterwards will not be reflected in the returned iterator.
98 /// While iterating, the returned iterator will panic if any key or value in the
99 /// environment is not valid unicode. If this is not desired, consider using the
100 /// `env::vars_os` function.
107 /// // We will iterate through the references to the element returned by
109 /// for (key, value) in env::vars() {
110 /// println!("{}: {}", key, value);
113 #[stable(feature = "env", since = "1.0.0")]
114 pub fn vars() -> Vars {
115 Vars { inner: vars_os() }
118 /// Returns an iterator of (variable, value) pairs of OS strings, for all the
119 /// environment variables of the current process.
121 /// The returned iterator contains a snapshot of the process's environment
122 /// variables at the time of this invocation, modifications to environment
123 /// variables afterwards will not be reflected in the returned iterator.
130 /// // We will iterate through the references to the element returned by
131 /// // env::vars_os();
132 /// for (key, value) in env::vars_os() {
133 /// println!("{:?}: {:?}", key, value);
136 #[stable(feature = "env", since = "1.0.0")]
137 pub fn vars_os() -> VarsOs {
138 let _g = ENV_LOCK.lock();
139 VarsOs { inner: os_imp::env() }
142 #[stable(feature = "env", since = "1.0.0")]
143 impl Iterator for Vars {
144 type Item = (String, String);
145 fn next(&mut self) -> Option<(String, String)> {
146 self.inner.next().map(|(a, b)| {
147 (a.into_string().unwrap(), b.into_string().unwrap())
150 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
153 #[stable(feature = "env", since = "1.0.0")]
154 impl Iterator for VarsOs {
155 type Item = (OsString, OsString);
156 fn next(&mut self) -> Option<(OsString, OsString)> { self.inner.next() }
157 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
160 /// Fetches the environment variable `key` from the current process.
162 /// The returned result is `Ok(s)` if the environment variable is present and is
163 /// valid unicode. If the environment variable is not present, or it is not
164 /// valid unicode, then `Err` will be returned.
171 /// let key = "HOME";
172 /// match env::var(key) {
173 /// Ok(val) => println!("{}: {:?}", key, val),
174 /// Err(e) => println!("couldn't interpret {}: {}", key, e),
177 #[stable(feature = "env", since = "1.0.0")]
178 pub fn var<K: AsRef<OsStr>>(key: K) -> Result<String, VarError> {
180 Some(s) => s.into_string().map_err(VarError::NotUnicode),
181 None => Err(VarError::NotPresent)
185 /// Fetches the environment variable `key` from the current process, returning
186 /// None if the variable isn't set.
193 /// let key = "HOME";
194 /// match env::var_os(key) {
195 /// Some(val) => println!("{}: {:?}", key, val),
196 /// None => println!("{} is not defined in the environment.", key)
199 #[stable(feature = "env", since = "1.0.0")]
200 pub fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> {
201 let _g = ENV_LOCK.lock();
202 os_imp::getenv(key.as_ref())
205 /// Possible errors from the `env::var` method.
206 #[derive(Debug, PartialEq, Eq, Clone)]
207 #[stable(feature = "env", since = "1.0.0")]
209 /// The specified environment variable was not present in the current
210 /// process's environment.
211 #[stable(feature = "env", since = "1.0.0")]
214 /// The specified environment variable was found, but it did not contain
215 /// valid unicode data. The found data is returned as a payload of this
217 #[stable(feature = "env", since = "1.0.0")]
218 NotUnicode(OsString),
221 #[stable(feature = "env", since = "1.0.0")]
222 impl fmt::Display for VarError {
223 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
225 VarError::NotPresent => write!(f, "environment variable not found"),
226 VarError::NotUnicode(ref s) => {
227 write!(f, "environment variable was not valid unicode: {:?}", s)
233 #[stable(feature = "env", since = "1.0.0")]
234 impl Error for VarError {
235 fn description(&self) -> &str {
237 VarError::NotPresent => "environment variable not found",
238 VarError::NotUnicode(..) => "environment variable was not valid unicode",
243 /// Sets the environment variable `k` to the value `v` for the currently running
246 /// Note that while concurrent access to environment variables is safe in Rust,
247 /// some platforms only expose inherently unsafe non-threadsafe APIs for
248 /// inspecting the environment. As a result extra care needs to be taken when
249 /// auditing calls to unsafe external FFI functions to ensure that any external
250 /// environment accesses are properly synchronized with accesses in Rust.
252 /// Discussion of this unsafety on Unix may be found in:
254 /// - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188)
255 /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
263 /// env::set_var(key, "VALUE");
264 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
266 #[stable(feature = "env", since = "1.0.0")]
267 pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(k: K, v: V) {
268 let _g = ENV_LOCK.lock();
269 os_imp::setenv(k.as_ref(), v.as_ref())
272 /// Removes an environment variable from the environment of the currently running process.
274 /// Note that while concurrent access to environment variables is safe in Rust,
275 /// some platforms only expose inherently unsafe non-threadsafe APIs for
276 /// inspecting the environment. As a result extra care needs to be taken when
277 /// auditing calls to unsafe external FFI functions to ensure that any external
278 /// environment accesses are properly synchronized with accesses in Rust.
280 /// Discussion of this unsafety on Unix may be found in:
282 /// - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188)
283 /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
291 /// env::set_var(key, "VALUE");
292 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
294 /// env::remove_var(key);
295 /// assert!(env::var(key).is_err());
297 #[stable(feature = "env", since = "1.0.0")]
298 pub fn remove_var<K: AsRef<OsStr>>(k: K) {
299 let _g = ENV_LOCK.lock();
300 os_imp::unsetenv(k.as_ref())
303 /// An iterator over `Path` instances for parsing an environment variable
304 /// according to platform-specific conventions.
306 /// This structure is returned from `std::env::split_paths`.
307 #[stable(feature = "env", since = "1.0.0")]
308 pub struct SplitPaths<'a> { inner: os_imp::SplitPaths<'a> }
310 /// Parses input according to platform conventions for the `PATH`
311 /// environment variable.
313 /// Returns an iterator over the paths contained in `unparsed`.
320 /// let key = "PATH";
321 /// match env::var_os(key) {
323 /// for path in env::split_paths(&paths) {
324 /// println!("'{}'", path.display());
327 /// None => println!("{} is not defined in the environment.", key)
330 #[stable(feature = "env", since = "1.0.0")]
331 pub fn split_paths<T: AsRef<OsStr> + ?Sized>(unparsed: &T) -> SplitPaths {
332 SplitPaths { inner: os_imp::split_paths(unparsed.as_ref()) }
335 #[stable(feature = "env", since = "1.0.0")]
336 impl<'a> Iterator for SplitPaths<'a> {
338 fn next(&mut self) -> Option<PathBuf> { self.inner.next() }
339 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
342 /// Error type returned from `std::env::join_paths` when paths fail to be
345 #[stable(feature = "env", since = "1.0.0")]
346 pub struct JoinPathsError {
347 inner: os_imp::JoinPathsError
350 /// Joins a collection of `Path`s appropriately for the `PATH`
351 /// environment variable.
353 /// Returns an `OsString` on success.
355 /// Returns an `Err` (containing an error message) if one of the input
356 /// `Path`s contains an invalid character for constructing the `PATH`
357 /// variable (a double quote on Windows or a colon on Unix).
363 /// use std::path::PathBuf;
365 /// if let Some(path) = env::var_os("PATH") {
366 /// let mut paths = env::split_paths(&path).collect::<Vec<_>>();
367 /// paths.push(PathBuf::from("/home/xyz/bin"));
368 /// let new_path = env::join_paths(paths.iter()).unwrap();
369 /// env::set_var("PATH", &new_path);
372 #[stable(feature = "env", since = "1.0.0")]
373 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
374 where I: IntoIterator<Item=T>, T: AsRef<OsStr>
376 os_imp::join_paths(paths.into_iter()).map_err(|e| {
377 JoinPathsError { inner: e }
381 #[stable(feature = "env", since = "1.0.0")]
382 impl fmt::Display for JoinPathsError {
383 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
388 #[stable(feature = "env", since = "1.0.0")]
389 impl Error for JoinPathsError {
390 fn description(&self) -> &str { self.inner.description() }
393 /// Optionally returns the path to the current user's home directory if known.
397 /// Returns the value of the 'HOME' environment variable if it is set
398 /// and not equal to the empty string.
402 /// Returns the value of the 'HOME' environment variable if it is
403 /// set and not equal to the empty string. Otherwise, returns the value of the
404 /// 'USERPROFILE' environment variable if it is set and not equal to the empty
412 /// match env::home_dir() {
413 /// Some(ref p) => println!("{}", p.display()),
414 /// None => println!("Impossible to get your home dir!")
417 #[stable(feature = "env", since = "1.0.0")]
418 pub fn home_dir() -> Option<PathBuf> {
422 /// Returns the path to a temporary directory.
424 /// On Unix, returns the value of the 'TMPDIR' environment variable if it is
425 /// set, otherwise for non-Android it returns '/tmp'. If Android, since there
426 /// is no global temporary folder (it is usually allocated per-app), we return
427 /// '/data/local/tmp'.
429 /// On Windows, returns the value of, in order, the 'TMP', 'TEMP',
430 /// 'USERPROFILE' environment variable if any are set and not the empty
431 /// string. Otherwise, tmpdir returns the path to the Windows directory.
435 /// use std::fs::File;
437 /// # fn foo() -> std::io::Result<()> {
438 /// let mut dir = env::temp_dir();
439 /// dir.push("foo.txt");
441 /// let f = try!(File::create(dir));
445 #[stable(feature = "env", since = "1.0.0")]
446 pub fn temp_dir() -> PathBuf {
450 /// Optionally returns the filesystem path to the current executable which is
451 /// running but with the executable name.
453 /// The path returned is not necessarily a "real path" to the executable as
454 /// there may be intermediate symlinks.
458 /// Acquiring the path to the current executable is a platform-specific operation
459 /// that can fail for a good number of reasons. Some errors can include, but not
460 /// be limited to filesystem operations failing or general syscall failures.
467 /// match env::current_exe() {
468 /// Ok(exe_path) => println!("Path of this executable is: {}",
469 /// exe_path.display()),
470 /// Err(e) => println!("failed to get current exe path: {}", e),
473 #[stable(feature = "env", since = "1.0.0")]
474 pub fn current_exe() -> io::Result<PathBuf> {
475 os_imp::current_exe()
478 static EXIT_STATUS: AtomicIsize = AtomicIsize::new(0);
480 /// Sets the process exit code
482 /// Sets the exit code returned by the process if all supervised threads
483 /// terminate successfully (without panicking). If the current root thread panics
484 /// and is supervised by the scheduler then any user-specified exit status is
485 /// ignored and the process exits with the default panic status.
487 /// Note that this is not synchronized against modifications of other threads.
488 #[unstable(feature = "exit_status", reason = "managing the exit status may change")]
489 pub fn set_exit_status(code: i32) {
490 EXIT_STATUS.store(code as isize, Ordering::SeqCst)
493 /// Fetches the process's current exit code. This defaults to 0 and can change
494 /// by calling `set_exit_status`.
495 #[unstable(feature = "exit_status", reason = "managing the exit status may change")]
496 pub fn get_exit_status() -> i32 {
497 EXIT_STATUS.load(Ordering::SeqCst) as i32
500 /// An iterator over the arguments of a process, yielding a `String` value
501 /// for each argument.
503 /// This structure is created through the `std::env::args` method.
504 #[stable(feature = "env", since = "1.0.0")]
505 pub struct Args { inner: ArgsOs }
507 /// An iterator over the arguments of a process, yielding an `OsString` value
508 /// for each argument.
510 /// This structure is created through the `std::env::args_os` method.
511 #[stable(feature = "env", since = "1.0.0")]
512 pub struct ArgsOs { inner: os_imp::Args }
514 /// Returns the arguments which this program was started with (normally passed
515 /// via the command line).
517 /// The first element is traditionally the path to the executable, but it can be
518 /// set to arbitrary text, and it may not even exist, so this property should
519 /// not be relied upon for security purposes.
523 /// The returned iterator will panic during iteration if any argument to the
524 /// process is not valid unicode. If this is not desired it is recommended to
525 /// use the `args_os` function instead.
532 /// // Prints each argument on a separate line
533 /// for argument in env::args() {
534 /// println!("{}", argument);
537 #[stable(feature = "env", since = "1.0.0")]
538 pub fn args() -> Args {
539 Args { inner: args_os() }
542 /// Returns the arguments which this program was started with (normally passed
543 /// via the command line).
545 /// The first element is traditionally the path to the executable, but it can be
546 /// set to arbitrary text, and it may not even exist, so this property should
547 /// not be relied upon for security purposes.
554 /// // Prints each argument on a separate line
555 /// for argument in env::args_os() {
556 /// println!("{:?}", argument);
559 #[stable(feature = "env", since = "1.0.0")]
560 pub fn args_os() -> ArgsOs {
561 ArgsOs { inner: os_imp::args() }
564 #[stable(feature = "env", since = "1.0.0")]
565 impl Iterator for Args {
567 fn next(&mut self) -> Option<String> {
568 self.inner.next().map(|s| s.into_string().unwrap())
570 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
573 #[stable(feature = "env", since = "1.0.0")]
574 impl ExactSizeIterator for Args {
575 fn len(&self) -> usize { self.inner.len() }
578 #[stable(feature = "env", since = "1.0.0")]
579 impl Iterator for ArgsOs {
580 type Item = OsString;
581 fn next(&mut self) -> Option<OsString> { self.inner.next() }
582 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
585 #[stable(feature = "env", since = "1.0.0")]
586 impl ExactSizeIterator for ArgsOs {
587 fn len(&self) -> usize { self.inner.len() }
590 /// Returns the page size of the current architecture in bytes.
591 #[unstable(feature = "page_size", reason = "naming and/or location may change")]
592 pub fn page_size() -> usize {
596 /// Constants associated with the current target
597 #[stable(feature = "env", since = "1.0.0")]
599 /// A string describing the architecture of the CPU that this is currently
601 #[stable(feature = "env", since = "1.0.0")]
602 pub const ARCH: &'static str = super::arch::ARCH;
604 /// The family of the operating system. In this case, `unix`.
605 #[stable(feature = "env", since = "1.0.0")]
606 pub const FAMILY: &'static str = super::os::FAMILY;
608 /// A string describing the specific operating system in use: in this
610 #[stable(feature = "env", since = "1.0.0")]
611 pub const OS: &'static str = super::os::OS;
613 /// Specifies the filename prefix used for shared libraries on this
614 /// platform: in this case, `lib`.
615 #[stable(feature = "env", since = "1.0.0")]
616 pub const DLL_PREFIX: &'static str = super::os::DLL_PREFIX;
618 /// Specifies the filename suffix used for shared libraries on this
619 /// platform: in this case, `.so`.
620 #[stable(feature = "env", since = "1.0.0")]
621 pub const DLL_SUFFIX: &'static str = super::os::DLL_SUFFIX;
623 /// Specifies the file extension used for shared libraries on this
624 /// platform that goes after the dot: in this case, `so`.
625 #[stable(feature = "env", since = "1.0.0")]
626 pub const DLL_EXTENSION: &'static str = super::os::DLL_EXTENSION;
628 /// Specifies the filename suffix used for executable binaries on this
629 /// platform: in this case, the empty string.
630 #[stable(feature = "env", since = "1.0.0")]
631 pub const EXE_SUFFIX: &'static str = super::os::EXE_SUFFIX;
633 /// Specifies the file extension, if any, used for executable binaries
634 /// on this platform: in this case, the empty string.
635 #[stable(feature = "env", since = "1.0.0")]
636 pub const EXE_EXTENSION: &'static str = super::os::EXE_EXTENSION;
640 #[cfg(target_os = "linux")]
642 pub const FAMILY: &'static str = "unix";
643 pub const OS: &'static str = "linux";
644 pub const DLL_PREFIX: &'static str = "lib";
645 pub const DLL_SUFFIX: &'static str = ".so";
646 pub const DLL_EXTENSION: &'static str = "so";
647 pub const EXE_SUFFIX: &'static str = "";
648 pub const EXE_EXTENSION: &'static str = "";
651 #[cfg(target_os = "macos")]
653 pub const FAMILY: &'static str = "unix";
654 pub const OS: &'static str = "macos";
655 pub const DLL_PREFIX: &'static str = "lib";
656 pub const DLL_SUFFIX: &'static str = ".dylib";
657 pub const DLL_EXTENSION: &'static str = "dylib";
658 pub const EXE_SUFFIX: &'static str = "";
659 pub const EXE_EXTENSION: &'static str = "";
662 #[cfg(target_os = "ios")]
664 pub const FAMILY: &'static str = "unix";
665 pub const OS: &'static str = "ios";
666 pub const DLL_PREFIX: &'static str = "lib";
667 pub const DLL_SUFFIX: &'static str = ".dylib";
668 pub const DLL_EXTENSION: &'static str = "dylib";
669 pub const EXE_SUFFIX: &'static str = "";
670 pub const EXE_EXTENSION: &'static str = "";
673 #[cfg(target_os = "freebsd")]
675 pub const FAMILY: &'static str = "unix";
676 pub const OS: &'static str = "freebsd";
677 pub const DLL_PREFIX: &'static str = "lib";
678 pub const DLL_SUFFIX: &'static str = ".so";
679 pub const DLL_EXTENSION: &'static str = "so";
680 pub const EXE_SUFFIX: &'static str = "";
681 pub const EXE_EXTENSION: &'static str = "";
684 #[cfg(target_os = "dragonfly")]
686 pub const FAMILY: &'static str = "unix";
687 pub const OS: &'static str = "dragonfly";
688 pub const DLL_PREFIX: &'static str = "lib";
689 pub const DLL_SUFFIX: &'static str = ".so";
690 pub const DLL_EXTENSION: &'static str = "so";
691 pub const EXE_SUFFIX: &'static str = "";
692 pub const EXE_EXTENSION: &'static str = "";
695 #[cfg(target_os = "bitrig")]
697 pub const FAMILY: &'static str = "unix";
698 pub const OS: &'static str = "bitrig";
699 pub const DLL_PREFIX: &'static str = "lib";
700 pub const DLL_SUFFIX: &'static str = ".so";
701 pub const DLL_EXTENSION: &'static str = "so";
702 pub const EXE_SUFFIX: &'static str = "";
703 pub const EXE_EXTENSION: &'static str = "";
706 #[cfg(target_os = "openbsd")]
708 pub const FAMILY: &'static str = "unix";
709 pub const OS: &'static str = "openbsd";
710 pub const DLL_PREFIX: &'static str = "lib";
711 pub const DLL_SUFFIX: &'static str = ".so";
712 pub const DLL_EXTENSION: &'static str = "so";
713 pub const EXE_SUFFIX: &'static str = "";
714 pub const EXE_EXTENSION: &'static str = "";
717 #[cfg(target_os = "android")]
719 pub const FAMILY: &'static str = "unix";
720 pub const OS: &'static str = "android";
721 pub const DLL_PREFIX: &'static str = "lib";
722 pub const DLL_SUFFIX: &'static str = ".so";
723 pub const DLL_EXTENSION: &'static str = "so";
724 pub const EXE_SUFFIX: &'static str = "";
725 pub const EXE_EXTENSION: &'static str = "";
728 #[cfg(target_os = "windows")]
730 pub const FAMILY: &'static str = "windows";
731 pub const OS: &'static str = "windows";
732 pub const DLL_PREFIX: &'static str = "";
733 pub const DLL_SUFFIX: &'static str = ".dll";
734 pub const DLL_EXTENSION: &'static str = "dll";
735 pub const EXE_SUFFIX: &'static str = ".exe";
736 pub const EXE_EXTENSION: &'static str = "exe";
739 #[cfg(target_arch = "x86")]
741 pub const ARCH: &'static str = "x86";
744 #[cfg(target_arch = "x86_64")]
746 pub const ARCH: &'static str = "x86_64";
749 #[cfg(target_arch = "arm")]
751 pub const ARCH: &'static str = "arm";
754 #[cfg(target_arch = "aarch64")]
756 pub const ARCH: &'static str = "aarch64";
759 #[cfg(target_arch = "mips")]
761 pub const ARCH: &'static str = "mips";
764 #[cfg(target_arch = "mipsel")]
766 pub const ARCH: &'static str = "mipsel";
769 #[cfg(target_arch = "powerpc")]
771 pub const ARCH: &'static str = "powerpc";
780 use rand::{self, Rng};
781 use ffi::{OsString, OsStr};
782 use path::{Path, PathBuf};
784 fn make_rand_name() -> OsString {
785 let mut rng = rand::thread_rng();
786 let n = format!("TEST{}", rng.gen_ascii_chars().take(10)
787 .collect::<String>());
788 let n = OsString::from(n);
789 assert!(var_os(&n).is_none());
793 fn eq(a: Option<OsString>, b: Option<&str>) {
794 assert_eq!(a.as_ref().map(|s| &**s), b.map(OsStr::new).map(|s| &*s));
799 let n = make_rand_name();
800 set_var(&n, "VALUE");
801 eq(var_os(&n), Some("VALUE"));
805 fn test_remove_var() {
806 let n = make_rand_name();
807 set_var(&n, "VALUE");
809 eq(var_os(&n), None);
813 fn test_set_var_overwrite() {
814 let n = make_rand_name();
817 eq(var_os(&n), Some("2"));
819 eq(var_os(&n), Some(""));
824 let mut s = "".to_string();
827 s.push_str("aaaaaaaaaa");
830 let n = make_rand_name();
832 eq(var_os(&n), Some(&s));
836 fn test_self_exe_path() {
837 let path = current_exe();
838 assert!(path.is_ok());
839 let path = path.unwrap();
841 // Hard to test this function
842 assert!(path.is_absolute());
846 fn test_env_set_get_huge() {
847 let n = make_rand_name();
848 let s = repeat("x").take(10000).collect::<String>();
850 eq(var_os(&n), Some(&s));
852 eq(var_os(&n), None);
856 fn test_env_set_var() {
857 let n = make_rand_name();
859 let mut e = vars_os();
860 set_var(&n, "VALUE");
861 assert!(!e.any(|(k, v)| {
862 &*k == &*n && &*v == "VALUE"
865 assert!(vars_os().any(|(k, v)| {
866 &*k == &*n && &*v == "VALUE"
872 assert!((!Path::new("test-path").is_absolute()));
874 current_dir().unwrap();
879 fn split_paths_windows() {
880 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
881 split_paths(unparsed).collect::<Vec<_>>() ==
882 parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
885 assert!(check_parse("", &mut [""]));
886 assert!(check_parse(r#""""#, &mut [""]));
887 assert!(check_parse(";;", &mut ["", "", ""]));
888 assert!(check_parse(r"c:\", &mut [r"c:\"]));
889 assert!(check_parse(r"c:\;", &mut [r"c:\", ""]));
890 assert!(check_parse(r"c:\;c:\Program Files\",
891 &mut [r"c:\", r"c:\Program Files\"]));
892 assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
893 assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
894 &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
899 fn split_paths_unix() {
900 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
901 split_paths(unparsed).collect::<Vec<_>>() ==
902 parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
905 assert!(check_parse("", &mut [""]));
906 assert!(check_parse("::", &mut ["", "", ""]));
907 assert!(check_parse("/", &mut ["/"]));
908 assert!(check_parse("/:", &mut ["/", ""]));
909 assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
914 fn join_paths_unix() {
915 fn test_eq(input: &[&str], output: &str) -> bool {
916 &*join_paths(input.iter().cloned()).unwrap() ==
920 assert!(test_eq(&[], ""));
921 assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"],
922 "/bin:/usr/bin:/usr/local/bin"));
923 assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""],
924 ":/bin:::/usr/bin:"));
925 assert!(join_paths(["/te:st"].iter().cloned()).is_err());
930 fn join_paths_windows() {
931 fn test_eq(input: &[&str], output: &str) -> bool {
932 &*join_paths(input.iter().cloned()).unwrap() ==
936 assert!(test_eq(&[], ""));
937 assert!(test_eq(&[r"c:\windows", r"c:\"],
939 assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""],
940 r";c:\windows;;;c:\;"));
941 assert!(test_eq(&[r"c:\te;st", r"c:\"],
942 r#""c:\te;st";c:\"#));
943 assert!(join_paths([r#"c:\te"st"#].iter().cloned()).is_err());