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")]
85 /// An iterator over a snapshot of the environment variables of this process.
87 /// This structure is created by the [`std::env::vars_os`] function. See
88 /// its documentation for more.
90 /// [`std::env::vars_os`]: fn.vars_os.html
91 #[stable(feature = "env", since = "1.0.0")]
96 /// Returns an iterator of (variable, value) pairs of strings, for all the
97 /// environment variables of the current process.
99 /// The returned iterator contains a snapshot of the process's environment
100 /// variables at the time of this invocation. Modifications to environment
101 /// variables afterwards will not be reflected in the returned iterator.
105 /// While iterating, the returned iterator will panic if any key or value in the
106 /// environment is not valid unicode. If this is not desired, consider using the
107 /// [`env::vars_os`] function.
109 /// [`env::vars_os`]: fn.vars_os.html
116 /// // We will iterate through the references to the element returned by
118 /// for (key, value) in env::vars() {
119 /// println!("{}: {}", key, value);
122 #[stable(feature = "env", since = "1.0.0")]
123 pub fn vars() -> Vars {
124 Vars { inner: vars_os() }
127 /// Returns an iterator of (variable, value) pairs of OS strings, for all the
128 /// environment variables of the current process.
130 /// The returned iterator contains a snapshot of the process's environment
131 /// variables at the time of this invocation. Modifications to environment
132 /// variables afterwards will not be reflected in the returned iterator.
139 /// // We will iterate through the references to the element returned by
140 /// // env::vars_os();
141 /// for (key, value) in env::vars_os() {
142 /// println!("{:?}: {:?}", key, value);
145 #[stable(feature = "env", since = "1.0.0")]
146 pub fn vars_os() -> VarsOs {
147 VarsOs { inner: os_imp::env() }
150 #[stable(feature = "env", since = "1.0.0")]
151 impl Iterator for Vars {
152 type Item = (String, String);
153 fn next(&mut self) -> Option<(String, String)> {
154 self.inner.next().map(|(a, b)| (a.into_string().unwrap(), b.into_string().unwrap()))
156 fn size_hint(&self) -> (usize, Option<usize>) {
157 self.inner.size_hint()
161 #[stable(feature = "std_debug", since = "1.16.0")]
162 impl fmt::Debug for Vars {
163 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168 #[stable(feature = "env", since = "1.0.0")]
169 impl Iterator for VarsOs {
170 type Item = (OsString, OsString);
171 fn next(&mut self) -> Option<(OsString, OsString)> {
174 fn size_hint(&self) -> (usize, Option<usize>) {
175 self.inner.size_hint()
179 #[stable(feature = "std_debug", since = "1.16.0")]
180 impl fmt::Debug for VarsOs {
181 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182 f.pad("VarsOs { .. }")
186 /// Fetches the environment variable `key` from the current process.
190 /// * Environment variable is not present
191 /// * Environment variable is not valid unicode
195 /// This function may panic if `key` is empty, contains an ASCII equals sign
196 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
204 /// let key = "HOME";
205 /// match env::var(key) {
206 /// Ok(val) => println!("{}: {:?}", key, val),
207 /// Err(e) => println!("couldn't interpret {}: {}", key, e),
210 #[stable(feature = "env", since = "1.0.0")]
211 pub fn var<K: AsRef<OsStr>>(key: K) -> Result<String, VarError> {
215 fn _var(key: &OsStr) -> Result<String, VarError> {
217 Some(s) => s.into_string().map_err(VarError::NotUnicode),
218 None => Err(VarError::NotPresent),
222 /// Fetches the environment variable `key` from the current process, returning
223 /// [`None`] if the variable isn't set.
225 /// [`None`]: ../option/enum.Option.html#variant.None
229 /// This function may panic if `key` is empty, contains an ASCII equals sign
230 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
238 /// let key = "HOME";
239 /// match env::var_os(key) {
240 /// Some(val) => println!("{}: {:?}", key, val),
241 /// None => println!("{} is not defined in the environment.", key)
244 #[stable(feature = "env", since = "1.0.0")]
245 pub fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> {
246 _var_os(key.as_ref())
249 fn _var_os(key: &OsStr) -> Option<OsString> {
251 .unwrap_or_else(|e| panic!("failed to get environment variable `{:?}`: {}", key, e))
254 /// The error type for operations interacting with environment variables.
255 /// Possibly returned from the [`env::var`] function.
257 /// [`env::var`]: fn.var.html
258 #[derive(Debug, PartialEq, Eq, Clone)]
259 #[stable(feature = "env", since = "1.0.0")]
261 /// The specified environment variable was not present in the current
262 /// process's environment.
263 #[stable(feature = "env", since = "1.0.0")]
266 /// The specified environment variable was found, but it did not contain
267 /// valid unicode data. The found data is returned as a payload of this
269 #[stable(feature = "env", since = "1.0.0")]
270 NotUnicode(#[stable(feature = "env", since = "1.0.0")] OsString),
273 #[stable(feature = "env", since = "1.0.0")]
274 impl fmt::Display for VarError {
275 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
277 VarError::NotPresent => write!(f, "environment variable not found"),
278 VarError::NotUnicode(ref s) => {
279 write!(f, "environment variable was not valid unicode: {:?}", s)
285 #[stable(feature = "env", since = "1.0.0")]
286 impl Error for VarError {
287 fn description(&self) -> &str {
289 VarError::NotPresent => "environment variable not found",
290 VarError::NotUnicode(..) => "environment variable was not valid unicode",
295 /// Sets the environment variable `k` to the value `v` for the currently running
298 /// Note that while concurrent access to environment variables is safe in Rust,
299 /// some platforms only expose inherently unsafe non-threadsafe APIs for
300 /// inspecting the environment. As a result, extra care needs to be taken when
301 /// auditing calls to unsafe external FFI functions to ensure that any external
302 /// environment accesses are properly synchronized with accesses in Rust.
304 /// Discussion of this unsafety on Unix may be found in:
306 /// - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188)
307 /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
311 /// This function may panic if `key` is empty, contains an ASCII equals sign
312 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
321 /// env::set_var(key, "VALUE");
322 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
324 #[stable(feature = "env", since = "1.0.0")]
325 pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(k: K, v: V) {
326 _set_var(k.as_ref(), v.as_ref())
329 fn _set_var(k: &OsStr, v: &OsStr) {
330 os_imp::setenv(k, v).unwrap_or_else(|e| {
331 panic!("failed to set environment variable `{:?}` to `{:?}`: {}", k, v, e)
335 /// Removes an environment variable from the environment of the currently running process.
337 /// Note that while concurrent access to environment variables is safe in Rust,
338 /// some platforms only expose inherently unsafe non-threadsafe APIs for
339 /// inspecting the environment. As a result extra care needs to be taken when
340 /// auditing calls to unsafe external FFI functions to ensure that any external
341 /// environment accesses are properly synchronized with accesses in Rust.
343 /// Discussion of this unsafety on Unix may be found in:
345 /// - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188)
346 /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
350 /// This function may panic if `key` is empty, contains an ASCII equals sign
351 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
360 /// env::set_var(key, "VALUE");
361 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
363 /// env::remove_var(key);
364 /// assert!(env::var(key).is_err());
366 #[stable(feature = "env", since = "1.0.0")]
367 pub fn remove_var<K: AsRef<OsStr>>(k: K) {
368 _remove_var(k.as_ref())
371 fn _remove_var(k: &OsStr) {
373 .unwrap_or_else(|e| panic!("failed to remove environment variable `{:?}`: {}", k, e))
376 /// An iterator that splits an environment variable into paths according to
377 /// platform-specific conventions.
379 /// The iterator element type is [`PathBuf`].
381 /// This structure is created by the [`std::env::split_paths`] function. See its
382 /// documentation for more.
384 /// [`PathBuf`]: ../../std/path/struct.PathBuf.html
385 /// [`std::env::split_paths`]: fn.split_paths.html
386 #[stable(feature = "env", since = "1.0.0")]
387 pub struct SplitPaths<'a> {
388 inner: os_imp::SplitPaths<'a>,
391 /// Parses input according to platform conventions for the `PATH`
392 /// environment variable.
394 /// Returns an iterator over the paths contained in `unparsed`. The iterator
395 /// element type is [`PathBuf`].
402 /// let key = "PATH";
403 /// match env::var_os(key) {
405 /// for path in env::split_paths(&paths) {
406 /// println!("'{}'", path.display());
409 /// None => println!("{} is not defined in the environment.", key)
413 /// [`PathBuf`]: ../../std/path/struct.PathBuf.html
414 #[stable(feature = "env", since = "1.0.0")]
415 pub fn split_paths<T: AsRef<OsStr> + ?Sized>(unparsed: &T) -> SplitPaths<'_> {
416 SplitPaths { inner: os_imp::split_paths(unparsed.as_ref()) }
419 #[stable(feature = "env", since = "1.0.0")]
420 impl<'a> Iterator for SplitPaths<'a> {
422 fn next(&mut self) -> Option<PathBuf> {
425 fn size_hint(&self) -> (usize, Option<usize>) {
426 self.inner.size_hint()
430 #[stable(feature = "std_debug", since = "1.16.0")]
431 impl fmt::Debug for SplitPaths<'_> {
432 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
433 f.pad("SplitPaths { .. }")
437 /// The error type for operations on the `PATH` variable. Possibly returned from
438 /// the [`env::join_paths`] function.
440 /// [`env::join_paths`]: fn.join_paths.html
442 #[stable(feature = "env", since = "1.0.0")]
443 pub struct JoinPathsError {
444 inner: os_imp::JoinPathsError,
447 /// Joins a collection of [`Path`]s appropriately for the `PATH`
448 /// environment variable.
452 /// Returns an [`Err`][err] (containing an error message) if one of the input
453 /// [`Path`]s contains an invalid character for constructing the `PATH`
454 /// variable (a double quote on Windows or a colon on Unix).
456 /// [`Path`]: ../../std/path/struct.Path.html
457 /// [`OsString`]: ../../std/ffi/struct.OsString.html
458 /// [err]: ../../std/result/enum.Result.html#variant.Err
462 /// Joining paths on a Unix-like platform:
466 /// use std::ffi::OsString;
467 /// use std::path::Path;
469 /// fn main() -> Result<(), env::JoinPathsError> {
470 /// # if cfg!(unix) {
471 /// let paths = [Path::new("/bin"), Path::new("/usr/bin")];
472 /// let path_os_string = env::join_paths(paths.iter())?;
473 /// assert_eq!(path_os_string, OsString::from("/bin:/usr/bin"));
479 /// Joining a path containing a colon on a Unix-like platform results in an error:
482 /// # if cfg!(unix) {
484 /// use std::path::Path;
486 /// let paths = [Path::new("/bin"), Path::new("/usr/bi:n")];
487 /// assert!(env::join_paths(paths.iter()).is_err());
491 /// Using `env::join_paths` with [`env::split_paths`] to append an item to the `PATH` environment
496 /// use std::path::PathBuf;
498 /// fn main() -> Result<(), env::JoinPathsError> {
499 /// if let Some(path) = env::var_os("PATH") {
500 /// let mut paths = env::split_paths(&path).collect::<Vec<_>>();
501 /// paths.push(PathBuf::from("/home/xyz/bin"));
502 /// let new_path = env::join_paths(paths)?;
503 /// env::set_var("PATH", &new_path);
510 /// [`env::split_paths`]: fn.split_paths.html
511 #[stable(feature = "env", since = "1.0.0")]
512 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
514 I: IntoIterator<Item = T>,
517 os_imp::join_paths(paths.into_iter()).map_err(|e| JoinPathsError { inner: e })
520 #[stable(feature = "env", since = "1.0.0")]
521 impl fmt::Display for JoinPathsError {
522 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
527 #[stable(feature = "env", since = "1.0.0")]
528 impl Error for JoinPathsError {
529 fn description(&self) -> &str {
530 self.inner.description()
534 /// Returns the path of the current user's home directory if known.
538 /// - Returns the value of the 'HOME' environment variable if it is set
539 /// (including to an empty string).
540 /// - Otherwise, it tries to determine the home directory by invoking the `getpwuid_r` function
541 /// using the UID of the current user. An empty home directory field returned from the
542 /// `getpwuid_r` function is considered to be a valid value.
543 /// - Returns `None` if the current user has no entry in the /etc/passwd file.
547 /// - Returns the value of the 'HOME' environment variable if it is set
548 /// (including to an empty string).
549 /// - Otherwise, returns the value of the 'USERPROFILE' environment variable if it is set
550 /// (including to an empty string).
551 /// - If both do not exist, [`GetUserProfileDirectory`][msdn] is used to return the path.
553 /// [msdn]: https://docs.microsoft.com/en-us/windows/win32/api/userenv/nf-userenv-getuserprofiledirectorya
560 /// match env::home_dir() {
561 /// Some(path) => println!("Your home directory, probably: {}", path.display()),
562 /// None => println!("Impossible to get your home dir!"),
567 reason = "This function's behavior is unexpected and probably not what you want. \
568 Consider using the home_dir function from https://crates.io/crates/dirs instead."
570 #[stable(feature = "env", since = "1.0.0")]
571 pub fn home_dir() -> Option<PathBuf> {
575 /// Returns the path of a temporary directory.
579 /// Returns the value of the `TMPDIR` environment variable if it is
580 /// set, otherwise for non-Android it returns `/tmp`. If Android, since there
581 /// is no global temporary folder (it is usually allocated per-app), it returns
582 /// `/data/local/tmp`.
586 /// Returns the value of, in order, the `TMP`, `TEMP`,
587 /// `USERPROFILE` environment variable if any are set and not the empty
588 /// string. Otherwise, `temp_dir` returns the path of the Windows directory.
589 /// This behavior is identical to that of [`GetTempPath`][msdn], which this
590 /// function uses internally.
592 /// [msdn]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppatha
596 /// use std::fs::File;
598 /// fn main() -> std::io::Result<()> {
599 /// let mut dir = env::temp_dir();
600 /// dir.push("foo.txt");
602 /// let f = File::create(dir)?;
606 #[stable(feature = "env", since = "1.0.0")]
607 pub fn temp_dir() -> PathBuf {
611 /// Returns the full filesystem path of the current running executable.
613 /// # Platform-specific behavior
615 /// If the executable was invoked through a symbolic link, some platforms will
616 /// return the path of the symbolic link and other platforms will return the
617 /// path of the symbolic link’s target.
621 /// Acquiring the path of the current executable is a platform-specific operation
622 /// that can fail for a good number of reasons. Some errors can include, but not
623 /// be limited to, filesystem operations failing or general syscall failures.
627 /// The output of this function should not be used in anything that might have
628 /// security implications. For example:
632 /// println!("{:?}", std::env::current_exe());
636 /// On Linux systems, if this is compiled as `foo`:
641 /// Ok("/home/alex/foo")
644 /// And you make a hard link of the program:
650 /// When you run it, you won’t get the path of the original executable, you’ll
651 /// get the path of the hard link:
655 /// Ok("/home/alex/bar")
658 /// This sort of behavior has been known to [lead to privilege escalation] when
659 /// used incorrectly.
661 /// [lead to privilege escalation]: https://securityvulns.com/Wdocument183.html
668 /// match env::current_exe() {
669 /// Ok(exe_path) => println!("Path of this executable is: {}",
670 /// exe_path.display()),
671 /// Err(e) => println!("failed to get current exe path: {}", e),
674 #[stable(feature = "env", since = "1.0.0")]
675 pub fn current_exe() -> io::Result<PathBuf> {
676 os_imp::current_exe()
679 /// An iterator over the arguments of a process, yielding a [`String`] value for
682 /// This struct is created by the [`std::env::args`] 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 /// [`String`]: ../string/struct.String.html
690 /// [`std::env::args`]: ./fn.args.html
691 #[stable(feature = "env", since = "1.0.0")]
696 /// An iterator over the arguments of a process, yielding an [`OsString`] value
697 /// for each argument.
699 /// This struct is created by the [`std::env::args_os`] function. See its
700 /// documentation for more.
702 /// The first element is traditionally the path of the executable, but it can be
703 /// set to arbitrary text, and may not even exist. This means this property
704 /// should not be relied upon for security purposes.
706 /// [`OsString`]: ../ffi/struct.OsString.html
707 /// [`std::env::args_os`]: ./fn.args_os.html
708 #[stable(feature = "env", since = "1.0.0")]
710 inner: sys::args::Args,
713 /// Returns the arguments which this program was started with (normally passed
714 /// via the command line).
716 /// The first element is traditionally the path of the executable, but it can be
717 /// set to arbitrary text, and may not even exist. This means this property should
718 /// not be relied upon for security purposes.
720 /// On Unix systems shell usually expands unquoted arguments with glob patterns
721 /// (such as `*` and `?`). On Windows this is not done, and such arguments are
724 /// On glibc Linux, arguments are retrieved by placing a function in .init_array.
725 /// glibc passes argc, argv, and envp to functions in .init_array, as a non-standard extension.
726 /// This allows `std::env::args` to work even in a `cdylib` or `staticlib`, as it does on macOS
731 /// The returned iterator will panic during iteration if any argument to the
732 /// process is not valid unicode. If this is not desired,
733 /// use the [`args_os`] function instead.
740 /// // Prints each argument on a separate line
741 /// for argument in env::args() {
742 /// println!("{}", argument);
746 /// [`args_os`]: ./fn.args_os.html
747 #[stable(feature = "env", since = "1.0.0")]
748 pub fn args() -> Args {
749 Args { inner: args_os() }
752 /// Returns the arguments which this program was started with (normally passed
753 /// via the command line).
755 /// The first element is traditionally the path of the executable, but it can be
756 /// set to arbitrary text, and it may not even exist, so this property should
757 /// not be relied upon for security purposes.
759 /// On glibc Linux, arguments are retrieved by placing a function in .init_array.
760 /// glibc passes argc, argv, and envp to functions in .init_array, as a non-standard extension.
761 /// This allows `std::env::args` to work even in a `cdylib` or `staticlib`, as it does on macOS
769 /// // Prints each argument on a separate line
770 /// for argument in env::args_os() {
771 /// println!("{:?}", argument);
774 #[stable(feature = "env", since = "1.0.0")]
775 pub fn args_os() -> ArgsOs {
776 ArgsOs { inner: sys::args::args() }
779 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
780 impl !Send for Args {}
782 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
783 impl !Sync for Args {}
785 #[stable(feature = "env", since = "1.0.0")]
786 impl Iterator for Args {
788 fn next(&mut self) -> Option<String> {
789 self.inner.next().map(|s| s.into_string().unwrap())
791 fn size_hint(&self) -> (usize, Option<usize>) {
792 self.inner.size_hint()
796 #[stable(feature = "env", since = "1.0.0")]
797 impl ExactSizeIterator for Args {
798 fn len(&self) -> usize {
801 fn is_empty(&self) -> bool {
802 self.inner.is_empty()
806 #[stable(feature = "env_iterators", since = "1.12.0")]
807 impl DoubleEndedIterator for Args {
808 fn next_back(&mut self) -> Option<String> {
809 self.inner.next_back().map(|s| s.into_string().unwrap())
813 #[stable(feature = "std_debug", since = "1.16.0")]
814 impl fmt::Debug for Args {
815 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
816 f.debug_struct("Args").field("inner", &self.inner.inner.inner_debug()).finish()
820 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
821 impl !Send for ArgsOs {}
823 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
824 impl !Sync for ArgsOs {}
826 #[stable(feature = "env", since = "1.0.0")]
827 impl Iterator for ArgsOs {
828 type Item = OsString;
829 fn next(&mut self) -> Option<OsString> {
832 fn size_hint(&self) -> (usize, Option<usize>) {
833 self.inner.size_hint()
837 #[stable(feature = "env", since = "1.0.0")]
838 impl ExactSizeIterator for ArgsOs {
839 fn len(&self) -> usize {
842 fn is_empty(&self) -> bool {
843 self.inner.is_empty()
847 #[stable(feature = "env_iterators", since = "1.12.0")]
848 impl DoubleEndedIterator for ArgsOs {
849 fn next_back(&mut self) -> Option<OsString> {
850 self.inner.next_back()
854 #[stable(feature = "std_debug", since = "1.16.0")]
855 impl fmt::Debug for ArgsOs {
856 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
857 f.debug_struct("ArgsOs").field("inner", &self.inner.inner_debug()).finish()
861 /// Constants associated with the current target
862 #[stable(feature = "env", since = "1.0.0")]
864 use crate::sys::env::os;
866 /// A string describing the architecture of the CPU that is currently
869 /// Some possible values:
881 #[stable(feature = "env", since = "1.0.0")]
882 pub const ARCH: &str = super::arch::ARCH;
884 /// The family of the operating system. Example value is `unix`.
886 /// Some possible values:
890 #[stable(feature = "env", since = "1.0.0")]
891 pub const FAMILY: &str = os::FAMILY;
893 /// A string describing the specific operating system in use.
894 /// Example value is `linux`.
896 /// Some possible values:
908 #[stable(feature = "env", since = "1.0.0")]
909 pub const OS: &str = os::OS;
911 /// Specifies the filename prefix used for shared libraries on this
912 /// platform. Example value is `lib`.
914 /// Some possible values:
917 /// - `""` (an empty string)
918 #[stable(feature = "env", since = "1.0.0")]
919 pub const DLL_PREFIX: &str = os::DLL_PREFIX;
921 /// Specifies the filename suffix used for shared libraries on this
922 /// platform. Example value is `.so`.
924 /// Some possible values:
929 #[stable(feature = "env", since = "1.0.0")]
930 pub const DLL_SUFFIX: &str = os::DLL_SUFFIX;
932 /// Specifies the file extension used for shared libraries on this
933 /// platform that goes after the dot. Example value is `so`.
935 /// Some possible values:
940 #[stable(feature = "env", since = "1.0.0")]
941 pub const DLL_EXTENSION: &str = os::DLL_EXTENSION;
943 /// Specifies the filename suffix used for executable binaries on this
944 /// platform. Example value is `.exe`.
946 /// Some possible values:
951 /// - `""` (an empty string)
952 #[stable(feature = "env", since = "1.0.0")]
953 pub const EXE_SUFFIX: &str = os::EXE_SUFFIX;
955 /// Specifies the file extension, if any, used for executable binaries
956 /// on this platform. Example value is `exe`.
958 /// Some possible values:
961 /// - `""` (an empty string)
962 #[stable(feature = "env", since = "1.0.0")]
963 pub const EXE_EXTENSION: &str = os::EXE_EXTENSION;
966 #[cfg(target_arch = "x86")]
968 pub const ARCH: &str = "x86";
971 #[cfg(target_arch = "x86_64")]
973 pub const ARCH: &str = "x86_64";
976 #[cfg(target_arch = "arm")]
978 pub const ARCH: &str = "arm";
981 #[cfg(target_arch = "aarch64")]
983 pub const ARCH: &str = "aarch64";
986 #[cfg(target_arch = "mips")]
988 pub const ARCH: &str = "mips";
991 #[cfg(target_arch = "mips64")]
993 pub const ARCH: &str = "mips64";
996 #[cfg(target_arch = "powerpc")]
998 pub const ARCH: &str = "powerpc";
1001 #[cfg(target_arch = "powerpc64")]
1003 pub const ARCH: &str = "powerpc64";
1006 #[cfg(target_arch = "s390x")]
1008 pub const ARCH: &str = "s390x";
1011 #[cfg(target_arch = "sparc64")]
1013 pub const ARCH: &str = "sparc64";
1016 #[cfg(target_arch = "le32")]
1018 pub const ARCH: &str = "le32";
1021 #[cfg(target_arch = "asmjs")]
1023 pub const ARCH: &str = "asmjs";
1026 #[cfg(target_arch = "wasm32")]
1028 pub const ARCH: &str = "wasm32";
1031 #[cfg(target_arch = "hexagon")]
1033 pub const ARCH: &'static str = "hexagon";
1040 use crate::path::Path;
1043 #[cfg_attr(any(target_os = "emscripten", target_env = "sgx"), ignore)]
1044 fn test_self_exe_path() {
1045 let path = current_exe();
1046 assert!(path.is_ok());
1047 let path = path.unwrap();
1049 // Hard to test this function
1050 assert!(path.is_absolute());
1055 assert!((!Path::new("test-path").is_absolute()));
1057 #[cfg(not(target_env = "sgx"))]
1058 current_dir().unwrap();
1063 fn split_paths_windows() {
1064 use crate::path::PathBuf;
1066 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1067 split_paths(unparsed).collect::<Vec<_>>()
1068 == parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
1071 assert!(check_parse("", &mut [""]));
1072 assert!(check_parse(r#""""#, &mut [""]));
1073 assert!(check_parse(";;", &mut ["", "", ""]));
1074 assert!(check_parse(r"c:\", &mut [r"c:\"]));
1075 assert!(check_parse(r"c:\;", &mut [r"c:\", ""]));
1076 assert!(check_parse(r"c:\;c:\Program Files\", &mut [r"c:\", r"c:\Program Files\"]));
1077 assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
1078 assert!(check_parse(
1079 r#"c:\;c:\"foo;bar"\;c:\baz"#,
1080 &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]
1086 fn split_paths_unix() {
1087 use crate::path::PathBuf;
1089 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1090 split_paths(unparsed).collect::<Vec<_>>()
1091 == parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
1094 assert!(check_parse("", &mut [""]));
1095 assert!(check_parse("::", &mut ["", "", ""]));
1096 assert!(check_parse("/", &mut ["/"]));
1097 assert!(check_parse("/:", &mut ["/", ""]));
1098 assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
1103 fn join_paths_unix() {
1104 use crate::ffi::OsStr;
1106 fn test_eq(input: &[&str], output: &str) -> bool {
1107 &*join_paths(input.iter().cloned()).unwrap() == OsStr::new(output)
1110 assert!(test_eq(&[], ""));
1111 assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"], "/bin:/usr/bin:/usr/local/bin"));
1112 assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""], ":/bin:::/usr/bin:"));
1113 assert!(join_paths(["/te:st"].iter().cloned()).is_err());
1118 fn join_paths_windows() {
1119 use crate::ffi::OsStr;
1121 fn test_eq(input: &[&str], output: &str) -> bool {
1122 &*join_paths(input.iter().cloned()).unwrap() == OsStr::new(output)
1125 assert!(test_eq(&[], ""));
1126 assert!(test_eq(&[r"c:\windows", r"c:\"], r"c:\windows;c:\"));
1127 assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""], r";c:\windows;;;c:\;"));
1128 assert!(test_eq(&[r"c:\te;st", r"c:\"], r#""c:\te;st";c:\"#));
1129 assert!(join_paths([r#"c:\te"st"#].iter().cloned()).is_err());
1135 format!("Args {{ inner: {:?} }}", args().collect::<Vec<_>>()),
1136 format!("{:?}", args())
1139 format!("ArgsOs {{ inner: {:?} }}", args_os().collect::<Vec<_>>()),
1140 format!("{:?}", args_os())