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 functions to inspect various aspects such as
14 //! environment variables, process arguments, the current directory, and various
15 //! other important directories.
17 #![stable(feature = "env", since = "1.0.0")]
20 use ffi::{OsStr, OsString};
23 use path::{Path, PathBuf};
25 use sys::os as os_imp;
27 /// Returns the current working directory as a [`PathBuf`].
31 /// Returns an [`Err`] if the current working directory value is invalid.
34 /// * Current directory does not exist.
35 /// * There are insufficient permissions to access the current directory.
37 /// [`PathBuf`]: ../../std/path/struct.PathBuf.html
38 /// [`Err`]: ../../std/result/enum.Result.html#method.err
45 /// // We assume that we are in a valid directory.
46 /// let p = env::current_dir().unwrap();
47 /// println!("The current directory is {}", p.display());
49 #[stable(feature = "env", since = "1.0.0")]
50 pub fn current_dir() -> io::Result<PathBuf> {
54 /// Changes the current working directory to the specified path, returning
55 /// whether the change was completed successfully or not.
61 /// use std::path::Path;
63 /// let root = Path::new("/");
64 /// assert!(env::set_current_dir(&root).is_ok());
65 /// println!("Successfully changed working directory to {}!", root.display());
67 #[stable(feature = "env", since = "1.0.0")]
68 pub fn set_current_dir<P: AsRef<Path>>(p: P) -> io::Result<()> {
69 os_imp::chdir(p.as_ref())
72 /// An iterator over a snapshot of the environment variables of this process.
74 /// This structure is created through the [`std::env::vars`] function.
76 /// [`std::env::vars`]: fn.vars.html
77 #[stable(feature = "env", since = "1.0.0")]
78 pub struct Vars { inner: VarsOs }
80 /// An iterator over a snapshot of the environment variables of this process.
82 /// This structure is created through the [`std::env::vars_os`] function.
84 /// [`std::env::vars_os`]: fn.vars_os.html
85 #[stable(feature = "env", since = "1.0.0")]
86 pub struct VarsOs { inner: os_imp::Env }
88 /// Returns an iterator of (variable, value) pairs of strings, for all the
89 /// environment variables of the current process.
91 /// The returned iterator contains a snapshot of the process's environment
92 /// variables at the time of this invocation. Modifications to environment
93 /// variables afterwards will not be reflected in the returned iterator.
97 /// While iterating, the returned iterator will panic if any key or value in the
98 /// environment is not valid unicode. If this is not desired, consider using the
99 /// `env::vars_os` function.
106 /// // We will iterate through the references to the element returned by
108 /// for (key, value) in env::vars() {
109 /// println!("{}: {}", key, value);
112 #[stable(feature = "env", since = "1.0.0")]
113 pub fn vars() -> Vars {
114 Vars { inner: vars_os() }
117 /// Returns an iterator of (variable, value) pairs of OS strings, for all the
118 /// environment variables of the current process.
120 /// The returned iterator contains a snapshot of the process's environment
121 /// variables at the time of this invocation. Modifications to environment
122 /// variables afterwards will not be reflected in the returned iterator.
129 /// // We will iterate through the references to the element returned by
130 /// // env::vars_os();
131 /// for (key, value) in env::vars_os() {
132 /// println!("{:?}: {:?}", key, value);
135 #[stable(feature = "env", since = "1.0.0")]
136 pub fn vars_os() -> VarsOs {
137 VarsOs { inner: os_imp::env() }
140 #[stable(feature = "env", since = "1.0.0")]
141 impl Iterator for Vars {
142 type Item = (String, String);
143 fn next(&mut self) -> Option<(String, String)> {
144 self.inner.next().map(|(a, b)| {
145 (a.into_string().unwrap(), b.into_string().unwrap())
148 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
151 #[stable(feature = "std_debug", since = "1.16.0")]
152 impl fmt::Debug for Vars {
153 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
158 #[stable(feature = "env", since = "1.0.0")]
159 impl Iterator for VarsOs {
160 type Item = (OsString, OsString);
161 fn next(&mut self) -> Option<(OsString, OsString)> { self.inner.next() }
162 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
165 #[stable(feature = "std_debug", since = "1.16.0")]
166 impl fmt::Debug for VarsOs {
167 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
168 f.pad("VarsOs { .. }")
172 /// Fetches the environment variable `key` from the current process.
174 /// The returned result is `Ok(s)` if the environment variable is present and is
175 /// valid unicode. If the environment variable is not present, or it is not
176 /// valid unicode, then `Err` will be returned.
183 /// let key = "HOME";
184 /// match env::var(key) {
185 /// Ok(val) => println!("{}: {:?}", key, val),
186 /// Err(e) => println!("couldn't interpret {}: {}", key, e),
189 #[stable(feature = "env", since = "1.0.0")]
190 pub fn var<K: AsRef<OsStr>>(key: K) -> Result<String, VarError> {
194 fn _var(key: &OsStr) -> Result<String, VarError> {
196 Some(s) => s.into_string().map_err(VarError::NotUnicode),
197 None => Err(VarError::NotPresent)
201 /// Fetches the environment variable `key` from the current process, returning
202 /// `None` if the variable isn't set.
209 /// let key = "HOME";
210 /// match env::var_os(key) {
211 /// Some(val) => println!("{}: {:?}", key, val),
212 /// None => println!("{} is not defined in the environment.", key)
215 #[stable(feature = "env", since = "1.0.0")]
216 pub fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> {
217 _var_os(key.as_ref())
220 fn _var_os(key: &OsStr) -> Option<OsString> {
221 os_imp::getenv(key).unwrap_or_else(|e| {
222 panic!("failed to get environment variable `{:?}`: {}", key, e)
226 /// Possible errors from the [`env::var`] function.
228 /// [`env::var`]: fn.var.html
229 #[derive(Debug, PartialEq, Eq, Clone)]
230 #[stable(feature = "env", since = "1.0.0")]
232 /// The specified environment variable was not present in the current
233 /// process's environment.
234 #[stable(feature = "env", since = "1.0.0")]
237 /// The specified environment variable was found, but it did not contain
238 /// valid unicode data. The found data is returned as a payload of this
240 #[stable(feature = "env", since = "1.0.0")]
241 NotUnicode(#[stable(feature = "env", since = "1.0.0")] OsString),
244 #[stable(feature = "env", since = "1.0.0")]
245 impl fmt::Display for VarError {
246 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
248 VarError::NotPresent => write!(f, "environment variable not found"),
249 VarError::NotUnicode(ref s) => {
250 write!(f, "environment variable was not valid unicode: {:?}", s)
256 #[stable(feature = "env", since = "1.0.0")]
257 impl Error for VarError {
258 fn description(&self) -> &str {
260 VarError::NotPresent => "environment variable not found",
261 VarError::NotUnicode(..) => "environment variable was not valid unicode",
266 /// Sets the environment variable `k` to the value `v` for the currently running
269 /// Note that while concurrent access to environment variables is safe in Rust,
270 /// some platforms only expose inherently unsafe non-threadsafe APIs for
271 /// inspecting the environment. As a result extra care needs to be taken when
272 /// auditing calls to unsafe external FFI functions to ensure that any external
273 /// environment accesses are properly synchronized with accesses in Rust.
275 /// Discussion of this unsafety on Unix may be found in:
277 /// - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188)
278 /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
282 /// This function may panic if `key` is empty, contains an ASCII equals sign
283 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
292 /// env::set_var(key, "VALUE");
293 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
295 #[stable(feature = "env", since = "1.0.0")]
296 pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(k: K, v: V) {
297 _set_var(k.as_ref(), v.as_ref())
300 fn _set_var(k: &OsStr, v: &OsStr) {
301 os_imp::setenv(k, v).unwrap_or_else(|e| {
302 panic!("failed to set environment variable `{:?}` to `{:?}`: {}",
307 /// Removes an environment variable from the environment of the currently running process.
309 /// Note that while concurrent access to environment variables is safe in Rust,
310 /// some platforms only expose inherently unsafe non-threadsafe APIs for
311 /// inspecting the environment. As a result extra care needs to be taken when
312 /// auditing calls to unsafe external FFI functions to ensure that any external
313 /// environment accesses are properly synchronized with accesses in Rust.
315 /// Discussion of this unsafety on Unix may be found in:
317 /// - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188)
318 /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
322 /// This function may panic if `key` is empty, contains an ASCII equals sign
323 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
332 /// env::set_var(key, "VALUE");
333 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
335 /// env::remove_var(key);
336 /// assert!(env::var(key).is_err());
338 #[stable(feature = "env", since = "1.0.0")]
339 pub fn remove_var<K: AsRef<OsStr>>(k: K) {
340 _remove_var(k.as_ref())
343 fn _remove_var(k: &OsStr) {
344 os_imp::unsetenv(k).unwrap_or_else(|e| {
345 panic!("failed to remove environment variable `{:?}`: {}", k, e)
349 /// An iterator over `PathBuf` instances for parsing an environment variable
350 /// according to platform-specific conventions.
352 /// This structure is returned from `std::env::split_paths`.
353 #[stable(feature = "env", since = "1.0.0")]
354 pub struct SplitPaths<'a> { inner: os_imp::SplitPaths<'a> }
356 /// Parses input according to platform conventions for the `PATH`
357 /// environment variable.
359 /// Returns an iterator over the paths contained in `unparsed`.
366 /// let key = "PATH";
367 /// match env::var_os(key) {
369 /// for path in env::split_paths(&paths) {
370 /// println!("'{}'", path.display());
373 /// None => println!("{} is not defined in the environment.", key)
376 #[stable(feature = "env", since = "1.0.0")]
377 pub fn split_paths<T: AsRef<OsStr> + ?Sized>(unparsed: &T) -> SplitPaths {
378 SplitPaths { inner: os_imp::split_paths(unparsed.as_ref()) }
381 #[stable(feature = "env", since = "1.0.0")]
382 impl<'a> Iterator for SplitPaths<'a> {
384 fn next(&mut self) -> Option<PathBuf> { self.inner.next() }
385 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
388 #[stable(feature = "std_debug", since = "1.16.0")]
389 impl<'a> fmt::Debug for SplitPaths<'a> {
390 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
391 f.pad("SplitPaths { .. }")
395 /// Error type returned from `std::env::join_paths` when paths fail to be
398 #[stable(feature = "env", since = "1.0.0")]
399 pub struct JoinPathsError {
400 inner: os_imp::JoinPathsError
403 /// Joins a collection of [`Path`]s appropriately for the `PATH`
404 /// environment variable.
406 /// Returns an [`OsString`] on success.
408 /// Returns an [`Err`][err] (containing an error message) if one of the input
409 /// [`Path`]s contains an invalid character for constructing the `PATH`
410 /// variable (a double quote on Windows or a colon on Unix).
412 /// [`Path`]: ../../std/path/struct.Path.html
413 /// [`OsString`]: ../../std/ffi/struct.OsString.html
414 /// [err]: ../../std/result/enum.Result.html#variant.Err
420 /// use std::path::PathBuf;
422 /// if let Some(path) = env::var_os("PATH") {
423 /// let mut paths = env::split_paths(&path).collect::<Vec<_>>();
424 /// paths.push(PathBuf::from("/home/xyz/bin"));
425 /// let new_path = env::join_paths(paths).unwrap();
426 /// env::set_var("PATH", &new_path);
429 #[stable(feature = "env", since = "1.0.0")]
430 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
431 where I: IntoIterator<Item=T>, T: AsRef<OsStr>
433 os_imp::join_paths(paths.into_iter()).map_err(|e| {
434 JoinPathsError { inner: e }
438 #[stable(feature = "env", since = "1.0.0")]
439 impl fmt::Display for JoinPathsError {
440 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
445 #[stable(feature = "env", since = "1.0.0")]
446 impl Error for JoinPathsError {
447 fn description(&self) -> &str { self.inner.description() }
450 /// Returns the path of the current user's home directory if known.
454 /// Returns the value of the 'HOME' environment variable if it is set
455 /// and not equal to the empty string. Otherwise, it tries to determine the
456 /// home directory by invoking the `getpwuid_r` function on the UID of the
461 /// Returns the value of the 'HOME' environment variable if it is
462 /// set and not equal to the empty string. Otherwise, returns the value of the
463 /// 'USERPROFILE' environment variable if it is set and not equal to the empty
464 /// string. If both do not exist, [`GetUserProfileDirectory`][msdn] is used to
465 /// return the appropriate path.
467 /// [msdn]: https://msdn.microsoft.com/en-us/library/windows/desktop/bb762280(v=vs.85).aspx
474 /// match env::home_dir() {
475 /// Some(path) => println!("{}", path.display()),
476 /// None => println!("Impossible to get your home dir!"),
479 #[stable(feature = "env", since = "1.0.0")]
480 pub fn home_dir() -> Option<PathBuf> {
484 /// Returns the path of a temporary directory.
486 /// On Unix, returns the value of the `TMPDIR` environment variable if it is
487 /// set, otherwise for non-Android it returns `/tmp`. If Android, since there
488 /// is no global temporary folder (it is usually allocated per-app), it returns
489 /// `/data/local/tmp`.
491 /// On Windows, returns the value of, in order, the `TMP`, `TEMP`,
492 /// `USERPROFILE` environment variable if any are set and not the empty
493 /// string. Otherwise, `temp_dir` returns the path of the Windows directory.
494 /// This behavior is identical to that of [`GetTempPath`][msdn], which this
495 /// function uses internally.
497 /// [msdn]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa364992(v=vs.85).aspx
501 /// use std::fs::File;
503 /// # fn foo() -> std::io::Result<()> {
504 /// let mut dir = env::temp_dir();
505 /// dir.push("foo.txt");
507 /// let f = File::create(dir)?;
511 #[stable(feature = "env", since = "1.0.0")]
512 pub fn temp_dir() -> PathBuf {
516 /// Returns the full filesystem path of the current running executable.
518 /// The path returned is not necessarily a "real path" of the executable as
519 /// there may be intermediate symlinks.
523 /// Acquiring the path of the current executable is a platform-specific operation
524 /// that can fail for a good number of reasons. Some errors can include, but not
525 /// be limited to, filesystem operations failing or general syscall failures.
529 /// The output of this function should not be used in anything that might have
530 /// security implications. For example:
534 /// println!("{:?}", std::env::current_exe());
538 /// On Linux systems, if this is compiled as `foo`:
543 /// Ok("/home/alex/foo")
546 /// And you make a symbolic link of the program:
552 /// When you run it, you won't get the original executable, you'll get the
557 /// Ok("/home/alex/bar")
560 /// This sort of behavior has been known to [lead to privilege escalation] when
561 /// used incorrectly, for example.
563 /// [lead to privilege escalation]: http://securityvulns.com/Wdocument183.html
570 /// match env::current_exe() {
571 /// Ok(exe_path) => println!("Path of this executable is: {}",
572 /// exe_path.display()),
573 /// Err(e) => println!("failed to get current exe path: {}", e),
576 #[stable(feature = "env", since = "1.0.0")]
577 pub fn current_exe() -> io::Result<PathBuf> {
578 os_imp::current_exe()
581 /// An iterator over the arguments of a process, yielding a [`String`] value
582 /// for each argument.
584 /// This structure is created through the [`std::env::args`] function.
586 /// [`String`]: ../string/struct.String.html
587 /// [`std::env::args`]: ./fn.args.html
588 #[stable(feature = "env", since = "1.0.0")]
589 pub struct Args { inner: ArgsOs }
591 /// An iterator over the arguments of a process, yielding an [`OsString`] value
592 /// for each argument.
594 /// This structure is created through the [`std::env::args_os`] function.
596 /// [`OsString`]: ../ffi/struct.OsString.html
597 /// [`std::env::args_os`]: ./fn.args_os.html
598 #[stable(feature = "env", since = "1.0.0")]
599 pub struct ArgsOs { inner: sys::args::Args }
601 /// Returns the arguments which this program was started with (normally passed
602 /// via the command line).
604 /// The first element is traditionally the path of the executable, but it can be
605 /// set to arbitrary text, and may not even exist. This means this property should
606 /// not be relied upon for security purposes.
610 /// The returned iterator will panic during iteration if any argument to the
611 /// process is not valid unicode. If this is not desired,
612 /// use the [`args_os`] function instead.
619 /// // Prints each argument on a separate line
620 /// for argument in env::args() {
621 /// println!("{}", argument);
625 /// [`args_os`]: ./fn.args_os.html
626 #[stable(feature = "env", since = "1.0.0")]
627 pub fn args() -> Args {
628 Args { inner: args_os() }
631 /// Returns the arguments which this program was started with (normally passed
632 /// via the command line).
634 /// The first element is traditionally the path of the executable, but it can be
635 /// set to arbitrary text, and it may not even exist, so this property should
636 /// not be relied upon for security purposes.
643 /// // Prints each argument on a separate line
644 /// for argument in env::args_os() {
645 /// println!("{:?}", argument);
648 #[stable(feature = "env", since = "1.0.0")]
649 pub fn args_os() -> ArgsOs {
650 ArgsOs { inner: sys::args::args() }
653 #[stable(feature = "env", since = "1.0.0")]
654 impl Iterator for Args {
656 fn next(&mut self) -> Option<String> {
657 self.inner.next().map(|s| s.into_string().unwrap())
659 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
662 #[stable(feature = "env", since = "1.0.0")]
663 impl ExactSizeIterator for Args {
664 fn len(&self) -> usize { self.inner.len() }
665 fn is_empty(&self) -> bool { self.inner.is_empty() }
668 #[stable(feature = "env_iterators", since = "1.11.0")]
669 impl DoubleEndedIterator for Args {
670 fn next_back(&mut self) -> Option<String> {
671 self.inner.next_back().map(|s| s.into_string().unwrap())
675 #[stable(feature = "std_debug", since = "1.16.0")]
676 impl fmt::Debug for Args {
677 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
682 #[stable(feature = "env", since = "1.0.0")]
683 impl Iterator for ArgsOs {
684 type Item = OsString;
685 fn next(&mut self) -> Option<OsString> { self.inner.next() }
686 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
689 #[stable(feature = "env", since = "1.0.0")]
690 impl ExactSizeIterator for ArgsOs {
691 fn len(&self) -> usize { self.inner.len() }
692 fn is_empty(&self) -> bool { self.inner.is_empty() }
695 #[stable(feature = "env_iterators", since = "1.11.0")]
696 impl DoubleEndedIterator for ArgsOs {
697 fn next_back(&mut self) -> Option<OsString> { self.inner.next_back() }
700 #[stable(feature = "std_debug", since = "1.16.0")]
701 impl fmt::Debug for ArgsOs {
702 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
703 f.pad("ArgsOs { .. }")
707 /// Constants associated with the current target
708 #[stable(feature = "env", since = "1.0.0")]
712 /// A string describing the architecture of the CPU that is currently
715 /// Some possible values:
727 #[stable(feature = "env", since = "1.0.0")]
728 pub const ARCH: &'static str = super::arch::ARCH;
730 /// The family of the operating system. Example value is `unix`.
732 /// Some possible values:
736 #[stable(feature = "env", since = "1.0.0")]
737 pub const FAMILY: &'static str = os::FAMILY;
739 /// A string describing the specific operating system in use.
740 /// Example value is `linux`.
742 /// Some possible values:
755 #[stable(feature = "env", since = "1.0.0")]
756 pub const OS: &'static str = os::OS;
758 /// Specifies the filename prefix used for shared libraries on this
759 /// platform. Example value is `lib`.
761 /// Some possible values:
764 /// - `""` (an empty string)
765 #[stable(feature = "env", since = "1.0.0")]
766 pub const DLL_PREFIX: &'static str = os::DLL_PREFIX;
768 /// Specifies the filename suffix used for shared libraries on this
769 /// platform. Example value is `.so`.
771 /// Some possible values:
776 #[stable(feature = "env", since = "1.0.0")]
777 pub const DLL_SUFFIX: &'static str = os::DLL_SUFFIX;
779 /// Specifies the file extension used for shared libraries on this
780 /// platform that goes after the dot. Example value is `so`.
782 /// Some possible values:
787 #[stable(feature = "env", since = "1.0.0")]
788 pub const DLL_EXTENSION: &'static str = os::DLL_EXTENSION;
790 /// Specifies the filename suffix used for executable binaries on this
791 /// platform. Example value is `.exe`.
793 /// Some possible values:
798 /// - `""` (an empty string)
799 #[stable(feature = "env", since = "1.0.0")]
800 pub const EXE_SUFFIX: &'static str = os::EXE_SUFFIX;
802 /// Specifies the file extension, if any, used for executable binaries
803 /// on this platform. Example value is `exe`.
805 /// Some possible values:
808 /// - `""` (an empty string)
809 #[stable(feature = "env", since = "1.0.0")]
810 pub const EXE_EXTENSION: &'static str = os::EXE_EXTENSION;
813 #[cfg(target_arch = "x86")]
815 pub const ARCH: &'static str = "x86";
818 #[cfg(target_arch = "x86_64")]
820 pub const ARCH: &'static str = "x86_64";
823 #[cfg(target_arch = "arm")]
825 pub const ARCH: &'static str = "arm";
828 #[cfg(target_arch = "aarch64")]
830 pub const ARCH: &'static str = "aarch64";
833 #[cfg(target_arch = "mips")]
835 pub const ARCH: &'static str = "mips";
838 #[cfg(target_arch = "mips64")]
840 pub const ARCH: &'static str = "mips64";
843 #[cfg(target_arch = "powerpc")]
845 pub const ARCH: &'static str = "powerpc";
848 #[cfg(target_arch = "powerpc64")]
850 pub const ARCH: &'static str = "powerpc64";
853 #[cfg(target_arch = "s390x")]
855 pub const ARCH: &'static str = "s390x";
858 #[cfg(target_arch = "sparc64")]
860 pub const ARCH: &'static str = "sparc64";
863 #[cfg(target_arch = "le32")]
865 pub const ARCH: &'static str = "le32";
868 #[cfg(target_arch = "asmjs")]
870 pub const ARCH: &'static str = "asmjs";
873 #[cfg(target_arch = "wasm32")]
875 pub const ARCH: &'static str = "wasm32";
883 use rand::{self, Rng};
884 use ffi::{OsString, OsStr};
885 use path::{Path, PathBuf};
887 fn make_rand_name() -> OsString {
888 let mut rng = rand::thread_rng();
889 let n = format!("TEST{}", rng.gen_ascii_chars().take(10)
890 .collect::<String>());
891 let n = OsString::from(n);
892 assert!(var_os(&n).is_none());
896 fn eq(a: Option<OsString>, b: Option<&str>) {
897 assert_eq!(a.as_ref().map(|s| &**s), b.map(OsStr::new).map(|s| &*s));
902 let n = make_rand_name();
903 set_var(&n, "VALUE");
904 eq(var_os(&n), Some("VALUE"));
908 fn test_remove_var() {
909 let n = make_rand_name();
910 set_var(&n, "VALUE");
912 eq(var_os(&n), None);
916 fn test_set_var_overwrite() {
917 let n = make_rand_name();
920 eq(var_os(&n), Some("2"));
922 eq(var_os(&n), Some(""));
926 #[cfg_attr(target_os = "emscripten", ignore)]
928 let mut s = "".to_string();
931 s.push_str("aaaaaaaaaa");
934 let n = make_rand_name();
936 eq(var_os(&n), Some(&s));
940 #[cfg_attr(target_os = "emscripten", ignore)]
941 fn test_self_exe_path() {
942 let path = current_exe();
943 assert!(path.is_ok());
944 let path = path.unwrap();
946 // Hard to test this function
947 assert!(path.is_absolute());
951 #[cfg_attr(target_os = "emscripten", ignore)]
952 fn test_env_set_get_huge() {
953 let n = make_rand_name();
954 let s = repeat("x").take(10000).collect::<String>();
956 eq(var_os(&n), Some(&s));
958 eq(var_os(&n), None);
962 fn test_env_set_var() {
963 let n = make_rand_name();
965 let mut e = vars_os();
966 set_var(&n, "VALUE");
967 assert!(!e.any(|(k, v)| {
968 &*k == &*n && &*v == "VALUE"
971 assert!(vars_os().any(|(k, v)| {
972 &*k == &*n && &*v == "VALUE"
978 assert!((!Path::new("test-path").is_absolute()));
980 current_dir().unwrap();
985 fn split_paths_windows() {
986 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
987 split_paths(unparsed).collect::<Vec<_>>() ==
988 parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
991 assert!(check_parse("", &mut [""]));
992 assert!(check_parse(r#""""#, &mut [""]));
993 assert!(check_parse(";;", &mut ["", "", ""]));
994 assert!(check_parse(r"c:\", &mut [r"c:\"]));
995 assert!(check_parse(r"c:\;", &mut [r"c:\", ""]));
996 assert!(check_parse(r"c:\;c:\Program Files\",
997 &mut [r"c:\", r"c:\Program Files\"]));
998 assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
999 assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
1000 &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
1005 fn split_paths_unix() {
1006 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1007 split_paths(unparsed).collect::<Vec<_>>() ==
1008 parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
1011 assert!(check_parse("", &mut [""]));
1012 assert!(check_parse("::", &mut ["", "", ""]));
1013 assert!(check_parse("/", &mut ["/"]));
1014 assert!(check_parse("/:", &mut ["/", ""]));
1015 assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
1020 fn join_paths_unix() {
1021 fn test_eq(input: &[&str], output: &str) -> bool {
1022 &*join_paths(input.iter().cloned()).unwrap() ==
1026 assert!(test_eq(&[], ""));
1027 assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"],
1028 "/bin:/usr/bin:/usr/local/bin"));
1029 assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""],
1030 ":/bin:::/usr/bin:"));
1031 assert!(join_paths(["/te:st"].iter().cloned()).is_err());
1036 fn join_paths_windows() {
1037 fn test_eq(input: &[&str], output: &str) -> bool {
1038 &*join_paths(input.iter().cloned()).unwrap() ==
1042 assert!(test_eq(&[], ""));
1043 assert!(test_eq(&[r"c:\windows", r"c:\"],
1044 r"c:\windows;c:\"));
1045 assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""],
1046 r";c:\windows;;;c:\;"));
1047 assert!(test_eq(&[r"c:\te;st", r"c:\"],
1048 r#""c:\te;st";c:\"#));
1049 assert!(join_paths([r#"c:\te"st"#].iter().cloned()).is_err());