1 //! Inspection and manipulation of the process's environment.
3 //! This module contains functions to inspect various aspects such as
4 //! environment variables, process arguments, the current directory, and various
5 //! other important directories.
7 //! There are several functions and structs in this module that have a
8 //! counterpart ending in `os`. Those ending in `os` will return an [`OsString`]
9 //! and those without will be returning a [`String`].
11 //! [`OsString`]: ../../std/ffi/struct.OsString.html
12 //! [`String`]: ../string/struct.String.html
14 #![stable(feature = "env", since = "1.0.0")]
16 use crate::error::Error;
17 use crate::ffi::{OsStr, OsString};
20 use crate::path::{Path, PathBuf};
22 use crate::sys::os as os_imp;
24 /// Returns the current working directory as a [`PathBuf`].
28 /// Returns an [`Err`] if the current working directory value is invalid.
31 /// * Current directory does not exist.
32 /// * There are insufficient permissions to access the current directory.
34 /// [`PathBuf`]: ../../std/path/struct.PathBuf.html
35 /// [`Err`]: ../../std/result/enum.Result.html#method.err
42 /// fn main() -> std::io::Result<()> {
43 /// let path = env::current_dir()?;
44 /// println!("The current directory is {}", path.display());
48 #[stable(feature = "env", since = "1.0.0")]
49 pub fn current_dir() -> io::Result<PathBuf> {
53 /// Changes the current working directory to the specified path.
55 /// Returns an [`Err`] if the operation fails.
57 /// [`Err`]: ../../std/result/enum.Result.html#method.err
63 /// use std::path::Path;
65 /// let root = Path::new("/");
66 /// assert!(env::set_current_dir(&root).is_ok());
67 /// println!("Successfully changed working directory to {}!", root.display());
69 #[stable(feature = "env", since = "1.0.0")]
70 pub fn set_current_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
71 os_imp::chdir(path.as_ref())
74 /// An iterator over a snapshot of the environment variables of this process.
76 /// This structure is created by the [`std::env::vars`] function. See its
77 /// documentation for more.
79 /// [`std::env::vars`]: fn.vars.html
80 #[stable(feature = "env", since = "1.0.0")]
81 pub struct Vars { inner: VarsOs }
83 /// An iterator over a snapshot of the environment variables of this process.
85 /// This structure is created by the [`std::env::vars_os`] function. See
86 /// its documentation for more.
88 /// [`std::env::vars_os`]: fn.vars_os.html
89 #[stable(feature = "env", since = "1.0.0")]
90 pub struct VarsOs { inner: os_imp::Env }
92 /// Returns an iterator of (variable, value) pairs of strings, for all the
93 /// environment variables of the current process.
95 /// The returned iterator contains a snapshot of the process's environment
96 /// variables at the time of this invocation. Modifications to environment
97 /// variables afterwards will not be reflected in the returned iterator.
101 /// While iterating, the returned iterator will panic if any key or value in the
102 /// environment is not valid unicode. If this is not desired, consider using the
103 /// [`env::vars_os`] function.
105 /// [`env::vars_os`]: fn.vars_os.html
112 /// // We will iterate through the references to the element returned by
114 /// for (key, value) in env::vars() {
115 /// println!("{}: {}", key, value);
118 #[stable(feature = "env", since = "1.0.0")]
119 pub fn vars() -> Vars {
120 Vars { inner: vars_os() }
123 /// Returns an iterator of (variable, value) pairs of OS strings, for all the
124 /// environment variables of the current process.
126 /// The returned iterator contains a snapshot of the process's environment
127 /// variables at the time of this invocation. Modifications to environment
128 /// variables afterwards will not be reflected in the returned iterator.
135 /// // We will iterate through the references to the element returned by
136 /// // env::vars_os();
137 /// for (key, value) in env::vars_os() {
138 /// println!("{:?}: {:?}", key, value);
141 #[stable(feature = "env", since = "1.0.0")]
142 pub fn vars_os() -> VarsOs {
143 VarsOs { inner: os_imp::env() }
146 #[stable(feature = "env", since = "1.0.0")]
147 impl Iterator for Vars {
148 type Item = (String, String);
149 fn next(&mut self) -> Option<(String, String)> {
150 self.inner.next().map(|(a, b)| {
151 (a.into_string().unwrap(), b.into_string().unwrap())
154 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
157 #[stable(feature = "std_debug", since = "1.16.0")]
158 impl fmt::Debug for Vars {
159 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
164 #[stable(feature = "env", since = "1.0.0")]
165 impl Iterator for VarsOs {
166 type Item = (OsString, OsString);
167 fn next(&mut self) -> Option<(OsString, OsString)> { self.inner.next() }
168 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
171 #[stable(feature = "std_debug", since = "1.16.0")]
172 impl fmt::Debug for VarsOs {
173 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
174 f.pad("VarsOs { .. }")
178 /// Fetches the environment variable `key` from the current process.
182 /// * Environment variable is not present
183 /// * Environment variable is not valid unicode
190 /// let key = "HOME";
191 /// match env::var(key) {
192 /// Ok(val) => println!("{}: {:?}", key, val),
193 /// Err(e) => println!("couldn't interpret {}: {}", key, e),
196 #[stable(feature = "env", since = "1.0.0")]
197 pub fn var<K: AsRef<OsStr>>(key: K) -> Result<String, VarError> {
201 fn _var(key: &OsStr) -> Result<String, VarError> {
203 Some(s) => s.into_string().map_err(VarError::NotUnicode),
204 None => Err(VarError::NotPresent),
208 /// Fetches the environment variable `key` from the current process, returning
209 /// [`None`] if the variable isn't set.
211 /// [`None`]: ../option/enum.Option.html#variant.None
218 /// let key = "HOME";
219 /// match env::var_os(key) {
220 /// Some(val) => println!("{}: {:?}", key, val),
221 /// None => println!("{} is not defined in the environment.", key)
224 #[stable(feature = "env", since = "1.0.0")]
225 pub fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> {
226 _var_os(key.as_ref())
229 fn _var_os(key: &OsStr) -> Option<OsString> {
230 os_imp::getenv(key).unwrap_or_else(|e| {
231 panic!("failed to get environment variable `{:?}`: {}", key, e)
235 /// The error type for operations interacting with environment variables.
236 /// Possibly returned from the [`env::var`] function.
238 /// [`env::var`]: fn.var.html
239 #[derive(Debug, PartialEq, Eq, Clone)]
240 #[stable(feature = "env", since = "1.0.0")]
242 /// The specified environment variable was not present in the current
243 /// process's environment.
244 #[stable(feature = "env", since = "1.0.0")]
247 /// The specified environment variable was found, but it did not contain
248 /// valid unicode data. The found data is returned as a payload of this
250 #[stable(feature = "env", since = "1.0.0")]
251 NotUnicode(#[stable(feature = "env", since = "1.0.0")] OsString),
254 #[stable(feature = "env", since = "1.0.0")]
255 impl fmt::Display for VarError {
256 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
258 VarError::NotPresent => write!(f, "environment variable not found"),
259 VarError::NotUnicode(ref s) => {
260 write!(f, "environment variable was not valid unicode: {:?}", s)
266 #[stable(feature = "env", since = "1.0.0")]
267 impl Error for VarError {
268 fn description(&self) -> &str {
270 VarError::NotPresent => "environment variable not found",
271 VarError::NotUnicode(..) => "environment variable was not valid unicode",
276 /// Sets the environment variable `k` to the value `v` for the currently running
279 /// Note that while concurrent access to environment variables is safe in Rust,
280 /// some platforms only expose inherently unsafe non-threadsafe APIs for
281 /// inspecting the environment. As a result extra care needs to be taken when
282 /// auditing calls to unsafe external FFI functions to ensure that any external
283 /// environment accesses are properly synchronized with accesses in Rust.
285 /// Discussion of this unsafety on Unix may be found in:
287 /// - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188)
288 /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
292 /// This function may panic if `key` is empty, contains an ASCII equals sign
293 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
302 /// env::set_var(key, "VALUE");
303 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
305 #[stable(feature = "env", since = "1.0.0")]
306 pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(k: K, v: V) {
307 _set_var(k.as_ref(), v.as_ref())
310 fn _set_var(k: &OsStr, v: &OsStr) {
311 os_imp::setenv(k, v).unwrap_or_else(|e| {
312 panic!("failed to set environment variable `{:?}` to `{:?}`: {}",
317 /// Removes an environment variable from the environment of the currently running process.
319 /// Note that while concurrent access to environment variables is safe in Rust,
320 /// some platforms only expose inherently unsafe non-threadsafe APIs for
321 /// inspecting the environment. As a result extra care needs to be taken when
322 /// auditing calls to unsafe external FFI functions to ensure that any external
323 /// environment accesses are properly synchronized with accesses in Rust.
325 /// Discussion of this unsafety on Unix may be found in:
327 /// - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188)
328 /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
332 /// This function may panic if `key` is empty, contains an ASCII equals sign
333 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
342 /// env::set_var(key, "VALUE");
343 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
345 /// env::remove_var(key);
346 /// assert!(env::var(key).is_err());
348 #[stable(feature = "env", since = "1.0.0")]
349 pub fn remove_var<K: AsRef<OsStr>>(k: K) {
350 _remove_var(k.as_ref())
353 fn _remove_var(k: &OsStr) {
354 os_imp::unsetenv(k).unwrap_or_else(|e| {
355 panic!("failed to remove environment variable `{:?}`: {}", k, e)
359 /// An iterator that splits an environment variable into paths according to
360 /// platform-specific conventions.
362 /// This structure is created by the [`std::env::split_paths`] function. See its
363 /// documentation for more.
365 /// [`std::env::split_paths`]: fn.split_paths.html
366 #[stable(feature = "env", since = "1.0.0")]
367 pub struct SplitPaths<'a> { inner: os_imp::SplitPaths<'a> }
369 /// Parses input according to platform conventions for the `PATH`
370 /// environment variable.
372 /// Returns an iterator over the paths contained in `unparsed`.
379 /// let key = "PATH";
380 /// match env::var_os(key) {
382 /// for path in env::split_paths(&paths) {
383 /// println!("'{}'", path.display());
386 /// None => println!("{} is not defined in the environment.", key)
389 #[stable(feature = "env", since = "1.0.0")]
390 pub fn split_paths<T: AsRef<OsStr> + ?Sized>(unparsed: &T) -> SplitPaths {
391 SplitPaths { inner: os_imp::split_paths(unparsed.as_ref()) }
394 #[stable(feature = "env", since = "1.0.0")]
395 impl<'a> Iterator for SplitPaths<'a> {
397 fn next(&mut self) -> Option<PathBuf> { self.inner.next() }
398 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
401 #[stable(feature = "std_debug", since = "1.16.0")]
402 impl fmt::Debug for SplitPaths<'_> {
403 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
404 f.pad("SplitPaths { .. }")
408 /// The error type for operations on the `PATH` variable. Possibly returned from
409 /// the [`env::join_paths`] function.
411 /// [`env::join_paths`]: fn.join_paths.html
413 #[stable(feature = "env", since = "1.0.0")]
414 pub struct JoinPathsError {
415 inner: os_imp::JoinPathsError
418 /// Joins a collection of [`Path`]s appropriately for the `PATH`
419 /// environment variable.
423 /// Returns an [`Err`][err] (containing an error message) if one of the input
424 /// [`Path`]s contains an invalid character for constructing the `PATH`
425 /// variable (a double quote on Windows or a colon on Unix).
427 /// [`Path`]: ../../std/path/struct.Path.html
428 /// [`OsString`]: ../../std/ffi/struct.OsString.html
429 /// [err]: ../../std/result/enum.Result.html#variant.Err
433 /// Joining paths on a Unix-like platform:
437 /// use std::ffi::OsString;
438 /// use std::path::Path;
440 /// fn main() -> Result<(), env::JoinPathsError> {
441 /// # if cfg!(unix) {
442 /// let paths = [Path::new("/bin"), Path::new("/usr/bin")];
443 /// let path_os_string = env::join_paths(paths.iter())?;
444 /// assert_eq!(path_os_string, OsString::from("/bin:/usr/bin"));
450 /// Joining a path containing a colon on a Unix-like platform results in an error:
453 /// # if cfg!(unix) {
455 /// use std::path::Path;
457 /// let paths = [Path::new("/bin"), Path::new("/usr/bi:n")];
458 /// assert!(env::join_paths(paths.iter()).is_err());
462 /// Using `env::join_paths` with `env::spit_paths` to append an item to the `PATH` environment
467 /// use std::path::PathBuf;
469 /// fn main() -> Result<(), env::JoinPathsError> {
470 /// if let Some(path) = env::var_os("PATH") {
471 /// let mut paths = env::split_paths(&path).collect::<Vec<_>>();
472 /// paths.push(PathBuf::from("/home/xyz/bin"));
473 /// let new_path = env::join_paths(paths)?;
474 /// env::set_var("PATH", &new_path);
480 #[stable(feature = "env", since = "1.0.0")]
481 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
482 where I: IntoIterator<Item=T>, T: AsRef<OsStr>
484 os_imp::join_paths(paths.into_iter()).map_err(|e| {
485 JoinPathsError { inner: e }
489 #[stable(feature = "env", since = "1.0.0")]
490 impl fmt::Display for JoinPathsError {
491 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
496 #[stable(feature = "env", since = "1.0.0")]
497 impl Error for JoinPathsError {
498 fn description(&self) -> &str { self.inner.description() }
501 /// Returns the path of the current user's home directory if known.
505 /// - Returns the value of the 'HOME' environment variable if it is set
506 /// (including to an empty string).
507 /// - Otherwise, it tries to determine the home directory by invoking the `getpwuid_r` function
508 /// using the UID of the current user. An empty home directory field returned from the
509 /// `getpwuid_r` function is considered to be a valid value.
510 /// - Returns `None` if the current user has no entry in the /etc/passwd file.
514 /// - Returns the value of the 'HOME' environment variable if it is set
515 /// (including to an empty string).
516 /// - Otherwise, returns the value of the 'USERPROFILE' environment variable if it is set
517 /// (including to an empty string).
518 /// - If both do not exist, [`GetUserProfileDirectory`][msdn] is used to return the path.
520 /// [msdn]: https://msdn.microsoft.com/en-us/library/windows/desktop/bb762280(v=vs.85).aspx
527 /// match env::home_dir() {
528 /// Some(path) => println!("Your home directory, probably: {}", path.display()),
529 /// None => println!("Impossible to get your home dir!"),
532 #[rustc_deprecated(since = "1.29.0",
533 reason = "This function's behavior is unexpected and probably not what you want. \
534 Consider using the home_dir function from https://crates.io/crates/dirs instead.")]
535 #[stable(feature = "env", since = "1.0.0")]
536 pub fn home_dir() -> Option<PathBuf> {
540 /// Returns the path of a temporary directory.
544 /// Returns the value of the `TMPDIR` environment variable if it is
545 /// set, otherwise for non-Android it returns `/tmp`. If Android, since there
546 /// is no global temporary folder (it is usually allocated per-app), it returns
547 /// `/data/local/tmp`.
551 /// Returns the value of, in order, the `TMP`, `TEMP`,
552 /// `USERPROFILE` environment variable if any are set and not the empty
553 /// string. Otherwise, `temp_dir` returns the path of the Windows directory.
554 /// This behavior is identical to that of [`GetTempPath`][msdn], which this
555 /// function uses internally.
557 /// [msdn]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa364992(v=vs.85).aspx
561 /// use std::fs::File;
563 /// fn main() -> std::io::Result<()> {
564 /// let mut dir = env::temp_dir();
565 /// dir.push("foo.txt");
567 /// let f = File::create(dir)?;
571 #[stable(feature = "env", since = "1.0.0")]
572 pub fn temp_dir() -> PathBuf {
576 /// Returns the full filesystem path of the current running executable.
578 /// # Platform-specific behavior
580 /// If the executable was invoked through a symbolic link, some platforms will
581 /// return the path of the symbolic link and other platforms will return the
582 /// path of the symbolic link’s target.
586 /// Acquiring the path of the current executable is a platform-specific operation
587 /// that can fail for a good number of reasons. Some errors can include, but not
588 /// be limited to, filesystem operations failing or general syscall failures.
592 /// The output of this function should not be used in anything that might have
593 /// security implications. For example:
597 /// println!("{:?}", std::env::current_exe());
601 /// On Linux systems, if this is compiled as `foo`:
606 /// Ok("/home/alex/foo")
609 /// And you make a hard link of the program:
615 /// When you run it, you won’t get the path of the original executable, you’ll
616 /// get the path of the hard link:
620 /// Ok("/home/alex/bar")
623 /// This sort of behavior has been known to [lead to privilege escalation] when
624 /// used incorrectly.
626 /// [lead to privilege escalation]: https://securityvulns.com/Wdocument183.html
633 /// match env::current_exe() {
634 /// Ok(exe_path) => println!("Path of this executable is: {}",
635 /// exe_path.display()),
636 /// Err(e) => println!("failed to get current exe path: {}", e),
639 #[stable(feature = "env", since = "1.0.0")]
640 pub fn current_exe() -> io::Result<PathBuf> {
641 os_imp::current_exe()
644 /// An iterator over the arguments of a process, yielding a [`String`] value for
647 /// This struct is created by the [`std::env::args`] function. See its
648 /// documentation for more.
650 /// The first element is traditionally the path of the executable, but it can be
651 /// set to arbitrary text, and may not even exist. This means this property
652 /// should not be relied upon for security purposes.
654 /// [`String`]: ../string/struct.String.html
655 /// [`std::env::args`]: ./fn.args.html
656 #[stable(feature = "env", since = "1.0.0")]
657 pub struct Args { inner: ArgsOs }
659 /// An iterator over the arguments of a process, yielding an [`OsString`] value
660 /// for each argument.
662 /// This struct is created by the [`std::env::args_os`] function. See its
663 /// documentation for more.
665 /// The first element is traditionally the path of the executable, but it can be
666 /// set to arbitrary text, and may not even exist. This means this property
667 /// should not be relied upon for security purposes.
669 /// [`OsString`]: ../ffi/struct.OsString.html
670 /// [`std::env::args_os`]: ./fn.args_os.html
671 #[stable(feature = "env", since = "1.0.0")]
672 pub struct ArgsOs { inner: sys::args::Args }
674 /// Returns the arguments which this program was started with (normally passed
675 /// via the command line).
677 /// The first element is traditionally the path of the executable, but it can be
678 /// set to arbitrary text, and may not even exist. This means this property should
679 /// not be relied upon for security purposes.
681 /// On Unix systems shell usually expands unquoted arguments with glob patterns
682 /// (such as `*` and `?`). On Windows this is not done, and such arguments are
687 /// The returned iterator will panic during iteration if any argument to the
688 /// process is not valid unicode. If this is not desired,
689 /// use the [`args_os`] function instead.
696 /// // Prints each argument on a separate line
697 /// for argument in env::args() {
698 /// println!("{}", argument);
702 /// [`args_os`]: ./fn.args_os.html
703 #[stable(feature = "env", since = "1.0.0")]
704 pub fn args() -> Args {
705 Args { inner: args_os() }
708 /// Returns the arguments which this program was started with (normally passed
709 /// via the command line).
711 /// The first element is traditionally the path of the executable, but it can be
712 /// set to arbitrary text, and it may not even exist, so this property should
713 /// not be relied upon for security purposes.
720 /// // Prints each argument on a separate line
721 /// for argument in env::args_os() {
722 /// println!("{:?}", argument);
725 #[stable(feature = "env", since = "1.0.0")]
726 pub fn args_os() -> ArgsOs {
727 ArgsOs { inner: sys::args::args() }
730 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
731 impl !Send for Args {}
733 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
734 impl !Sync for Args {}
736 #[stable(feature = "env", since = "1.0.0")]
737 impl Iterator for Args {
739 fn next(&mut self) -> Option<String> {
740 self.inner.next().map(|s| s.into_string().unwrap())
742 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
745 #[stable(feature = "env", since = "1.0.0")]
746 impl ExactSizeIterator for Args {
747 fn len(&self) -> usize { self.inner.len() }
748 fn is_empty(&self) -> bool { self.inner.is_empty() }
751 #[stable(feature = "env_iterators", since = "1.12.0")]
752 impl DoubleEndedIterator for Args {
753 fn next_back(&mut self) -> Option<String> {
754 self.inner.next_back().map(|s| s.into_string().unwrap())
758 #[stable(feature = "std_debug", since = "1.16.0")]
759 impl fmt::Debug for Args {
760 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
761 f.debug_struct("Args")
762 .field("inner", &self.inner.inner.inner_debug())
767 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
768 impl !Send for ArgsOs {}
770 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
771 impl !Sync for ArgsOs {}
773 #[stable(feature = "env", since = "1.0.0")]
774 impl Iterator for ArgsOs {
775 type Item = OsString;
776 fn next(&mut self) -> Option<OsString> { self.inner.next() }
777 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
780 #[stable(feature = "env", since = "1.0.0")]
781 impl ExactSizeIterator for ArgsOs {
782 fn len(&self) -> usize { self.inner.len() }
783 fn is_empty(&self) -> bool { self.inner.is_empty() }
786 #[stable(feature = "env_iterators", since = "1.12.0")]
787 impl DoubleEndedIterator for ArgsOs {
788 fn next_back(&mut self) -> Option<OsString> { self.inner.next_back() }
791 #[stable(feature = "std_debug", since = "1.16.0")]
792 impl fmt::Debug for ArgsOs {
793 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
794 f.debug_struct("ArgsOs")
795 .field("inner", &self.inner.inner_debug())
800 /// Constants associated with the current target
801 #[stable(feature = "env", since = "1.0.0")]
803 use crate::sys::env::os;
805 /// A string describing the architecture of the CPU that is currently
808 /// Some possible values:
820 #[stable(feature = "env", since = "1.0.0")]
821 pub const ARCH: &str = super::arch::ARCH;
823 /// The family of the operating system. Example value is `unix`.
825 /// Some possible values:
829 #[stable(feature = "env", since = "1.0.0")]
830 pub const FAMILY: &str = os::FAMILY;
832 /// A string describing the specific operating system in use.
833 /// Example value is `linux`.
835 /// Some possible values:
848 #[stable(feature = "env", since = "1.0.0")]
849 pub const OS: &str = os::OS;
851 /// Specifies the filename prefix used for shared libraries on this
852 /// platform. Example value is `lib`.
854 /// Some possible values:
857 /// - `""` (an empty string)
858 #[stable(feature = "env", since = "1.0.0")]
859 pub const DLL_PREFIX: &str = os::DLL_PREFIX;
861 /// Specifies the filename suffix used for shared libraries on this
862 /// platform. Example value is `.so`.
864 /// Some possible values:
869 #[stable(feature = "env", since = "1.0.0")]
870 pub const DLL_SUFFIX: &str = os::DLL_SUFFIX;
872 /// Specifies the file extension used for shared libraries on this
873 /// platform that goes after the dot. Example value is `so`.
875 /// Some possible values:
880 #[stable(feature = "env", since = "1.0.0")]
881 pub const DLL_EXTENSION: &str = os::DLL_EXTENSION;
883 /// Specifies the filename suffix used for executable binaries on this
884 /// platform. Example value is `.exe`.
886 /// Some possible values:
891 /// - `""` (an empty string)
892 #[stable(feature = "env", since = "1.0.0")]
893 pub const EXE_SUFFIX: &str = os::EXE_SUFFIX;
895 /// Specifies the file extension, if any, used for executable binaries
896 /// on this platform. Example value is `exe`.
898 /// Some possible values:
901 /// - `""` (an empty string)
902 #[stable(feature = "env", since = "1.0.0")]
903 pub const EXE_EXTENSION: &str = os::EXE_EXTENSION;
906 #[cfg(target_arch = "x86")]
908 pub const ARCH: &str = "x86";
911 #[cfg(target_arch = "x86_64")]
913 pub const ARCH: &str = "x86_64";
916 #[cfg(target_arch = "arm")]
918 pub const ARCH: &str = "arm";
921 #[cfg(target_arch = "aarch64")]
923 pub const ARCH: &str = "aarch64";
926 #[cfg(target_arch = "mips")]
928 pub const ARCH: &str = "mips";
931 #[cfg(target_arch = "mips64")]
933 pub const ARCH: &str = "mips64";
936 #[cfg(target_arch = "powerpc")]
938 pub const ARCH: &str = "powerpc";
941 #[cfg(target_arch = "powerpc64")]
943 pub const ARCH: &str = "powerpc64";
946 #[cfg(target_arch = "s390x")]
948 pub const ARCH: &str = "s390x";
951 #[cfg(target_arch = "sparc64")]
953 pub const ARCH: &str = "sparc64";
956 #[cfg(target_arch = "le32")]
958 pub const ARCH: &str = "le32";
961 #[cfg(target_arch = "asmjs")]
963 pub const ARCH: &str = "asmjs";
966 #[cfg(target_arch = "wasm32")]
968 pub const ARCH: &str = "wasm32";
975 use crate::path::Path;
978 #[cfg_attr(any(target_os = "emscripten", target_env = "sgx"), ignore)]
979 fn test_self_exe_path() {
980 let path = current_exe();
981 assert!(path.is_ok());
982 let path = path.unwrap();
984 // Hard to test this function
985 assert!(path.is_absolute());
990 assert!((!Path::new("test-path").is_absolute()));
992 #[cfg(not(target_env = "sgx"))]
993 current_dir().unwrap();
998 fn split_paths_windows() {
999 use crate::path::PathBuf;
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 use crate::path::PathBuf;
1023 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1024 split_paths(unparsed).collect::<Vec<_>>() ==
1025 parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
1028 assert!(check_parse("", &mut [""]));
1029 assert!(check_parse("::", &mut ["", "", ""]));
1030 assert!(check_parse("/", &mut ["/"]));
1031 assert!(check_parse("/:", &mut ["/", ""]));
1032 assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
1037 fn join_paths_unix() {
1038 use crate::ffi::OsStr;
1040 fn test_eq(input: &[&str], output: &str) -> bool {
1041 &*join_paths(input.iter().cloned()).unwrap() ==
1045 assert!(test_eq(&[], ""));
1046 assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"],
1047 "/bin:/usr/bin:/usr/local/bin"));
1048 assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""],
1049 ":/bin:::/usr/bin:"));
1050 assert!(join_paths(["/te:st"].iter().cloned()).is_err());
1055 fn join_paths_windows() {
1056 use crate::ffi::OsStr;
1058 fn test_eq(input: &[&str], output: &str) -> bool {
1059 &*join_paths(input.iter().cloned()).unwrap() ==
1063 assert!(test_eq(&[], ""));
1064 assert!(test_eq(&[r"c:\windows", r"c:\"],
1065 r"c:\windows;c:\"));
1066 assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""],
1067 r";c:\windows;;;c:\;"));
1068 assert!(test_eq(&[r"c:\te;st", r"c:\"],
1069 r#""c:\te;st";c:\"#));
1070 assert!(join_paths([r#"c:\te"st"#].iter().cloned()).is_err());
1076 format!("Args {{ inner: {:?} }}", args().collect::<Vec<_>>()),
1077 format!("{:?}", args()));
1079 format!("ArgsOs {{ inner: {:?} }}", args_os().collect::<Vec<_>>()),
1080 format!("{:?}", args_os()));