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 //! There are several functions and structs in this module that have a
18 //! counterpart ending in `os`. Those ending in `os` will return an [`OsString`]
19 //! and those without will be returning a [`String`].
21 //! [`OsString`]: ../../std/ffi/struct.OsString.html
22 //! [`String`]: ../string/struct.String.html
24 #![stable(feature = "env", since = "1.0.0")]
27 use ffi::{OsStr, OsString};
30 use path::{Path, PathBuf};
32 use sys::os as os_imp;
34 /// Returns the current working directory as a [`PathBuf`].
38 /// Returns an [`Err`] if the current working directory value is invalid.
41 /// * Current directory does not exist.
42 /// * There are insufficient permissions to access the current directory.
44 /// [`PathBuf`]: ../../std/path/struct.PathBuf.html
45 /// [`Err`]: ../../std/result/enum.Result.html#method.err
52 /// fn main() -> std::io::Result<()> {
53 /// let path = env::current_dir()?;
54 /// println!("The current directory is {}", path.display());
58 #[stable(feature = "env", since = "1.0.0")]
59 pub fn current_dir() -> io::Result<PathBuf> {
63 /// Changes the current working directory to the specified path.
65 /// Returns an [`Err`] if the operation fails.
67 /// [`Err`]: ../../std/result/enum.Result.html#method.err
73 /// use std::path::Path;
75 /// let root = Path::new("/");
76 /// assert!(env::set_current_dir(&root).is_ok());
77 /// println!("Successfully changed working directory to {}!", root.display());
79 #[stable(feature = "env", since = "1.0.0")]
80 pub fn set_current_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
81 os_imp::chdir(path.as_ref())
84 /// An iterator over a snapshot of the environment variables of this process.
86 /// This structure is created by the [`std::env::vars`] function. See its
87 /// documentation for more.
89 /// [`std::env::vars`]: fn.vars.html
90 #[stable(feature = "env", since = "1.0.0")]
91 pub struct Vars { inner: VarsOs }
93 /// An iterator over a snapshot of the environment variables of this process.
95 /// This structure is created by the [`std::env::vars_os`] function. See
96 /// its documentation for more.
98 /// [`std::env::vars_os`]: fn.vars_os.html
99 #[stable(feature = "env", since = "1.0.0")]
100 pub struct VarsOs { inner: os_imp::Env }
102 /// Returns an iterator of (variable, value) pairs of strings, for all the
103 /// environment variables of the current process.
105 /// The returned iterator contains a snapshot of the process's environment
106 /// variables at the time of this invocation. Modifications to environment
107 /// variables afterwards will not be reflected in the returned iterator.
111 /// While iterating, the returned iterator will panic if any key or value in the
112 /// environment is not valid unicode. If this is not desired, consider using the
113 /// [`env::vars_os`] function.
115 /// [`env::vars_os`]: fn.vars_os.html
122 /// // We will iterate through the references to the element returned by
124 /// for (key, value) in env::vars() {
125 /// println!("{}: {}", key, value);
128 #[stable(feature = "env", since = "1.0.0")]
129 pub fn vars() -> Vars {
130 Vars { inner: vars_os() }
133 /// Returns an iterator of (variable, value) pairs of OS strings, for all the
134 /// environment variables of the current process.
136 /// The returned iterator contains a snapshot of the process's environment
137 /// variables at the time of this invocation. Modifications to environment
138 /// variables afterwards will not be reflected in the returned iterator.
145 /// // We will iterate through the references to the element returned by
146 /// // env::vars_os();
147 /// for (key, value) in env::vars_os() {
148 /// println!("{:?}: {:?}", key, value);
151 #[stable(feature = "env", since = "1.0.0")]
152 pub fn vars_os() -> VarsOs {
153 VarsOs { inner: os_imp::env() }
156 #[stable(feature = "env", since = "1.0.0")]
157 impl Iterator for Vars {
158 type Item = (String, String);
159 fn next(&mut self) -> Option<(String, String)> {
160 self.inner.next().map(|(a, b)| {
161 (a.into_string().unwrap(), b.into_string().unwrap())
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 Vars {
169 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
174 #[stable(feature = "env", since = "1.0.0")]
175 impl Iterator for VarsOs {
176 type Item = (OsString, OsString);
177 fn next(&mut self) -> Option<(OsString, OsString)> { self.inner.next() }
178 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
181 #[stable(feature = "std_debug", since = "1.16.0")]
182 impl fmt::Debug for VarsOs {
183 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
184 f.pad("VarsOs { .. }")
188 /// Fetches the environment variable `key` from the current process.
192 /// * Environment variable is not present
193 /// * Environment variable is not valid unicode
200 /// let key = "HOME";
201 /// match env::var(key) {
202 /// Ok(val) => println!("{}: {:?}", key, val),
203 /// Err(e) => println!("couldn't interpret {}: {}", key, e),
206 #[stable(feature = "env", since = "1.0.0")]
207 pub fn var<K: AsRef<OsStr>>(key: K) -> Result<String, VarError> {
211 fn _var(key: &OsStr) -> Result<String, VarError> {
213 Some(s) => s.into_string().map_err(VarError::NotUnicode),
214 None => Err(VarError::NotPresent),
218 /// Fetches the environment variable `key` from the current process, returning
219 /// [`None`] if the variable isn't set.
221 /// [`None`]: ../option/enum.Option.html#variant.None
228 /// let key = "HOME";
229 /// match env::var_os(key) {
230 /// Some(val) => println!("{}: {:?}", key, val),
231 /// None => println!("{} is not defined in the environment.", key)
234 #[stable(feature = "env", since = "1.0.0")]
235 pub fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> {
236 _var_os(key.as_ref())
239 fn _var_os(key: &OsStr) -> Option<OsString> {
240 os_imp::getenv(key).unwrap_or_else(|e| {
241 panic!("failed to get environment variable `{:?}`: {}", key, e)
245 /// The error type for operations interacting with environment variables.
246 /// Possibly returned from the [`env::var`] function.
248 /// [`env::var`]: fn.var.html
249 #[derive(Debug, PartialEq, Eq, Clone)]
250 #[stable(feature = "env", since = "1.0.0")]
252 /// The specified environment variable was not present in the current
253 /// process's environment.
254 #[stable(feature = "env", since = "1.0.0")]
257 /// The specified environment variable was found, but it did not contain
258 /// valid unicode data. The found data is returned as a payload of this
260 #[stable(feature = "env", since = "1.0.0")]
261 NotUnicode(#[stable(feature = "env", since = "1.0.0")] OsString),
264 #[stable(feature = "env", since = "1.0.0")]
265 impl fmt::Display for VarError {
266 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
268 VarError::NotPresent => write!(f, "environment variable not found"),
269 VarError::NotUnicode(ref s) => {
270 write!(f, "environment variable was not valid unicode: {:?}", s)
276 #[stable(feature = "env", since = "1.0.0")]
277 impl Error for VarError {
278 fn description(&self) -> &str {
280 VarError::NotPresent => "environment variable not found",
281 VarError::NotUnicode(..) => "environment variable was not valid unicode",
286 /// Sets the environment variable `k` to the value `v` for the currently running
289 /// Note that while concurrent access to environment variables is safe in Rust,
290 /// some platforms only expose inherently unsafe non-threadsafe APIs for
291 /// inspecting the environment. As a result extra care needs to be taken when
292 /// auditing calls to unsafe external FFI functions to ensure that any external
293 /// environment accesses are properly synchronized with accesses in Rust.
295 /// Discussion of this unsafety on Unix may be found in:
297 /// - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188)
298 /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
302 /// This function may panic if `key` is empty, contains an ASCII equals sign
303 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
312 /// env::set_var(key, "VALUE");
313 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
315 #[stable(feature = "env", since = "1.0.0")]
316 pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(k: K, v: V) {
317 _set_var(k.as_ref(), v.as_ref())
320 fn _set_var(k: &OsStr, v: &OsStr) {
321 os_imp::setenv(k, v).unwrap_or_else(|e| {
322 panic!("failed to set environment variable `{:?}` to `{:?}`: {}",
327 /// Removes an environment variable from the environment of the currently running process.
329 /// Note that while concurrent access to environment variables is safe in Rust,
330 /// some platforms only expose inherently unsafe non-threadsafe APIs for
331 /// inspecting the environment. As a result extra care needs to be taken when
332 /// auditing calls to unsafe external FFI functions to ensure that any external
333 /// environment accesses are properly synchronized with accesses in Rust.
335 /// Discussion of this unsafety on Unix may be found in:
337 /// - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188)
338 /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
342 /// This function may panic if `key` is empty, contains an ASCII equals sign
343 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
352 /// env::set_var(key, "VALUE");
353 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
355 /// env::remove_var(key);
356 /// assert!(env::var(key).is_err());
358 #[stable(feature = "env", since = "1.0.0")]
359 pub fn remove_var<K: AsRef<OsStr>>(k: K) {
360 _remove_var(k.as_ref())
363 fn _remove_var(k: &OsStr) {
364 os_imp::unsetenv(k).unwrap_or_else(|e| {
365 panic!("failed to remove environment variable `{:?}`: {}", k, e)
369 /// An iterator that splits an environment variable into paths according to
370 /// platform-specific conventions.
372 /// This structure is created by the [`std::env::split_paths`] function. See its
373 /// documentation for more.
375 /// [`std::env::split_paths`]: fn.split_paths.html
376 #[stable(feature = "env", since = "1.0.0")]
377 pub struct SplitPaths<'a> { inner: os_imp::SplitPaths<'a> }
379 /// Parses input according to platform conventions for the `PATH`
380 /// environment variable.
382 /// Returns an iterator over the paths contained in `unparsed`.
389 /// let key = "PATH";
390 /// match env::var_os(key) {
392 /// for path in env::split_paths(&paths) {
393 /// println!("'{}'", path.display());
396 /// None => println!("{} is not defined in the environment.", key)
399 #[stable(feature = "env", since = "1.0.0")]
400 pub fn split_paths<T: AsRef<OsStr> + ?Sized>(unparsed: &T) -> SplitPaths {
401 SplitPaths { inner: os_imp::split_paths(unparsed.as_ref()) }
404 #[stable(feature = "env", since = "1.0.0")]
405 impl<'a> Iterator for SplitPaths<'a> {
407 fn next(&mut self) -> Option<PathBuf> { self.inner.next() }
408 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
411 #[stable(feature = "std_debug", since = "1.16.0")]
412 impl<'a> fmt::Debug for SplitPaths<'a> {
413 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
414 f.pad("SplitPaths { .. }")
418 /// The error type for operations on the `PATH` variable. Possibly returned from
419 /// the [`env::join_paths`] function.
421 /// [`env::join_paths`]: fn.join_paths.html
423 #[stable(feature = "env", since = "1.0.0")]
424 pub struct JoinPathsError {
425 inner: os_imp::JoinPathsError
428 /// Joins a collection of [`Path`]s appropriately for the `PATH`
429 /// environment variable.
433 /// Returns an [`Err`][err] (containing an error message) if one of the input
434 /// [`Path`]s contains an invalid character for constructing the `PATH`
435 /// variable (a double quote on Windows or a colon on Unix).
437 /// [`Path`]: ../../std/path/struct.Path.html
438 /// [`OsString`]: ../../std/ffi/struct.OsString.html
439 /// [err]: ../../std/result/enum.Result.html#variant.Err
443 /// Joining paths on a Unix-like platform:
447 /// use std::ffi::OsString;
448 /// use std::path::Path;
450 /// fn main() -> Result<(), env::JoinPathsError> {
451 /// # if cfg!(unix) {
452 /// let paths = [Path::new("/bin"), Path::new("/usr/bin")];
453 /// let path_os_string = env::join_paths(paths.iter())?;
454 /// assert_eq!(path_os_string, OsString::from("/bin:/usr/bin"));
460 /// Joining a path containing a colon on a Unix-like platform results in an error:
463 /// # if cfg!(unix) {
465 /// use std::path::Path;
467 /// let paths = [Path::new("/bin"), Path::new("/usr/bi:n")];
468 /// assert!(env::join_paths(paths.iter()).is_err());
472 /// Using `env::join_paths` with `env::spit_paths` to append an item to the `PATH` environment
477 /// use std::path::PathBuf;
479 /// fn main() -> Result<(), env::JoinPathsError> {
480 /// if let Some(path) = env::var_os("PATH") {
481 /// let mut paths = env::split_paths(&path).collect::<Vec<_>>();
482 /// paths.push(PathBuf::from("/home/xyz/bin"));
483 /// let new_path = env::join_paths(paths)?;
484 /// env::set_var("PATH", &new_path);
490 #[stable(feature = "env", since = "1.0.0")]
491 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
492 where I: IntoIterator<Item=T>, T: AsRef<OsStr>
494 os_imp::join_paths(paths.into_iter()).map_err(|e| {
495 JoinPathsError { inner: e }
499 #[stable(feature = "env", since = "1.0.0")]
500 impl fmt::Display for JoinPathsError {
501 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
506 #[stable(feature = "env", since = "1.0.0")]
507 impl Error for JoinPathsError {
508 fn description(&self) -> &str { self.inner.description() }
511 /// Returns the path of the current user's home directory if known.
515 /// - Returns the value of the 'HOME' environment variable if it is set
516 /// (including to an empty string).
517 /// - Otherwise, it tries to determine the home directory by invoking the `getpwuid_r` function
518 /// using the UID of the current user. An empty home directory field returned from the
519 /// `getpwuid_r` function is considered to be a valid value.
520 /// - Returns `None` if the current user has no entry in the /etc/passwd file.
524 /// - Returns the value of the 'HOME' environment variable if it is set
525 /// (including to an empty string).
526 /// - Otherwise, returns the value of the 'USERPROFILE' environment variable if it is set
527 /// (including to an empty string).
528 /// - If both do not exist, [`GetUserProfileDirectory`][msdn] is used to return the path.
530 /// [msdn]: https://msdn.microsoft.com/en-us/library/windows/desktop/bb762280(v=vs.85).aspx
537 /// match env::home_dir() {
538 /// Some(path) => println!("Your home directory, probably: {}", path.display()),
539 /// None => println!("Impossible to get your home dir!"),
542 #[rustc_deprecated(since = "1.29.0",
543 reason = "This function's behavior is unexpected and probably not what you want. \
544 Consider using the home_dir function from https://crates.io/crates/dirs instead.")]
545 #[stable(feature = "env", since = "1.0.0")]
546 pub fn home_dir() -> Option<PathBuf> {
550 /// Returns the path of a temporary directory.
554 /// Returns the value of the `TMPDIR` environment variable if it is
555 /// set, otherwise for non-Android it returns `/tmp`. If Android, since there
556 /// is no global temporary folder (it is usually allocated per-app), it returns
557 /// `/data/local/tmp`.
561 /// Returns the value of, in order, the `TMP`, `TEMP`,
562 /// `USERPROFILE` environment variable if any are set and not the empty
563 /// string. Otherwise, `temp_dir` returns the path of the Windows directory.
564 /// This behavior is identical to that of [`GetTempPath`][msdn], which this
565 /// function uses internally.
567 /// [msdn]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa364992(v=vs.85).aspx
571 /// use std::fs::File;
573 /// fn main() -> std::io::Result<()> {
574 /// let mut dir = env::temp_dir();
575 /// dir.push("foo.txt");
577 /// let f = File::create(dir)?;
581 #[stable(feature = "env", since = "1.0.0")]
582 pub fn temp_dir() -> PathBuf {
586 /// Returns the full filesystem path of the current running executable.
588 /// # Platform-specific behavior
590 /// If the executable was invoked through a symbolic link, some platforms will
591 /// return the path of the symbolic link and other platforms will return the
592 /// path of the symbolic link’s target.
596 /// Acquiring the path of the current executable is a platform-specific operation
597 /// that can fail for a good number of reasons. Some errors can include, but not
598 /// be limited to, filesystem operations failing or general syscall failures.
602 /// The output of this function should not be used in anything that might have
603 /// security implications. For example:
607 /// println!("{:?}", std::env::current_exe());
611 /// On Linux systems, if this is compiled as `foo`:
616 /// Ok("/home/alex/foo")
619 /// And you make a hard link of the program:
625 /// When you run it, you won’t get the path of the original executable, you’ll
626 /// get the path of the hard link:
630 /// Ok("/home/alex/bar")
633 /// This sort of behavior has been known to [lead to privilege escalation] when
634 /// used incorrectly.
636 /// [lead to privilege escalation]: https://securityvulns.com/Wdocument183.html
643 /// match env::current_exe() {
644 /// Ok(exe_path) => println!("Path of this executable is: {}",
645 /// exe_path.display()),
646 /// Err(e) => println!("failed to get current exe path: {}", e),
649 #[stable(feature = "env", since = "1.0.0")]
650 pub fn current_exe() -> io::Result<PathBuf> {
651 os_imp::current_exe()
654 /// An iterator over the arguments of a process, yielding a [`String`] value for
657 /// This struct is created by the [`std::env::args`] function. See its
658 /// documentation for more.
660 /// The first element is traditionally the path of the executable, but it can be
661 /// set to arbitrary text, and may not even exist. This means this property
662 /// should not be relied upon for security purposes.
664 /// [`String`]: ../string/struct.String.html
665 /// [`std::env::args`]: ./fn.args.html
666 #[stable(feature = "env", since = "1.0.0")]
667 pub struct Args { inner: ArgsOs }
669 /// An iterator over the arguments of a process, yielding an [`OsString`] value
670 /// for each argument.
672 /// This struct is created by the [`std::env::args_os`] function. See its
673 /// documentation for more.
675 /// The first element is traditionally the path of the executable, but it can be
676 /// set to arbitrary text, and may not even exist. This means this property
677 /// should not be relied upon for security purposes.
679 /// [`OsString`]: ../ffi/struct.OsString.html
680 /// [`std::env::args_os`]: ./fn.args_os.html
681 #[stable(feature = "env", since = "1.0.0")]
682 pub struct ArgsOs { inner: sys::args::Args }
684 /// Returns the arguments which this program was started with (normally passed
685 /// via the command line).
687 /// The first element is traditionally the path of the executable, but it can be
688 /// set to arbitrary text, and may not even exist. This means this property should
689 /// not be relied upon for security purposes.
691 /// On Unix systems shell usually expands unquoted arguments with glob patterns
692 /// (such as `*` and `?`). On Windows this is not done, and such arguments are
697 /// The returned iterator will panic during iteration if any argument to the
698 /// process is not valid unicode. If this is not desired,
699 /// use the [`args_os`] function instead.
706 /// // Prints each argument on a separate line
707 /// for argument in env::args() {
708 /// println!("{}", argument);
712 /// [`args_os`]: ./fn.args_os.html
713 #[stable(feature = "env", since = "1.0.0")]
714 pub fn args() -> Args {
715 Args { inner: args_os() }
718 /// Returns the arguments which this program was started with (normally passed
719 /// via the command line).
721 /// The first element is traditionally the path of the executable, but it can be
722 /// set to arbitrary text, and it may not even exist, so this property should
723 /// not be relied upon for security purposes.
730 /// // Prints each argument on a separate line
731 /// for argument in env::args_os() {
732 /// println!("{:?}", argument);
735 #[stable(feature = "env", since = "1.0.0")]
736 pub fn args_os() -> ArgsOs {
737 ArgsOs { inner: sys::args::args() }
740 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
741 impl !Send for Args {}
743 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
744 impl !Sync for Args {}
746 #[stable(feature = "env", since = "1.0.0")]
747 impl Iterator for Args {
749 fn next(&mut self) -> Option<String> {
750 self.inner.next().map(|s| s.into_string().unwrap())
752 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
755 #[stable(feature = "env", since = "1.0.0")]
756 impl ExactSizeIterator for Args {
757 fn len(&self) -> usize { self.inner.len() }
758 fn is_empty(&self) -> bool { self.inner.is_empty() }
761 #[stable(feature = "env_iterators", since = "1.12.0")]
762 impl DoubleEndedIterator for Args {
763 fn next_back(&mut self) -> Option<String> {
764 self.inner.next_back().map(|s| s.into_string().unwrap())
768 #[stable(feature = "std_debug", since = "1.16.0")]
769 impl fmt::Debug for Args {
770 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
771 f.debug_struct("Args")
772 .field("inner", &self.inner.inner.inner_debug())
777 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
778 impl !Send for ArgsOs {}
780 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
781 impl !Sync for ArgsOs {}
783 #[stable(feature = "env", since = "1.0.0")]
784 impl Iterator for ArgsOs {
785 type Item = OsString;
786 fn next(&mut self) -> Option<OsString> { self.inner.next() }
787 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
790 #[stable(feature = "env", since = "1.0.0")]
791 impl ExactSizeIterator for ArgsOs {
792 fn len(&self) -> usize { self.inner.len() }
793 fn is_empty(&self) -> bool { self.inner.is_empty() }
796 #[stable(feature = "env_iterators", since = "1.12.0")]
797 impl DoubleEndedIterator for ArgsOs {
798 fn next_back(&mut self) -> Option<OsString> { self.inner.next_back() }
801 #[stable(feature = "std_debug", since = "1.16.0")]
802 impl fmt::Debug for ArgsOs {
803 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
804 f.debug_struct("ArgsOs")
805 .field("inner", &self.inner.inner_debug())
810 /// Constants associated with the current target
811 #[stable(feature = "env", since = "1.0.0")]
815 /// A string describing the architecture of the CPU that is currently
818 /// Some possible values:
830 #[stable(feature = "env", since = "1.0.0")]
831 pub const ARCH: &'static str = super::arch::ARCH;
833 /// The family of the operating system. Example value is `unix`.
835 /// Some possible values:
839 #[stable(feature = "env", since = "1.0.0")]
840 pub const FAMILY: &'static str = os::FAMILY;
842 /// A string describing the specific operating system in use.
843 /// Example value is `linux`.
845 /// Some possible values:
858 #[stable(feature = "env", since = "1.0.0")]
859 pub const OS: &'static str = os::OS;
861 /// Specifies the filename prefix used for shared libraries on this
862 /// platform. Example value is `lib`.
864 /// Some possible values:
867 /// - `""` (an empty string)
868 #[stable(feature = "env", since = "1.0.0")]
869 pub const DLL_PREFIX: &'static str = os::DLL_PREFIX;
871 /// Specifies the filename suffix used for shared libraries on this
872 /// platform. Example value is `.so`.
874 /// Some possible values:
879 #[stable(feature = "env", since = "1.0.0")]
880 pub const DLL_SUFFIX: &'static str = os::DLL_SUFFIX;
882 /// Specifies the file extension used for shared libraries on this
883 /// platform that goes after the dot. Example value is `so`.
885 /// Some possible values:
890 #[stable(feature = "env", since = "1.0.0")]
891 pub const DLL_EXTENSION: &'static str = os::DLL_EXTENSION;
893 /// Specifies the filename suffix used for executable binaries on this
894 /// platform. Example value is `.exe`.
896 /// Some possible values:
901 /// - `""` (an empty string)
902 #[stable(feature = "env", since = "1.0.0")]
903 pub const EXE_SUFFIX: &'static str = os::EXE_SUFFIX;
905 /// Specifies the file extension, if any, used for executable binaries
906 /// on this platform. Example value is `exe`.
908 /// Some possible values:
911 /// - `""` (an empty string)
912 #[stable(feature = "env", since = "1.0.0")]
913 pub const EXE_EXTENSION: &'static str = os::EXE_EXTENSION;
916 #[cfg(target_arch = "x86")]
918 pub const ARCH: &'static str = "x86";
921 #[cfg(target_arch = "x86_64")]
923 pub const ARCH: &'static str = "x86_64";
926 #[cfg(target_arch = "arm")]
928 pub const ARCH: &'static str = "arm";
931 #[cfg(target_arch = "aarch64")]
933 pub const ARCH: &'static str = "aarch64";
936 #[cfg(target_arch = "mips")]
938 pub const ARCH: &'static str = "mips";
941 #[cfg(target_arch = "mips64")]
943 pub const ARCH: &'static str = "mips64";
946 #[cfg(target_arch = "powerpc")]
948 pub const ARCH: &'static str = "powerpc";
951 #[cfg(target_arch = "powerpc64")]
953 pub const ARCH: &'static str = "powerpc64";
956 #[cfg(target_arch = "s390x")]
958 pub const ARCH: &'static str = "s390x";
961 #[cfg(target_arch = "sparc64")]
963 pub const ARCH: &'static str = "sparc64";
966 #[cfg(target_arch = "le32")]
968 pub const ARCH: &'static str = "le32";
971 #[cfg(target_arch = "asmjs")]
973 pub const ARCH: &'static str = "asmjs";
976 #[cfg(target_arch = "wasm32")]
978 pub const ARCH: &'static str = "wasm32";
988 #[cfg_attr(target_os = "emscripten", ignore)]
989 fn test_self_exe_path() {
990 let path = current_exe();
991 assert!(path.is_ok());
992 let path = path.unwrap();
994 // Hard to test this function
995 assert!(path.is_absolute());
1000 assert!((!Path::new("test-path").is_absolute()));
1002 current_dir().unwrap();
1007 fn split_paths_windows() {
1010 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1011 split_paths(unparsed).collect::<Vec<_>>() ==
1012 parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
1015 assert!(check_parse("", &mut [""]));
1016 assert!(check_parse(r#""""#, &mut [""]));
1017 assert!(check_parse(";;", &mut ["", "", ""]));
1018 assert!(check_parse(r"c:\", &mut [r"c:\"]));
1019 assert!(check_parse(r"c:\;", &mut [r"c:\", ""]));
1020 assert!(check_parse(r"c:\;c:\Program Files\",
1021 &mut [r"c:\", r"c:\Program Files\"]));
1022 assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
1023 assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
1024 &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
1029 fn split_paths_unix() {
1032 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1033 split_paths(unparsed).collect::<Vec<_>>() ==
1034 parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
1037 assert!(check_parse("", &mut [""]));
1038 assert!(check_parse("::", &mut ["", "", ""]));
1039 assert!(check_parse("/", &mut ["/"]));
1040 assert!(check_parse("/:", &mut ["/", ""]));
1041 assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
1046 fn join_paths_unix() {
1049 fn test_eq(input: &[&str], output: &str) -> bool {
1050 &*join_paths(input.iter().cloned()).unwrap() ==
1054 assert!(test_eq(&[], ""));
1055 assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"],
1056 "/bin:/usr/bin:/usr/local/bin"));
1057 assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""],
1058 ":/bin:::/usr/bin:"));
1059 assert!(join_paths(["/te:st"].iter().cloned()).is_err());
1064 fn join_paths_windows() {
1067 fn test_eq(input: &[&str], output: &str) -> bool {
1068 &*join_paths(input.iter().cloned()).unwrap() ==
1072 assert!(test_eq(&[], ""));
1073 assert!(test_eq(&[r"c:\windows", r"c:\"],
1074 r"c:\windows;c:\"));
1075 assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""],
1076 r";c:\windows;;;c:\;"));
1077 assert!(test_eq(&[r"c:\te;st", r"c:\"],
1078 r#""c:\te;st";c:\"#));
1079 assert!(join_paths([r#"c:\te"st"#].iter().cloned()).is_err());
1085 format!("Args {{ inner: {:?} }}", args().collect::<Vec<_>>()),
1086 format!("{:?}", args()));
1088 format!("ArgsOs {{ inner: {:?} }}", args_os().collect::<Vec<_>>()),
1089 format!("{:?}", args_os()));