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
187 /// This function may panic if `key` is empty, contains an ASCII equals sign
188 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
196 /// let key = "HOME";
197 /// match env::var(key) {
198 /// Ok(val) => println!("{}: {:?}", key, val),
199 /// Err(e) => println!("couldn't interpret {}: {}", key, e),
202 #[stable(feature = "env", since = "1.0.0")]
203 pub fn var<K: AsRef<OsStr>>(key: K) -> Result<String, VarError> {
207 fn _var(key: &OsStr) -> Result<String, VarError> {
209 Some(s) => s.into_string().map_err(VarError::NotUnicode),
210 None => Err(VarError::NotPresent),
214 /// Fetches the environment variable `key` from the current process, returning
215 /// [`None`] if the variable isn't set.
217 /// [`None`]: ../option/enum.Option.html#variant.None
221 /// This function may panic if `key` is empty, contains an ASCII equals sign
222 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
230 /// let key = "HOME";
231 /// match env::var_os(key) {
232 /// Some(val) => println!("{}: {:?}", key, val),
233 /// None => println!("{} is not defined in the environment.", key)
236 #[stable(feature = "env", since = "1.0.0")]
237 pub fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> {
238 _var_os(key.as_ref())
241 fn _var_os(key: &OsStr) -> Option<OsString> {
242 os_imp::getenv(key).unwrap_or_else(|e| {
243 panic!("failed to get environment variable `{:?}`: {}", key, e)
247 /// The error type for operations interacting with environment variables.
248 /// Possibly returned from the [`env::var`] function.
250 /// [`env::var`]: fn.var.html
251 #[derive(Debug, PartialEq, Eq, Clone)]
252 #[stable(feature = "env", since = "1.0.0")]
254 /// The specified environment variable was not present in the current
255 /// process's environment.
256 #[stable(feature = "env", since = "1.0.0")]
259 /// The specified environment variable was found, but it did not contain
260 /// valid unicode data. The found data is returned as a payload of this
262 #[stable(feature = "env", since = "1.0.0")]
263 NotUnicode(#[stable(feature = "env", since = "1.0.0")] OsString),
266 #[stable(feature = "env", since = "1.0.0")]
267 impl fmt::Display for VarError {
268 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
270 VarError::NotPresent => write!(f, "environment variable not found"),
271 VarError::NotUnicode(ref s) => {
272 write!(f, "environment variable was not valid unicode: {:?}", s)
278 #[stable(feature = "env", since = "1.0.0")]
279 impl Error for VarError {
280 fn description(&self) -> &str {
282 VarError::NotPresent => "environment variable not found",
283 VarError::NotUnicode(..) => "environment variable was not valid unicode",
288 /// Sets the environment variable `k` to the value `v` for the currently running
291 /// Note that while concurrent access to environment variables is safe in Rust,
292 /// some platforms only expose inherently unsafe non-threadsafe APIs for
293 /// inspecting the environment. As a result extra care needs to be taken when
294 /// auditing calls to unsafe external FFI functions to ensure that any external
295 /// environment accesses are properly synchronized with accesses in Rust.
297 /// Discussion of this unsafety on Unix may be found in:
299 /// - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188)
300 /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
304 /// This function may panic if `key` is empty, contains an ASCII equals sign
305 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
314 /// env::set_var(key, "VALUE");
315 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
317 #[stable(feature = "env", since = "1.0.0")]
318 pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(k: K, v: V) {
319 _set_var(k.as_ref(), v.as_ref())
322 fn _set_var(k: &OsStr, v: &OsStr) {
323 os_imp::setenv(k, v).unwrap_or_else(|e| {
324 panic!("failed to set environment variable `{:?}` to `{:?}`: {}",
329 /// Removes an environment variable from the environment of the currently running process.
331 /// Note that while concurrent access to environment variables is safe in Rust,
332 /// some platforms only expose inherently unsafe non-threadsafe APIs for
333 /// inspecting the environment. As a result extra care needs to be taken when
334 /// auditing calls to unsafe external FFI functions to ensure that any external
335 /// environment accesses are properly synchronized with accesses in Rust.
337 /// Discussion of this unsafety on Unix may be found in:
339 /// - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188)
340 /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
344 /// This function may panic if `key` is empty, contains an ASCII equals sign
345 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
354 /// env::set_var(key, "VALUE");
355 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
357 /// env::remove_var(key);
358 /// assert!(env::var(key).is_err());
360 #[stable(feature = "env", since = "1.0.0")]
361 pub fn remove_var<K: AsRef<OsStr>>(k: K) {
362 _remove_var(k.as_ref())
365 fn _remove_var(k: &OsStr) {
366 os_imp::unsetenv(k).unwrap_or_else(|e| {
367 panic!("failed to remove environment variable `{:?}`: {}", k, e)
371 /// An iterator that splits an environment variable into paths according to
372 /// platform-specific conventions.
374 /// The iterator element type is [`PathBuf`].
376 /// This structure is created by the [`std::env::split_paths`] function. See its
377 /// documentation for more.
379 /// [`PathBuf`]: ../../std/path/struct.PathBuf.html
380 /// [`std::env::split_paths`]: fn.split_paths.html
381 #[stable(feature = "env", since = "1.0.0")]
382 pub struct SplitPaths<'a> { inner: os_imp::SplitPaths<'a> }
384 /// Parses input according to platform conventions for the `PATH`
385 /// environment variable.
387 /// Returns an iterator over the paths contained in `unparsed`. The iterator
388 /// element type is [`PathBuf`].
395 /// let key = "PATH";
396 /// match env::var_os(key) {
398 /// for path in env::split_paths(&paths) {
399 /// println!("'{}'", path.display());
402 /// None => println!("{} is not defined in the environment.", key)
406 /// [`PathBuf`]: ../../std/path/struct.PathBuf.html
407 #[stable(feature = "env", since = "1.0.0")]
408 pub fn split_paths<T: AsRef<OsStr> + ?Sized>(unparsed: &T) -> SplitPaths<'_> {
409 SplitPaths { inner: os_imp::split_paths(unparsed.as_ref()) }
412 #[stable(feature = "env", since = "1.0.0")]
413 impl<'a> Iterator for SplitPaths<'a> {
415 fn next(&mut self) -> Option<PathBuf> { self.inner.next() }
416 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
419 #[stable(feature = "std_debug", since = "1.16.0")]
420 impl fmt::Debug for SplitPaths<'_> {
421 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
422 f.pad("SplitPaths { .. }")
426 /// The error type for operations on the `PATH` variable. Possibly returned from
427 /// the [`env::join_paths`] function.
429 /// [`env::join_paths`]: fn.join_paths.html
431 #[stable(feature = "env", since = "1.0.0")]
432 pub struct JoinPathsError {
433 inner: os_imp::JoinPathsError
436 /// Joins a collection of [`Path`]s appropriately for the `PATH`
437 /// environment variable.
441 /// Returns an [`Err`][err] (containing an error message) if one of the input
442 /// [`Path`]s contains an invalid character for constructing the `PATH`
443 /// variable (a double quote on Windows or a colon on Unix).
445 /// [`Path`]: ../../std/path/struct.Path.html
446 /// [`OsString`]: ../../std/ffi/struct.OsString.html
447 /// [err]: ../../std/result/enum.Result.html#variant.Err
451 /// Joining paths on a Unix-like platform:
455 /// use std::ffi::OsString;
456 /// use std::path::Path;
458 /// fn main() -> Result<(), env::JoinPathsError> {
459 /// # if cfg!(unix) {
460 /// let paths = [Path::new("/bin"), Path::new("/usr/bin")];
461 /// let path_os_string = env::join_paths(paths.iter())?;
462 /// assert_eq!(path_os_string, OsString::from("/bin:/usr/bin"));
468 /// Joining a path containing a colon on a Unix-like platform results in an error:
471 /// # if cfg!(unix) {
473 /// use std::path::Path;
475 /// let paths = [Path::new("/bin"), Path::new("/usr/bi:n")];
476 /// assert!(env::join_paths(paths.iter()).is_err());
480 /// Using `env::join_paths` with [`env::split_paths`] to append an item to the `PATH` environment
485 /// use std::path::PathBuf;
487 /// fn main() -> Result<(), env::JoinPathsError> {
488 /// if let Some(path) = env::var_os("PATH") {
489 /// let mut paths = env::split_paths(&path).collect::<Vec<_>>();
490 /// paths.push(PathBuf::from("/home/xyz/bin"));
491 /// let new_path = env::join_paths(paths)?;
492 /// env::set_var("PATH", &new_path);
499 /// [`env::split_paths`]: fn.split_paths.html
500 #[stable(feature = "env", since = "1.0.0")]
501 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
502 where I: IntoIterator<Item=T>, T: AsRef<OsStr>
504 os_imp::join_paths(paths.into_iter()).map_err(|e| {
505 JoinPathsError { inner: e }
509 #[stable(feature = "env", since = "1.0.0")]
510 impl fmt::Display for JoinPathsError {
511 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
516 #[stable(feature = "env", since = "1.0.0")]
517 impl Error for JoinPathsError {
518 fn description(&self) -> &str { self.inner.description() }
521 /// Returns the path of the current user's home directory if known.
525 /// - Returns the value of the 'HOME' environment variable if it is set
526 /// (including to an empty string).
527 /// - Otherwise, it tries to determine the home directory by invoking the `getpwuid_r` function
528 /// using the UID of the current user. An empty home directory field returned from the
529 /// `getpwuid_r` function is considered to be a valid value.
530 /// - Returns `None` if the current user has no entry in the /etc/passwd file.
534 /// - Returns the value of the 'HOME' environment variable if it is set
535 /// (including to an empty string).
536 /// - Otherwise, returns the value of the 'USERPROFILE' environment variable if it is set
537 /// (including to an empty string).
538 /// - If both do not exist, [`GetUserProfileDirectory`][msdn] is used to return the path.
540 /// [msdn]: https://msdn.microsoft.com/en-us/library/windows/desktop/bb762280(v=vs.85).aspx
547 /// match env::home_dir() {
548 /// Some(path) => println!("Your home directory, probably: {}", path.display()),
549 /// None => println!("Impossible to get your home dir!"),
552 #[rustc_deprecated(since = "1.29.0",
553 reason = "This function's behavior is unexpected and probably not what you want. \
554 Consider using the home_dir function from https://crates.io/crates/dirs instead.")]
555 #[stable(feature = "env", since = "1.0.0")]
556 pub fn home_dir() -> Option<PathBuf> {
560 /// Returns the path of a temporary directory.
564 /// Returns the value of the `TMPDIR` environment variable if it is
565 /// set, otherwise for non-Android it returns `/tmp`. If Android, since there
566 /// is no global temporary folder (it is usually allocated per-app), it returns
567 /// `/data/local/tmp`.
571 /// Returns the value of, in order, the `TMP`, `TEMP`,
572 /// `USERPROFILE` environment variable if any are set and not the empty
573 /// string. Otherwise, `temp_dir` returns the path of the Windows directory.
574 /// This behavior is identical to that of [`GetTempPath`][msdn], which this
575 /// function uses internally.
577 /// [msdn]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa364992(v=vs.85).aspx
581 /// use std::fs::File;
583 /// fn main() -> std::io::Result<()> {
584 /// let mut dir = env::temp_dir();
585 /// dir.push("foo.txt");
587 /// let f = File::create(dir)?;
591 #[stable(feature = "env", since = "1.0.0")]
592 pub fn temp_dir() -> PathBuf {
596 /// Returns the full filesystem path of the current running executable.
598 /// # Platform-specific behavior
600 /// If the executable was invoked through a symbolic link, some platforms will
601 /// return the path of the symbolic link and other platforms will return the
602 /// path of the symbolic link’s target.
606 /// Acquiring the path of the current executable is a platform-specific operation
607 /// that can fail for a good number of reasons. Some errors can include, but not
608 /// be limited to, filesystem operations failing or general syscall failures.
612 /// The output of this function should not be used in anything that might have
613 /// security implications. For example:
617 /// println!("{:?}", std::env::current_exe());
621 /// On Linux systems, if this is compiled as `foo`:
626 /// Ok("/home/alex/foo")
629 /// And you make a hard link of the program:
635 /// When you run it, you won’t get the path of the original executable, you’ll
636 /// get the path of the hard link:
640 /// Ok("/home/alex/bar")
643 /// This sort of behavior has been known to [lead to privilege escalation] when
644 /// used incorrectly.
646 /// [lead to privilege escalation]: https://securityvulns.com/Wdocument183.html
653 /// match env::current_exe() {
654 /// Ok(exe_path) => println!("Path of this executable is: {}",
655 /// exe_path.display()),
656 /// Err(e) => println!("failed to get current exe path: {}", e),
659 #[stable(feature = "env", since = "1.0.0")]
660 pub fn current_exe() -> io::Result<PathBuf> {
661 os_imp::current_exe()
664 /// An iterator over the arguments of a process, yielding a [`String`] value for
667 /// This struct is created by the [`std::env::args`] function. See its
668 /// documentation for more.
670 /// The first element is traditionally the path of the executable, but it can be
671 /// set to arbitrary text, and may not even exist. This means this property
672 /// should not be relied upon for security purposes.
674 /// [`String`]: ../string/struct.String.html
675 /// [`std::env::args`]: ./fn.args.html
676 #[stable(feature = "env", since = "1.0.0")]
677 pub struct Args { inner: ArgsOs }
679 /// An iterator over the arguments of a process, yielding an [`OsString`] value
680 /// for each argument.
682 /// This struct is created by the [`std::env::args_os`] function. See its
683 /// documentation for more.
685 /// The first element is traditionally the path of the executable, but it can be
686 /// set to arbitrary text, and may not even exist. This means this property
687 /// should not be relied upon for security purposes.
689 /// [`OsString`]: ../ffi/struct.OsString.html
690 /// [`std::env::args_os`]: ./fn.args_os.html
691 #[stable(feature = "env", since = "1.0.0")]
692 pub struct ArgsOs { inner: sys::args::Args }
694 /// Returns the arguments which this program was started with (normally passed
695 /// via the command line).
697 /// The first element is traditionally the path of the executable, but it can be
698 /// set to arbitrary text, and may not even exist. This means this property should
699 /// not be relied upon for security purposes.
701 /// On Unix systems shell usually expands unquoted arguments with glob patterns
702 /// (such as `*` and `?`). On Windows this is not done, and such arguments are
707 /// The returned iterator will panic during iteration if any argument to the
708 /// process is not valid unicode. If this is not desired,
709 /// use the [`args_os`] function instead.
716 /// // Prints each argument on a separate line
717 /// for argument in env::args() {
718 /// println!("{}", argument);
722 /// [`args_os`]: ./fn.args_os.html
723 #[stable(feature = "env", since = "1.0.0")]
724 pub fn args() -> Args {
725 Args { inner: args_os() }
728 /// Returns the arguments which this program was started with (normally passed
729 /// via the command line).
731 /// The first element is traditionally the path of the executable, but it can be
732 /// set to arbitrary text, and it may not even exist, so this property should
733 /// not be relied upon for security purposes.
740 /// // Prints each argument on a separate line
741 /// for argument in env::args_os() {
742 /// println!("{:?}", argument);
745 #[stable(feature = "env", since = "1.0.0")]
746 pub fn args_os() -> ArgsOs {
747 ArgsOs { inner: sys::args::args() }
750 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
751 impl !Send for Args {}
753 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
754 impl !Sync for Args {}
756 #[stable(feature = "env", since = "1.0.0")]
757 impl Iterator for Args {
759 fn next(&mut self) -> Option<String> {
760 self.inner.next().map(|s| s.into_string().unwrap())
762 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
765 #[stable(feature = "env", since = "1.0.0")]
766 impl ExactSizeIterator for Args {
767 fn len(&self) -> usize { self.inner.len() }
768 fn is_empty(&self) -> bool { self.inner.is_empty() }
771 #[stable(feature = "env_iterators", since = "1.12.0")]
772 impl DoubleEndedIterator for Args {
773 fn next_back(&mut self) -> Option<String> {
774 self.inner.next_back().map(|s| s.into_string().unwrap())
778 #[stable(feature = "std_debug", since = "1.16.0")]
779 impl fmt::Debug for Args {
780 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
781 f.debug_struct("Args")
782 .field("inner", &self.inner.inner.inner_debug())
787 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
788 impl !Send for ArgsOs {}
790 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
791 impl !Sync for ArgsOs {}
793 #[stable(feature = "env", since = "1.0.0")]
794 impl Iterator for ArgsOs {
795 type Item = OsString;
796 fn next(&mut self) -> Option<OsString> { self.inner.next() }
797 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
800 #[stable(feature = "env", since = "1.0.0")]
801 impl ExactSizeIterator for ArgsOs {
802 fn len(&self) -> usize { self.inner.len() }
803 fn is_empty(&self) -> bool { self.inner.is_empty() }
806 #[stable(feature = "env_iterators", since = "1.12.0")]
807 impl DoubleEndedIterator for ArgsOs {
808 fn next_back(&mut self) -> Option<OsString> { self.inner.next_back() }
811 #[stable(feature = "std_debug", since = "1.16.0")]
812 impl fmt::Debug for ArgsOs {
813 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
814 f.debug_struct("ArgsOs")
815 .field("inner", &self.inner.inner_debug())
820 /// Constants associated with the current target
821 #[stable(feature = "env", since = "1.0.0")]
823 use crate::sys::env::os;
825 /// A string describing the architecture of the CPU that is currently
828 /// Some possible values:
840 #[stable(feature = "env", since = "1.0.0")]
841 pub const ARCH: &str = super::arch::ARCH;
843 /// The family of the operating system. Example value is `unix`.
845 /// Some possible values:
849 #[stable(feature = "env", since = "1.0.0")]
850 pub const FAMILY: &str = os::FAMILY;
852 /// A string describing the specific operating system in use.
853 /// Example value is `linux`.
855 /// Some possible values:
867 #[stable(feature = "env", since = "1.0.0")]
868 pub const OS: &str = os::OS;
870 /// Specifies the filename prefix used for shared libraries on this
871 /// platform. Example value is `lib`.
873 /// Some possible values:
876 /// - `""` (an empty string)
877 #[stable(feature = "env", since = "1.0.0")]
878 pub const DLL_PREFIX: &str = os::DLL_PREFIX;
880 /// Specifies the filename suffix used for shared libraries on this
881 /// platform. Example value is `.so`.
883 /// Some possible values:
888 #[stable(feature = "env", since = "1.0.0")]
889 pub const DLL_SUFFIX: &str = os::DLL_SUFFIX;
891 /// Specifies the file extension used for shared libraries on this
892 /// platform that goes after the dot. Example value is `so`.
894 /// Some possible values:
899 #[stable(feature = "env", since = "1.0.0")]
900 pub const DLL_EXTENSION: &str = os::DLL_EXTENSION;
902 /// Specifies the filename suffix used for executable binaries on this
903 /// platform. Example value is `.exe`.
905 /// Some possible values:
910 /// - `""` (an empty string)
911 #[stable(feature = "env", since = "1.0.0")]
912 pub const EXE_SUFFIX: &str = os::EXE_SUFFIX;
914 /// Specifies the file extension, if any, used for executable binaries
915 /// on this platform. Example value is `exe`.
917 /// Some possible values:
920 /// - `""` (an empty string)
921 #[stable(feature = "env", since = "1.0.0")]
922 pub const EXE_EXTENSION: &str = os::EXE_EXTENSION;
925 #[cfg(target_arch = "x86")]
927 pub const ARCH: &str = "x86";
930 #[cfg(target_arch = "x86_64")]
932 pub const ARCH: &str = "x86_64";
935 #[cfg(target_arch = "arm")]
937 pub const ARCH: &str = "arm";
940 #[cfg(target_arch = "aarch64")]
942 pub const ARCH: &str = "aarch64";
945 #[cfg(target_arch = "mips")]
947 pub const ARCH: &str = "mips";
950 #[cfg(target_arch = "mips64")]
952 pub const ARCH: &str = "mips64";
955 #[cfg(target_arch = "powerpc")]
957 pub const ARCH: &str = "powerpc";
960 #[cfg(target_arch = "powerpc64")]
962 pub const ARCH: &str = "powerpc64";
965 #[cfg(target_arch = "s390x")]
967 pub const ARCH: &str = "s390x";
970 #[cfg(target_arch = "sparc64")]
972 pub const ARCH: &str = "sparc64";
975 #[cfg(target_arch = "le32")]
977 pub const ARCH: &str = "le32";
980 #[cfg(target_arch = "asmjs")]
982 pub const ARCH: &str = "asmjs";
985 #[cfg(target_arch = "wasm32")]
987 pub const ARCH: &str = "wasm32";
990 #[cfg(target_arch = "hexagon")]
992 pub const ARCH: &'static str = "hexagon";
999 use crate::path::Path;
1002 #[cfg_attr(any(target_os = "emscripten", target_env = "sgx"), ignore)]
1003 fn test_self_exe_path() {
1004 let path = current_exe();
1005 assert!(path.is_ok());
1006 let path = path.unwrap();
1008 // Hard to test this function
1009 assert!(path.is_absolute());
1014 assert!((!Path::new("test-path").is_absolute()));
1016 #[cfg(not(target_env = "sgx"))]
1017 current_dir().unwrap();
1022 fn split_paths_windows() {
1023 use crate::path::PathBuf;
1025 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1026 split_paths(unparsed).collect::<Vec<_>>() ==
1027 parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
1030 assert!(check_parse("", &mut [""]));
1031 assert!(check_parse(r#""""#, &mut [""]));
1032 assert!(check_parse(";;", &mut ["", "", ""]));
1033 assert!(check_parse(r"c:\", &mut [r"c:\"]));
1034 assert!(check_parse(r"c:\;", &mut [r"c:\", ""]));
1035 assert!(check_parse(r"c:\;c:\Program Files\",
1036 &mut [r"c:\", r"c:\Program Files\"]));
1037 assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
1038 assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
1039 &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
1044 fn split_paths_unix() {
1045 use crate::path::PathBuf;
1047 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1048 split_paths(unparsed).collect::<Vec<_>>() ==
1049 parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
1052 assert!(check_parse("", &mut [""]));
1053 assert!(check_parse("::", &mut ["", "", ""]));
1054 assert!(check_parse("/", &mut ["/"]));
1055 assert!(check_parse("/:", &mut ["/", ""]));
1056 assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
1061 fn join_paths_unix() {
1062 use crate::ffi::OsStr;
1064 fn test_eq(input: &[&str], output: &str) -> bool {
1065 &*join_paths(input.iter().cloned()).unwrap() ==
1069 assert!(test_eq(&[], ""));
1070 assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"],
1071 "/bin:/usr/bin:/usr/local/bin"));
1072 assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""],
1073 ":/bin:::/usr/bin:"));
1074 assert!(join_paths(["/te:st"].iter().cloned()).is_err());
1079 fn join_paths_windows() {
1080 use crate::ffi::OsStr;
1082 fn test_eq(input: &[&str], output: &str) -> bool {
1083 &*join_paths(input.iter().cloned()).unwrap() ==
1087 assert!(test_eq(&[], ""));
1088 assert!(test_eq(&[r"c:\windows", r"c:\"],
1089 r"c:\windows;c:\"));
1090 assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""],
1091 r";c:\windows;;;c:\;"));
1092 assert!(test_eq(&[r"c:\te;st", r"c:\"],
1093 r#""c:\te;st";c:\"#));
1094 assert!(join_paths([r#"c:\te"st"#].iter().cloned()).is_err());
1100 format!("Args {{ inner: {:?} }}", args().collect::<Vec<_>>()),
1101 format!("{:?}", args()));
1103 format!("ArgsOs {{ inner: {:?} }}", args_os().collect::<Vec<_>>()),
1104 format!("{:?}", args_os()));