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 return 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 {
288 fn description(&self) -> &str {
290 VarError::NotPresent => "environment variable not found",
291 VarError::NotUnicode(..) => "environment variable was not valid unicode",
296 /// Sets the environment variable `k` to the value `v` for the currently running
299 /// Note that while concurrent access to environment variables is safe in Rust,
300 /// some platforms only expose inherently unsafe non-threadsafe APIs for
301 /// inspecting the environment. As a result, extra care needs to be taken when
302 /// auditing calls to unsafe external FFI functions to ensure that any external
303 /// environment accesses are properly synchronized with accesses in Rust.
305 /// Discussion of this unsafety on Unix may be found in:
307 /// - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188)
308 /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
312 /// This function may panic if `key` is empty, contains an ASCII equals sign
313 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
322 /// env::set_var(key, "VALUE");
323 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
325 #[stable(feature = "env", since = "1.0.0")]
326 pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(k: K, v: V) {
327 _set_var(k.as_ref(), v.as_ref())
330 fn _set_var(k: &OsStr, v: &OsStr) {
331 os_imp::setenv(k, v).unwrap_or_else(|e| {
332 panic!("failed to set environment variable `{:?}` to `{:?}`: {}", k, v, e)
336 /// Removes an environment variable from the environment of the currently running process.
338 /// Note that while concurrent access to environment variables is safe in Rust,
339 /// some platforms only expose inherently unsafe non-threadsafe APIs for
340 /// inspecting the environment. As a result extra care needs to be taken when
341 /// auditing calls to unsafe external FFI functions to ensure that any external
342 /// environment accesses are properly synchronized with accesses in Rust.
344 /// Discussion of this unsafety on Unix may be found in:
346 /// - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188)
347 /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
351 /// This function may panic if `key` is empty, contains an ASCII equals sign
352 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
361 /// env::set_var(key, "VALUE");
362 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
364 /// env::remove_var(key);
365 /// assert!(env::var(key).is_err());
367 #[stable(feature = "env", since = "1.0.0")]
368 pub fn remove_var<K: AsRef<OsStr>>(k: K) {
369 _remove_var(k.as_ref())
372 fn _remove_var(k: &OsStr) {
374 .unwrap_or_else(|e| panic!("failed to remove environment variable `{:?}`: {}", k, e))
377 /// An iterator that splits an environment variable into paths according to
378 /// platform-specific conventions.
380 /// The iterator element type is [`PathBuf`].
382 /// This structure is created by the [`std::env::split_paths`] function. See its
383 /// documentation for more.
385 /// [`PathBuf`]: ../../std/path/struct.PathBuf.html
386 /// [`std::env::split_paths`]: fn.split_paths.html
387 #[stable(feature = "env", since = "1.0.0")]
388 pub struct SplitPaths<'a> {
389 inner: os_imp::SplitPaths<'a>,
392 /// Parses input according to platform conventions for the `PATH`
393 /// environment variable.
395 /// Returns an iterator over the paths contained in `unparsed`. The iterator
396 /// element type is [`PathBuf`].
403 /// let key = "PATH";
404 /// match env::var_os(key) {
406 /// for path in env::split_paths(&paths) {
407 /// println!("'{}'", path.display());
410 /// None => println!("{} is not defined in the environment.", key)
414 /// [`PathBuf`]: ../../std/path/struct.PathBuf.html
415 #[stable(feature = "env", since = "1.0.0")]
416 pub fn split_paths<T: AsRef<OsStr> + ?Sized>(unparsed: &T) -> SplitPaths<'_> {
417 SplitPaths { inner: os_imp::split_paths(unparsed.as_ref()) }
420 #[stable(feature = "env", since = "1.0.0")]
421 impl<'a> Iterator for SplitPaths<'a> {
423 fn next(&mut self) -> Option<PathBuf> {
426 fn size_hint(&self) -> (usize, Option<usize>) {
427 self.inner.size_hint()
431 #[stable(feature = "std_debug", since = "1.16.0")]
432 impl fmt::Debug for SplitPaths<'_> {
433 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
434 f.pad("SplitPaths { .. }")
438 /// The error type for operations on the `PATH` variable. Possibly returned from
439 /// the [`env::join_paths`] function.
441 /// [`env::join_paths`]: fn.join_paths.html
443 #[stable(feature = "env", since = "1.0.0")]
444 pub struct JoinPathsError {
445 inner: os_imp::JoinPathsError,
448 /// Joins a collection of [`Path`]s appropriately for the `PATH`
449 /// environment variable.
453 /// Returns an [`Err`][err] (containing an error message) if one of the input
454 /// [`Path`]s contains an invalid character for constructing the `PATH`
455 /// variable (a double quote on Windows or a colon on Unix).
457 /// [`Path`]: ../../std/path/struct.Path.html
458 /// [`OsString`]: ../../std/ffi/struct.OsString.html
459 /// [err]: ../../std/result/enum.Result.html#variant.Err
463 /// Joining paths on a Unix-like platform:
467 /// use std::ffi::OsString;
468 /// use std::path::Path;
470 /// fn main() -> Result<(), env::JoinPathsError> {
471 /// # if cfg!(unix) {
472 /// let paths = [Path::new("/bin"), Path::new("/usr/bin")];
473 /// let path_os_string = env::join_paths(paths.iter())?;
474 /// assert_eq!(path_os_string, OsString::from("/bin:/usr/bin"));
480 /// Joining a path containing a colon on a Unix-like platform results in an error:
483 /// # if cfg!(unix) {
485 /// use std::path::Path;
487 /// let paths = [Path::new("/bin"), Path::new("/usr/bi:n")];
488 /// assert!(env::join_paths(paths.iter()).is_err());
492 /// Using `env::join_paths` with [`env::split_paths`] to append an item to the `PATH` environment
497 /// use std::path::PathBuf;
499 /// fn main() -> Result<(), env::JoinPathsError> {
500 /// if let Some(path) = env::var_os("PATH") {
501 /// let mut paths = env::split_paths(&path).collect::<Vec<_>>();
502 /// paths.push(PathBuf::from("/home/xyz/bin"));
503 /// let new_path = env::join_paths(paths)?;
504 /// env::set_var("PATH", &new_path);
511 /// [`env::split_paths`]: fn.split_paths.html
512 #[stable(feature = "env", since = "1.0.0")]
513 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
515 I: IntoIterator<Item = T>,
518 os_imp::join_paths(paths.into_iter()).map_err(|e| JoinPathsError { inner: e })
521 #[stable(feature = "env", since = "1.0.0")]
522 impl fmt::Display for JoinPathsError {
523 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
528 #[stable(feature = "env", since = "1.0.0")]
529 impl Error for JoinPathsError {
530 #[allow(deprecated, deprecated_in_future)]
531 fn description(&self) -> &str {
532 self.inner.description()
536 /// Returns the path of the current user's home directory if known.
540 /// - Returns the value of the 'HOME' environment variable if it is set
541 /// (including to an empty string).
542 /// - Otherwise, it tries to determine the home directory by invoking the `getpwuid_r` function
543 /// using the UID of the current user. An empty home directory field returned from the
544 /// `getpwuid_r` function is considered to be a valid value.
545 /// - Returns `None` if the current user has no entry in the /etc/passwd file.
549 /// - Returns the value of the 'HOME' environment variable if it is set
550 /// (including to an empty string).
551 /// - Otherwise, returns the value of the 'USERPROFILE' environment variable if it is set
552 /// (including to an empty string).
553 /// - If both do not exist, [`GetUserProfileDirectory`][msdn] is used to return the path.
555 /// [msdn]: https://docs.microsoft.com/en-us/windows/win32/api/userenv/nf-userenv-getuserprofiledirectorya
562 /// match env::home_dir() {
563 /// Some(path) => println!("Your home directory, probably: {}", path.display()),
564 /// None => println!("Impossible to get your home dir!"),
569 reason = "This function's behavior is unexpected and probably not what you want. \
570 Consider using a crate from crates.io instead."
572 #[stable(feature = "env", since = "1.0.0")]
573 pub fn home_dir() -> Option<PathBuf> {
577 /// Returns the path of a temporary directory.
581 /// Returns the value of the `TMPDIR` environment variable if it is
582 /// set, otherwise for non-Android it returns `/tmp`. If Android, since there
583 /// is no global temporary folder (it is usually allocated per-app), it returns
584 /// `/data/local/tmp`.
588 /// Returns the value of, in order, the `TMP`, `TEMP`,
589 /// `USERPROFILE` environment variable if any are set and not the empty
590 /// string. Otherwise, `temp_dir` returns the path of the Windows directory.
591 /// This behavior is identical to that of [`GetTempPath`][msdn], which this
592 /// function uses internally.
594 /// [msdn]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppatha
598 /// use std::fs::File;
600 /// fn main() -> std::io::Result<()> {
601 /// let mut dir = env::temp_dir();
602 /// dir.push("foo.txt");
604 /// let f = File::create(dir)?;
608 #[stable(feature = "env", since = "1.0.0")]
609 pub fn temp_dir() -> PathBuf {
613 /// Returns the full filesystem path of the current running executable.
615 /// # Platform-specific behavior
617 /// If the executable was invoked through a symbolic link, some platforms will
618 /// return the path of the symbolic link and other platforms will return the
619 /// path of the symbolic link’s target.
623 /// Acquiring the path of the current executable is a platform-specific operation
624 /// that can fail for a good number of reasons. Some errors can include, but not
625 /// be limited to, filesystem operations failing or general syscall failures.
629 /// The output of this function should not be used in anything that might have
630 /// security implications. For example:
634 /// println!("{:?}", std::env::current_exe());
638 /// On Linux systems, if this is compiled as `foo`:
643 /// Ok("/home/alex/foo")
646 /// And you make a hard link of the program:
652 /// When you run it, you won’t get the path of the original executable, you’ll
653 /// get the path of the hard link:
657 /// Ok("/home/alex/bar")
660 /// This sort of behavior has been known to [lead to privilege escalation] when
661 /// used incorrectly.
663 /// [lead to privilege escalation]: https://securityvulns.com/Wdocument183.html
670 /// match env::current_exe() {
671 /// Ok(exe_path) => println!("Path of this executable is: {}",
672 /// exe_path.display()),
673 /// Err(e) => println!("failed to get current exe path: {}", e),
676 #[stable(feature = "env", since = "1.0.0")]
677 pub fn current_exe() -> io::Result<PathBuf> {
678 os_imp::current_exe()
681 /// An iterator over the arguments of a process, yielding a [`String`] value for
684 /// This struct is created by the [`std::env::args`] function. See its
685 /// documentation for more.
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
689 /// should not be relied upon for security purposes.
691 /// [`String`]: ../string/struct.String.html
692 /// [`std::env::args`]: ./fn.args.html
693 #[stable(feature = "env", since = "1.0.0")]
698 /// An iterator over the arguments of a process, yielding an [`OsString`] value
699 /// for each argument.
701 /// This struct is created by the [`std::env::args_os`] function. See its
702 /// documentation for more.
704 /// The first element is traditionally the path of the executable, but it can be
705 /// set to arbitrary text, and may not even exist. This means this property
706 /// should not be relied upon for security purposes.
708 /// [`OsString`]: ../ffi/struct.OsString.html
709 /// [`std::env::args_os`]: ./fn.args_os.html
710 #[stable(feature = "env", since = "1.0.0")]
712 inner: sys::args::Args,
715 /// Returns the arguments which this program was started with (normally passed
716 /// via the command line).
718 /// The first element is traditionally the path of the executable, but it can be
719 /// set to arbitrary text, and may not even exist. This means this property should
720 /// not be relied upon for security purposes.
722 /// On Unix systems shell usually expands unquoted arguments with glob patterns
723 /// (such as `*` and `?`). On Windows this is not done, and such arguments are
726 /// On glibc Linux systems, arguments are retrieved by placing a function in ".init_array".
727 /// Glibc passes argc, argv, and envp to functions in ".init_array", as a non-standard extension.
728 /// This allows `std::env::args` to work even in a `cdylib` or `staticlib`, as it does on macOS
733 /// The returned iterator will panic during iteration if any argument to the
734 /// process is not valid unicode. If this is not desired,
735 /// use the [`args_os`] function instead.
742 /// // Prints each argument on a separate line
743 /// for argument in env::args() {
744 /// println!("{}", argument);
748 /// [`args_os`]: ./fn.args_os.html
749 #[stable(feature = "env", since = "1.0.0")]
750 pub fn args() -> Args {
751 Args { inner: args_os() }
754 /// Returns the arguments which this program was started with (normally passed
755 /// via the command line).
757 /// The first element is traditionally the path of the executable, but it can be
758 /// set to arbitrary text, and it may not even exist, so this property should
759 /// not be relied upon for security purposes.
761 /// On glibc Linux systems, arguments are retrieved by placing a function in ".init_array".
762 /// Glibc passes argc, argv, and envp to functions in ".init_array", as a non-standard extension.
763 /// This allows `std::env::args` to work even in a `cdylib` or `staticlib`, as it does on macOS
771 /// // Prints each argument on a separate line
772 /// for argument in env::args_os() {
773 /// println!("{:?}", argument);
776 #[stable(feature = "env", since = "1.0.0")]
777 pub fn args_os() -> ArgsOs {
778 ArgsOs { inner: sys::args::args() }
781 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
782 impl !Send for Args {}
784 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
785 impl !Sync for Args {}
787 #[stable(feature = "env", since = "1.0.0")]
788 impl Iterator for Args {
790 fn next(&mut self) -> Option<String> {
791 self.inner.next().map(|s| s.into_string().unwrap())
793 fn size_hint(&self) -> (usize, Option<usize>) {
794 self.inner.size_hint()
798 #[stable(feature = "env", since = "1.0.0")]
799 impl ExactSizeIterator for Args {
800 fn len(&self) -> usize {
803 fn is_empty(&self) -> bool {
804 self.inner.is_empty()
808 #[stable(feature = "env_iterators", since = "1.12.0")]
809 impl DoubleEndedIterator for Args {
810 fn next_back(&mut self) -> Option<String> {
811 self.inner.next_back().map(|s| s.into_string().unwrap())
815 #[stable(feature = "std_debug", since = "1.16.0")]
816 impl fmt::Debug for Args {
817 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
818 f.debug_struct("Args").field("inner", &self.inner.inner.inner_debug()).finish()
822 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
823 impl !Send for ArgsOs {}
825 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
826 impl !Sync for ArgsOs {}
828 #[stable(feature = "env", since = "1.0.0")]
829 impl Iterator for ArgsOs {
830 type Item = OsString;
831 fn next(&mut self) -> Option<OsString> {
834 fn size_hint(&self) -> (usize, Option<usize>) {
835 self.inner.size_hint()
839 #[stable(feature = "env", since = "1.0.0")]
840 impl ExactSizeIterator for ArgsOs {
841 fn len(&self) -> usize {
844 fn is_empty(&self) -> bool {
845 self.inner.is_empty()
849 #[stable(feature = "env_iterators", since = "1.12.0")]
850 impl DoubleEndedIterator for ArgsOs {
851 fn next_back(&mut self) -> Option<OsString> {
852 self.inner.next_back()
856 #[stable(feature = "std_debug", since = "1.16.0")]
857 impl fmt::Debug for ArgsOs {
858 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
859 f.debug_struct("ArgsOs").field("inner", &self.inner.inner_debug()).finish()
863 /// Constants associated with the current target
864 #[stable(feature = "env", since = "1.0.0")]
866 use crate::sys::env::os;
868 /// A string describing the architecture of the CPU that is currently
871 /// Some possible values:
884 #[stable(feature = "env", since = "1.0.0")]
885 pub const ARCH: &str = super::arch::ARCH;
887 /// The family of the operating system. Example value is `unix`.
889 /// Some possible values:
893 #[stable(feature = "env", since = "1.0.0")]
894 pub const FAMILY: &str = os::FAMILY;
896 /// A string describing the specific operating system in use.
897 /// Example value is `linux`.
899 /// Some possible values:
911 #[stable(feature = "env", since = "1.0.0")]
912 pub const OS: &str = os::OS;
914 /// Specifies the filename prefix used for shared libraries on this
915 /// platform. Example value is `lib`.
917 /// Some possible values:
920 /// - `""` (an empty string)
921 #[stable(feature = "env", since = "1.0.0")]
922 pub const DLL_PREFIX: &str = os::DLL_PREFIX;
924 /// Specifies the filename suffix used for shared libraries on this
925 /// platform. Example value is `.so`.
927 /// Some possible values:
932 #[stable(feature = "env", since = "1.0.0")]
933 pub const DLL_SUFFIX: &str = os::DLL_SUFFIX;
935 /// Specifies the file extension used for shared libraries on this
936 /// platform that goes after the dot. Example value is `so`.
938 /// Some possible values:
943 #[stable(feature = "env", since = "1.0.0")]
944 pub const DLL_EXTENSION: &str = os::DLL_EXTENSION;
946 /// Specifies the filename suffix used for executable binaries on this
947 /// platform. Example value is `.exe`.
949 /// Some possible values:
954 /// - `""` (an empty string)
955 #[stable(feature = "env", since = "1.0.0")]
956 pub const EXE_SUFFIX: &str = os::EXE_SUFFIX;
958 /// Specifies the file extension, if any, used for executable binaries
959 /// on this platform. Example value is `exe`.
961 /// Some possible values:
964 /// - `""` (an empty string)
965 #[stable(feature = "env", since = "1.0.0")]
966 pub const EXE_EXTENSION: &str = os::EXE_EXTENSION;
969 #[cfg(target_arch = "x86")]
971 pub const ARCH: &str = "x86";
974 #[cfg(target_arch = "x86_64")]
976 pub const ARCH: &str = "x86_64";
979 #[cfg(target_arch = "arm")]
981 pub const ARCH: &str = "arm";
984 #[cfg(target_arch = "aarch64")]
986 pub const ARCH: &str = "aarch64";
989 #[cfg(target_arch = "mips")]
991 pub const ARCH: &str = "mips";
994 #[cfg(target_arch = "mips64")]
996 pub const ARCH: &str = "mips64";
999 #[cfg(target_arch = "powerpc")]
1001 pub const ARCH: &str = "powerpc";
1004 #[cfg(target_arch = "powerpc64")]
1006 pub const ARCH: &str = "powerpc64";
1009 #[cfg(target_arch = "s390x")]
1011 pub const ARCH: &str = "s390x";
1014 #[cfg(target_arch = "sparc64")]
1016 pub const ARCH: &str = "sparc64";
1019 #[cfg(target_arch = "le32")]
1021 pub const ARCH: &str = "le32";
1024 #[cfg(target_arch = "asmjs")]
1026 pub const ARCH: &str = "asmjs";
1029 #[cfg(target_arch = "wasm32")]
1031 pub const ARCH: &str = "wasm32";
1034 #[cfg(target_arch = "hexagon")]
1036 pub const ARCH: &'static str = "hexagon";
1039 #[cfg(target_arch = "riscv64")]
1041 pub const ARCH: &'static str = "riscv64";
1048 use crate::path::Path;
1051 #[cfg_attr(any(target_os = "emscripten", target_env = "sgx"), ignore)]
1052 fn test_self_exe_path() {
1053 let path = current_exe();
1054 assert!(path.is_ok());
1055 let path = path.unwrap();
1057 // Hard to test this function
1058 assert!(path.is_absolute());
1063 assert!((!Path::new("test-path").is_absolute()));
1065 #[cfg(not(target_env = "sgx"))]
1066 current_dir().unwrap();
1071 fn split_paths_windows() {
1072 use crate::path::PathBuf;
1074 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1075 split_paths(unparsed).collect::<Vec<_>>()
1076 == parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
1079 assert!(check_parse("", &mut [""]));
1080 assert!(check_parse(r#""""#, &mut [""]));
1081 assert!(check_parse(";;", &mut ["", "", ""]));
1082 assert!(check_parse(r"c:\", &mut [r"c:\"]));
1083 assert!(check_parse(r"c:\;", &mut [r"c:\", ""]));
1084 assert!(check_parse(r"c:\;c:\Program Files\", &mut [r"c:\", r"c:\Program Files\"]));
1085 assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
1086 assert!(check_parse(
1087 r#"c:\;c:\"foo;bar"\;c:\baz"#,
1088 &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]
1094 fn split_paths_unix() {
1095 use crate::path::PathBuf;
1097 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1098 split_paths(unparsed).collect::<Vec<_>>()
1099 == parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
1102 assert!(check_parse("", &mut [""]));
1103 assert!(check_parse("::", &mut ["", "", ""]));
1104 assert!(check_parse("/", &mut ["/"]));
1105 assert!(check_parse("/:", &mut ["/", ""]));
1106 assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
1111 fn join_paths_unix() {
1112 use crate::ffi::OsStr;
1114 fn test_eq(input: &[&str], output: &str) -> bool {
1115 &*join_paths(input.iter().cloned()).unwrap() == OsStr::new(output)
1118 assert!(test_eq(&[], ""));
1119 assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"], "/bin:/usr/bin:/usr/local/bin"));
1120 assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""], ":/bin:::/usr/bin:"));
1121 assert!(join_paths(["/te:st"].iter().cloned()).is_err());
1126 fn join_paths_windows() {
1127 use crate::ffi::OsStr;
1129 fn test_eq(input: &[&str], output: &str) -> bool {
1130 &*join_paths(input.iter().cloned()).unwrap() == OsStr::new(output)
1133 assert!(test_eq(&[], ""));
1134 assert!(test_eq(&[r"c:\windows", r"c:\"], r"c:\windows;c:\"));
1135 assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""], r";c:\windows;;;c:\;"));
1136 assert!(test_eq(&[r"c:\te;st", r"c:\"], r#""c:\te;st";c:\"#));
1137 assert!(join_paths([r#"c:\te"st"#].iter().cloned()).is_err());
1143 format!("Args {{ inner: {:?} }}", args().collect::<Vec<_>>()),
1144 format!("{:?}", args())
1147 format!("ArgsOs {{ inner: {:?} }}", args_os().collect::<Vec<_>>()),
1148 format!("{:?}", args_os())