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.
101 /// [`env::vars_os`]: fn.vars_os.html
108 /// // We will iterate through the references to the element returned by
110 /// for (key, value) in env::vars() {
111 /// println!("{}: {}", key, value);
114 #[stable(feature = "env", since = "1.0.0")]
115 pub fn vars() -> Vars {
116 Vars { inner: vars_os() }
119 /// Returns an iterator of (variable, value) pairs of OS strings, for all the
120 /// environment variables of the current process.
122 /// The returned iterator contains a snapshot of the process's environment
123 /// variables at the time of this invocation. Modifications to environment
124 /// variables afterwards will not be reflected in the returned iterator.
131 /// // We will iterate through the references to the element returned by
132 /// // env::vars_os();
133 /// for (key, value) in env::vars_os() {
134 /// println!("{:?}: {:?}", key, value);
137 #[stable(feature = "env", since = "1.0.0")]
138 pub fn vars_os() -> VarsOs {
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 = "std_debug", since = "1.16.0")]
154 impl fmt::Debug for Vars {
155 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
160 #[stable(feature = "env", since = "1.0.0")]
161 impl Iterator for VarsOs {
162 type Item = (OsString, OsString);
163 fn next(&mut self) -> Option<(OsString, OsString)> { self.inner.next() }
164 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
167 #[stable(feature = "std_debug", since = "1.16.0")]
168 impl fmt::Debug for VarsOs {
169 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
170 f.pad("VarsOs { .. }")
174 /// Fetches the environment variable `key` from the current process.
176 /// The returned result is [`Ok(s)`] if the environment variable is present and is
177 /// valid unicode. If the environment variable is not present, or it is not
178 /// valid unicode, then [`Err`] will be returned.
180 /// [`Ok(s)`]: ../result/enum.Result.html#variant.Ok
181 /// [`Err`]: ../result/enum.Result.html#variant.Err
188 /// let key = "HOME";
189 /// match env::var(key) {
190 /// Ok(val) => println!("{}: {:?}", key, val),
191 /// Err(e) => println!("couldn't interpret {}: {}", key, e),
194 #[stable(feature = "env", since = "1.0.0")]
195 pub fn var<K: AsRef<OsStr>>(key: K) -> Result<String, VarError> {
199 fn _var(key: &OsStr) -> Result<String, VarError> {
201 Some(s) => s.into_string().map_err(VarError::NotUnicode),
202 None => Err(VarError::NotPresent)
206 /// Fetches the environment variable `key` from the current process, returning
207 /// [`None`] if the variable isn't set.
209 /// [`None`]: ../option/enum.Option.html#variant.None
216 /// let key = "HOME";
217 /// match env::var_os(key) {
218 /// Some(val) => println!("{}: {:?}", key, val),
219 /// None => println!("{} is not defined in the environment.", key)
222 #[stable(feature = "env", since = "1.0.0")]
223 pub fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> {
224 _var_os(key.as_ref())
227 fn _var_os(key: &OsStr) -> Option<OsString> {
228 os_imp::getenv(key).unwrap_or_else(|e| {
229 panic!("failed to get environment variable `{:?}`: {}", key, e)
233 /// Possible errors from the [`env::var`] function.
235 /// [`env::var`]: fn.var.html
236 #[derive(Debug, PartialEq, Eq, Clone)]
237 #[stable(feature = "env", since = "1.0.0")]
239 /// The specified environment variable was not present in the current
240 /// process's environment.
241 #[stable(feature = "env", since = "1.0.0")]
244 /// The specified environment variable was found, but it did not contain
245 /// valid unicode data. The found data is returned as a payload of this
247 #[stable(feature = "env", since = "1.0.0")]
248 NotUnicode(#[stable(feature = "env", since = "1.0.0")] OsString),
251 #[stable(feature = "env", since = "1.0.0")]
252 impl fmt::Display for VarError {
253 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
255 VarError::NotPresent => write!(f, "environment variable not found"),
256 VarError::NotUnicode(ref s) => {
257 write!(f, "environment variable was not valid unicode: {:?}", s)
263 #[stable(feature = "env", since = "1.0.0")]
264 impl Error for VarError {
265 fn description(&self) -> &str {
267 VarError::NotPresent => "environment variable not found",
268 VarError::NotUnicode(..) => "environment variable was not valid unicode",
273 /// Sets the environment variable `k` to the value `v` for the currently running
276 /// Note that while concurrent access to environment variables is safe in Rust,
277 /// some platforms only expose inherently unsafe non-threadsafe APIs for
278 /// inspecting the environment. As a result extra care needs to be taken when
279 /// auditing calls to unsafe external FFI functions to ensure that any external
280 /// environment accesses are properly synchronized with accesses in Rust.
282 /// Discussion of this unsafety on Unix may be found in:
284 /// - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188)
285 /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
289 /// This function may panic if `key` is empty, contains an ASCII equals sign
290 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
299 /// env::set_var(key, "VALUE");
300 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
302 #[stable(feature = "env", since = "1.0.0")]
303 pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(k: K, v: V) {
304 _set_var(k.as_ref(), v.as_ref())
307 fn _set_var(k: &OsStr, v: &OsStr) {
308 os_imp::setenv(k, v).unwrap_or_else(|e| {
309 panic!("failed to set environment variable `{:?}` to `{:?}`: {}",
314 /// Removes an environment variable from the environment of the currently running process.
316 /// Note that while concurrent access to environment variables is safe in Rust,
317 /// some platforms only expose inherently unsafe non-threadsafe APIs for
318 /// inspecting the environment. As a result extra care needs to be taken when
319 /// auditing calls to unsafe external FFI functions to ensure that any external
320 /// environment accesses are properly synchronized with accesses in Rust.
322 /// Discussion of this unsafety on Unix may be found in:
324 /// - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188)
325 /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
329 /// This function may panic if `key` is empty, contains an ASCII equals sign
330 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
339 /// env::set_var(key, "VALUE");
340 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
342 /// env::remove_var(key);
343 /// assert!(env::var(key).is_err());
345 #[stable(feature = "env", since = "1.0.0")]
346 pub fn remove_var<K: AsRef<OsStr>>(k: K) {
347 _remove_var(k.as_ref())
350 fn _remove_var(k: &OsStr) {
351 os_imp::unsetenv(k).unwrap_or_else(|e| {
352 panic!("failed to remove environment variable `{:?}`: {}", k, e)
356 /// An iterator over `PathBuf` instances for parsing an environment variable
357 /// according to platform-specific conventions.
359 /// This structure is returned from `std::env::split_paths`.
360 #[stable(feature = "env", since = "1.0.0")]
361 pub struct SplitPaths<'a> { inner: os_imp::SplitPaths<'a> }
363 /// Parses input according to platform conventions for the `PATH`
364 /// environment variable.
366 /// Returns an iterator over the paths contained in `unparsed`.
373 /// let key = "PATH";
374 /// match env::var_os(key) {
376 /// for path in env::split_paths(&paths) {
377 /// println!("'{}'", path.display());
380 /// None => println!("{} is not defined in the environment.", key)
383 #[stable(feature = "env", since = "1.0.0")]
384 pub fn split_paths<T: AsRef<OsStr> + ?Sized>(unparsed: &T) -> SplitPaths {
385 SplitPaths { inner: os_imp::split_paths(unparsed.as_ref()) }
388 #[stable(feature = "env", since = "1.0.0")]
389 impl<'a> Iterator for SplitPaths<'a> {
391 fn next(&mut self) -> Option<PathBuf> { self.inner.next() }
392 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
395 #[stable(feature = "std_debug", since = "1.16.0")]
396 impl<'a> fmt::Debug for SplitPaths<'a> {
397 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
398 f.pad("SplitPaths { .. }")
402 /// Error type returned from `std::env::join_paths` when paths fail to be
405 #[stable(feature = "env", since = "1.0.0")]
406 pub struct JoinPathsError {
407 inner: os_imp::JoinPathsError
410 /// Joins a collection of [`Path`]s appropriately for the `PATH`
411 /// environment variable.
413 /// Returns an [`OsString`] on success.
415 /// Returns an [`Err`][err] (containing an error message) if one of the input
416 /// [`Path`]s contains an invalid character for constructing the `PATH`
417 /// variable (a double quote on Windows or a colon on Unix).
419 /// [`Path`]: ../../std/path/struct.Path.html
420 /// [`OsString`]: ../../std/ffi/struct.OsString.html
421 /// [err]: ../../std/result/enum.Result.html#variant.Err
427 /// use std::path::PathBuf;
429 /// if let Some(path) = env::var_os("PATH") {
430 /// let mut paths = env::split_paths(&path).collect::<Vec<_>>();
431 /// paths.push(PathBuf::from("/home/xyz/bin"));
432 /// let new_path = env::join_paths(paths).unwrap();
433 /// env::set_var("PATH", &new_path);
436 #[stable(feature = "env", since = "1.0.0")]
437 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
438 where I: IntoIterator<Item=T>, T: AsRef<OsStr>
440 os_imp::join_paths(paths.into_iter()).map_err(|e| {
441 JoinPathsError { inner: e }
445 #[stable(feature = "env", since = "1.0.0")]
446 impl fmt::Display for JoinPathsError {
447 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
452 #[stable(feature = "env", since = "1.0.0")]
453 impl Error for JoinPathsError {
454 fn description(&self) -> &str { self.inner.description() }
457 /// Returns the path of the current user's home directory if known.
461 /// Returns the value of the 'HOME' environment variable if it is set
462 /// and not equal to the empty string. Otherwise, it tries to determine the
463 /// home directory by invoking the `getpwuid_r` function on the UID of the
468 /// Returns the value of the 'HOME' environment variable if it is
469 /// set and not equal to the empty string. Otherwise, returns the value of the
470 /// 'USERPROFILE' environment variable if it is set and not equal to the empty
471 /// string. If both do not exist, [`GetUserProfileDirectory`][msdn] is used to
472 /// return the appropriate path.
474 /// [msdn]: https://msdn.microsoft.com/en-us/library/windows/desktop/bb762280(v=vs.85).aspx
481 /// match env::home_dir() {
482 /// Some(path) => println!("{}", path.display()),
483 /// None => println!("Impossible to get your home dir!"),
486 #[stable(feature = "env", since = "1.0.0")]
487 pub fn home_dir() -> Option<PathBuf> {
491 /// Returns the path of a temporary directory.
493 /// On Unix, returns the value of the `TMPDIR` environment variable if it is
494 /// set, otherwise for non-Android it returns `/tmp`. If Android, since there
495 /// is no global temporary folder (it is usually allocated per-app), it returns
496 /// `/data/local/tmp`.
498 /// On Windows, returns the value of, in order, the `TMP`, `TEMP`,
499 /// `USERPROFILE` environment variable if any are set and not the empty
500 /// string. Otherwise, `temp_dir` returns the path of the Windows directory.
501 /// This behavior is identical to that of [`GetTempPath`][msdn], which this
502 /// function uses internally.
504 /// [msdn]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa364992(v=vs.85).aspx
508 /// use std::fs::File;
510 /// # fn foo() -> std::io::Result<()> {
511 /// let mut dir = env::temp_dir();
512 /// dir.push("foo.txt");
514 /// let f = File::create(dir)?;
518 #[stable(feature = "env", since = "1.0.0")]
519 pub fn temp_dir() -> PathBuf {
523 /// Returns the full filesystem path of the current running executable.
525 /// The path returned is not necessarily a "real path" of the executable as
526 /// there may be intermediate symlinks.
530 /// Acquiring the path of the current executable is a platform-specific operation
531 /// that can fail for a good number of reasons. Some errors can include, but not
532 /// be limited to, filesystem operations failing or general syscall failures.
536 /// The output of this function should not be used in anything that might have
537 /// security implications. For example:
541 /// println!("{:?}", std::env::current_exe());
545 /// On Linux systems, if this is compiled as `foo`:
550 /// Ok("/home/alex/foo")
553 /// And you make a symbolic link of the program:
559 /// When you run it, you won't get the original executable, you'll get the
564 /// Ok("/home/alex/bar")
567 /// This sort of behavior has been known to [lead to privilege escalation] when
568 /// used incorrectly, for example.
570 /// [lead to privilege escalation]: http://securityvulns.com/Wdocument183.html
577 /// match env::current_exe() {
578 /// Ok(exe_path) => println!("Path of this executable is: {}",
579 /// exe_path.display()),
580 /// Err(e) => println!("failed to get current exe path: {}", e),
583 #[stable(feature = "env", since = "1.0.0")]
584 pub fn current_exe() -> io::Result<PathBuf> {
585 os_imp::current_exe()
588 /// An iterator over the arguments of a process, yielding a [`String`] value
589 /// for each argument.
591 /// This structure is created through the [`std::env::args`] function.
593 /// The first element is traditionally the path of the executable, but it can be
594 /// set to arbitrary text, and may not even exist. This means this property should
595 /// not be relied upon for security purposes.
597 /// [`String`]: ../string/struct.String.html
598 /// [`std::env::args`]: ./fn.args.html
599 #[stable(feature = "env", since = "1.0.0")]
600 pub struct Args { inner: ArgsOs }
602 /// An iterator over the arguments of a process, yielding an [`OsString`] value
603 /// for each argument.
605 /// This structure is created through the [`std::env::args_os`] function.
607 /// The first element is traditionally the path of the executable, but it can be
608 /// set to arbitrary text, and may not even exist. This means this property should
609 /// not be relied upon for security purposes.
611 /// [`OsString`]: ../ffi/struct.OsString.html
612 /// [`std::env::args_os`]: ./fn.args_os.html
613 #[stable(feature = "env", since = "1.0.0")]
614 pub struct ArgsOs { inner: sys::args::Args }
616 /// Returns the arguments which this program was started with (normally passed
617 /// via the command line).
619 /// The first element is traditionally the path of the executable, but it can be
620 /// set to arbitrary text, and may not even exist. This means this property should
621 /// not be relied upon for security purposes.
625 /// The returned iterator will panic during iteration if any argument to the
626 /// process is not valid unicode. If this is not desired,
627 /// use the [`args_os`] function instead.
634 /// // Prints each argument on a separate line
635 /// for argument in env::args() {
636 /// println!("{}", argument);
640 /// [`args_os`]: ./fn.args_os.html
641 #[stable(feature = "env", since = "1.0.0")]
642 pub fn args() -> Args {
643 Args { inner: args_os() }
646 /// Returns the arguments which this program was started with (normally passed
647 /// via the command line).
649 /// The first element is traditionally the path of the executable, but it can be
650 /// set to arbitrary text, and it may not even exist, so this property should
651 /// not be relied upon for security purposes.
658 /// // Prints each argument on a separate line
659 /// for argument in env::args_os() {
660 /// println!("{:?}", argument);
663 #[stable(feature = "env", since = "1.0.0")]
664 pub fn args_os() -> ArgsOs {
665 ArgsOs { inner: sys::args::args() }
668 #[stable(feature = "env", since = "1.0.0")]
669 impl Iterator for Args {
671 fn next(&mut self) -> Option<String> {
672 self.inner.next().map(|s| s.into_string().unwrap())
674 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
677 #[stable(feature = "env", since = "1.0.0")]
678 impl ExactSizeIterator for Args {
679 fn len(&self) -> usize { self.inner.len() }
680 fn is_empty(&self) -> bool { self.inner.is_empty() }
683 #[stable(feature = "env_iterators", since = "1.12.0")]
684 impl DoubleEndedIterator for Args {
685 fn next_back(&mut self) -> Option<String> {
686 self.inner.next_back().map(|s| s.into_string().unwrap())
690 #[stable(feature = "std_debug", since = "1.16.0")]
691 impl fmt::Debug for Args {
692 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
697 #[stable(feature = "env", since = "1.0.0")]
698 impl Iterator for ArgsOs {
699 type Item = OsString;
700 fn next(&mut self) -> Option<OsString> { self.inner.next() }
701 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
704 #[stable(feature = "env", since = "1.0.0")]
705 impl ExactSizeIterator for ArgsOs {
706 fn len(&self) -> usize { self.inner.len() }
707 fn is_empty(&self) -> bool { self.inner.is_empty() }
710 #[stable(feature = "env_iterators", since = "1.12.0")]
711 impl DoubleEndedIterator for ArgsOs {
712 fn next_back(&mut self) -> Option<OsString> { self.inner.next_back() }
715 #[stable(feature = "std_debug", since = "1.16.0")]
716 impl fmt::Debug for ArgsOs {
717 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
718 f.pad("ArgsOs { .. }")
722 /// Constants associated with the current target
723 #[stable(feature = "env", since = "1.0.0")]
727 /// A string describing the architecture of the CPU that is currently
730 /// Some possible values:
742 #[stable(feature = "env", since = "1.0.0")]
743 pub const ARCH: &'static str = super::arch::ARCH;
745 /// The family of the operating system. Example value is `unix`.
747 /// Some possible values:
751 #[stable(feature = "env", since = "1.0.0")]
752 pub const FAMILY: &'static str = os::FAMILY;
754 /// A string describing the specific operating system in use.
755 /// Example value is `linux`.
757 /// Some possible values:
770 #[stable(feature = "env", since = "1.0.0")]
771 pub const OS: &'static str = os::OS;
773 /// Specifies the filename prefix used for shared libraries on this
774 /// platform. Example value is `lib`.
776 /// Some possible values:
779 /// - `""` (an empty string)
780 #[stable(feature = "env", since = "1.0.0")]
781 pub const DLL_PREFIX: &'static str = os::DLL_PREFIX;
783 /// Specifies the filename suffix used for shared libraries on this
784 /// platform. Example value is `.so`.
786 /// Some possible values:
791 #[stable(feature = "env", since = "1.0.0")]
792 pub const DLL_SUFFIX: &'static str = os::DLL_SUFFIX;
794 /// Specifies the file extension used for shared libraries on this
795 /// platform that goes after the dot. Example value is `so`.
797 /// Some possible values:
802 #[stable(feature = "env", since = "1.0.0")]
803 pub const DLL_EXTENSION: &'static str = os::DLL_EXTENSION;
805 /// Specifies the filename suffix used for executable binaries on this
806 /// platform. Example value is `.exe`.
808 /// Some possible values:
813 /// - `""` (an empty string)
814 #[stable(feature = "env", since = "1.0.0")]
815 pub const EXE_SUFFIX: &'static str = os::EXE_SUFFIX;
817 /// Specifies the file extension, if any, used for executable binaries
818 /// on this platform. Example value is `exe`.
820 /// Some possible values:
823 /// - `""` (an empty string)
824 #[stable(feature = "env", since = "1.0.0")]
825 pub const EXE_EXTENSION: &'static str = os::EXE_EXTENSION;
828 #[cfg(target_arch = "x86")]
830 pub const ARCH: &'static str = "x86";
833 #[cfg(target_arch = "x86_64")]
835 pub const ARCH: &'static str = "x86_64";
838 #[cfg(target_arch = "arm")]
840 pub const ARCH: &'static str = "arm";
843 #[cfg(target_arch = "aarch64")]
845 pub const ARCH: &'static str = "aarch64";
848 #[cfg(target_arch = "mips")]
850 pub const ARCH: &'static str = "mips";
853 #[cfg(target_arch = "mips64")]
855 pub const ARCH: &'static str = "mips64";
858 #[cfg(target_arch = "powerpc")]
860 pub const ARCH: &'static str = "powerpc";
863 #[cfg(target_arch = "powerpc64")]
865 pub const ARCH: &'static str = "powerpc64";
868 #[cfg(target_arch = "s390x")]
870 pub const ARCH: &'static str = "s390x";
873 #[cfg(target_arch = "sparc64")]
875 pub const ARCH: &'static str = "sparc64";
878 #[cfg(target_arch = "le32")]
880 pub const ARCH: &'static str = "le32";
883 #[cfg(target_arch = "asmjs")]
885 pub const ARCH: &'static str = "asmjs";
888 #[cfg(target_arch = "wasm32")]
890 pub const ARCH: &'static str = "wasm32";
898 use rand::{self, Rng};
899 use ffi::{OsString, OsStr};
900 use path::{Path, PathBuf};
902 fn make_rand_name() -> OsString {
903 let mut rng = rand::thread_rng();
904 let n = format!("TEST{}", rng.gen_ascii_chars().take(10)
905 .collect::<String>());
906 let n = OsString::from(n);
907 assert!(var_os(&n).is_none());
911 fn eq(a: Option<OsString>, b: Option<&str>) {
912 assert_eq!(a.as_ref().map(|s| &**s), b.map(OsStr::new).map(|s| &*s));
917 let n = make_rand_name();
918 set_var(&n, "VALUE");
919 eq(var_os(&n), Some("VALUE"));
923 fn test_remove_var() {
924 let n = make_rand_name();
925 set_var(&n, "VALUE");
927 eq(var_os(&n), None);
931 fn test_set_var_overwrite() {
932 let n = make_rand_name();
935 eq(var_os(&n), Some("2"));
937 eq(var_os(&n), Some(""));
941 #[cfg_attr(target_os = "emscripten", ignore)]
943 let mut s = "".to_string();
946 s.push_str("aaaaaaaaaa");
949 let n = make_rand_name();
951 eq(var_os(&n), Some(&s));
955 #[cfg_attr(target_os = "emscripten", ignore)]
956 fn test_self_exe_path() {
957 let path = current_exe();
958 assert!(path.is_ok());
959 let path = path.unwrap();
961 // Hard to test this function
962 assert!(path.is_absolute());
966 #[cfg_attr(target_os = "emscripten", ignore)]
967 fn test_env_set_get_huge() {
968 let n = make_rand_name();
969 let s = repeat("x").take(10000).collect::<String>();
971 eq(var_os(&n), Some(&s));
973 eq(var_os(&n), None);
977 fn test_env_set_var() {
978 let n = make_rand_name();
980 let mut e = vars_os();
981 set_var(&n, "VALUE");
982 assert!(!e.any(|(k, v)| {
983 &*k == &*n && &*v == "VALUE"
986 assert!(vars_os().any(|(k, v)| {
987 &*k == &*n && &*v == "VALUE"
993 assert!((!Path::new("test-path").is_absolute()));
995 current_dir().unwrap();
1000 fn split_paths_windows() {
1001 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1002 split_paths(unparsed).collect::<Vec<_>>() ==
1003 parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
1006 assert!(check_parse("", &mut [""]));
1007 assert!(check_parse(r#""""#, &mut [""]));
1008 assert!(check_parse(";;", &mut ["", "", ""]));
1009 assert!(check_parse(r"c:\", &mut [r"c:\"]));
1010 assert!(check_parse(r"c:\;", &mut [r"c:\", ""]));
1011 assert!(check_parse(r"c:\;c:\Program Files\",
1012 &mut [r"c:\", r"c:\Program Files\"]));
1013 assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
1014 assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
1015 &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
1020 fn split_paths_unix() {
1021 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1022 split_paths(unparsed).collect::<Vec<_>>() ==
1023 parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
1026 assert!(check_parse("", &mut [""]));
1027 assert!(check_parse("::", &mut ["", "", ""]));
1028 assert!(check_parse("/", &mut ["/"]));
1029 assert!(check_parse("/:", &mut ["/", ""]));
1030 assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
1035 fn join_paths_unix() {
1036 fn test_eq(input: &[&str], output: &str) -> bool {
1037 &*join_paths(input.iter().cloned()).unwrap() ==
1041 assert!(test_eq(&[], ""));
1042 assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"],
1043 "/bin:/usr/bin:/usr/local/bin"));
1044 assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""],
1045 ":/bin:::/usr/bin:"));
1046 assert!(join_paths(["/te:st"].iter().cloned()).is_err());
1051 fn join_paths_windows() {
1052 fn test_eq(input: &[&str], output: &str) -> bool {
1053 &*join_paths(input.iter().cloned()).unwrap() ==
1057 assert!(test_eq(&[], ""));
1058 assert!(test_eq(&[r"c:\windows", r"c:\"],
1059 r"c:\windows;c:\"));
1060 assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""],
1061 r";c:\windows;;;c:\;"));
1062 assert!(test_eq(&[r"c:\te;st", r"c:\"],
1063 r#""c:\te;st";c:\"#));
1064 assert!(join_paths([r#"c:\te"st"#].iter().cloned()).is_err());