]> git.lizzy.rs Git - rust.git/blob - src/libstd/env.rs
Rollup merge of #68388 - varkor:toogeneric-wf, r=eddyb
[rust.git] / src / libstd / env.rs
1 //! Inspection and manipulation of the process's environment.
2 //!
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.
6 //!
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`].
10 //!
11 //! [`OsString`]: ../../std/ffi/struct.OsString.html
12 //! [`String`]: ../string/struct.String.html
13
14 #![stable(feature = "env", since = "1.0.0")]
15
16 use crate::error::Error;
17 use crate::ffi::{OsStr, OsString};
18 use crate::fmt;
19 use crate::io;
20 use crate::path::{Path, PathBuf};
21 use crate::sys;
22 use crate::sys::os as os_imp;
23
24 /// Returns the current working directory as a [`PathBuf`].
25 ///
26 /// # Errors
27 ///
28 /// Returns an [`Err`] if the current working directory value is invalid.
29 /// Possible cases:
30 ///
31 /// * Current directory does not exist.
32 /// * There are insufficient permissions to access the current directory.
33 ///
34 /// [`PathBuf`]: ../../std/path/struct.PathBuf.html
35 /// [`Err`]: ../../std/result/enum.Result.html#method.err
36 ///
37 /// # Examples
38 ///
39 /// ```
40 /// use std::env;
41 ///
42 /// fn main() -> std::io::Result<()> {
43 ///     let path = env::current_dir()?;
44 ///     println!("The current directory is {}", path.display());
45 ///     Ok(())
46 /// }
47 /// ```
48 #[stable(feature = "env", since = "1.0.0")]
49 pub fn current_dir() -> io::Result<PathBuf> {
50     os_imp::getcwd()
51 }
52
53 /// Changes the current working directory to the specified path.
54 ///
55 /// Returns an [`Err`] if the operation fails.
56 ///
57 /// [`Err`]: ../../std/result/enum.Result.html#method.err
58 ///
59 /// # Examples
60 ///
61 /// ```
62 /// use std::env;
63 /// use std::path::Path;
64 ///
65 /// let root = Path::new("/");
66 /// assert!(env::set_current_dir(&root).is_ok());
67 /// println!("Successfully changed working directory to {}!", root.display());
68 /// ```
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())
72 }
73
74 /// An iterator over a snapshot of the environment variables of this process.
75 ///
76 /// This structure is created by the [`std::env::vars`] function. See its
77 /// documentation for more.
78 ///
79 /// [`std::env::vars`]: fn.vars.html
80 #[stable(feature = "env", since = "1.0.0")]
81 pub struct Vars {
82     inner: VarsOs,
83 }
84
85 /// An iterator over a snapshot of the environment variables of this process.
86 ///
87 /// This structure is created by the [`std::env::vars_os`] function. See
88 /// its documentation for more.
89 ///
90 /// [`std::env::vars_os`]: fn.vars_os.html
91 #[stable(feature = "env", since = "1.0.0")]
92 pub struct VarsOs {
93     inner: os_imp::Env,
94 }
95
96 /// Returns an iterator of (variable, value) pairs of strings, for all the
97 /// environment variables of the current process.
98 ///
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.
102 ///
103 /// # Panics
104 ///
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.
108 ///
109 /// [`env::vars_os`]: fn.vars_os.html
110 ///
111 /// # Examples
112 ///
113 /// ```
114 /// use std::env;
115 ///
116 /// // We will iterate through the references to the element returned by
117 /// // env::vars();
118 /// for (key, value) in env::vars() {
119 ///     println!("{}: {}", key, value);
120 /// }
121 /// ```
122 #[stable(feature = "env", since = "1.0.0")]
123 pub fn vars() -> Vars {
124     Vars { inner: vars_os() }
125 }
126
127 /// Returns an iterator of (variable, value) pairs of OS strings, for all the
128 /// environment variables of the current process.
129 ///
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.
133 ///
134 /// # Examples
135 ///
136 /// ```
137 /// use std::env;
138 ///
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);
143 /// }
144 /// ```
145 #[stable(feature = "env", since = "1.0.0")]
146 pub fn vars_os() -> VarsOs {
147     VarsOs { inner: os_imp::env() }
148 }
149
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()))
155     }
156     fn size_hint(&self) -> (usize, Option<usize>) {
157         self.inner.size_hint()
158     }
159 }
160
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 {
164         f.pad("Vars { .. }")
165     }
166 }
167
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)> {
172         self.inner.next()
173     }
174     fn size_hint(&self) -> (usize, Option<usize>) {
175         self.inner.size_hint()
176     }
177 }
178
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 { .. }")
183     }
184 }
185
186 /// Fetches the environment variable `key` from the current process.
187 ///
188 /// # Errors
189 ///
190 /// * Environment variable is not present
191 /// * Environment variable is not valid unicode
192 ///
193 /// # Panics
194 ///
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
197 /// character.
198 ///
199 /// # Examples
200 ///
201 /// ```
202 /// use std::env;
203 ///
204 /// let key = "HOME";
205 /// match env::var(key) {
206 ///     Ok(val) => println!("{}: {:?}", key, val),
207 ///     Err(e) => println!("couldn't interpret {}: {}", key, e),
208 /// }
209 /// ```
210 #[stable(feature = "env", since = "1.0.0")]
211 pub fn var<K: AsRef<OsStr>>(key: K) -> Result<String, VarError> {
212     _var(key.as_ref())
213 }
214
215 fn _var(key: &OsStr) -> Result<String, VarError> {
216     match var_os(key) {
217         Some(s) => s.into_string().map_err(VarError::NotUnicode),
218         None => Err(VarError::NotPresent),
219     }
220 }
221
222 /// Fetches the environment variable `key` from the current process, returning
223 /// [`None`] if the variable isn't set.
224 ///
225 /// [`None`]: ../option/enum.Option.html#variant.None
226 ///
227 /// # Panics
228 ///
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
231 /// character.
232 ///
233 /// # Examples
234 ///
235 /// ```
236 /// use std::env;
237 ///
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)
242 /// }
243 /// ```
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())
247 }
248
249 fn _var_os(key: &OsStr) -> Option<OsString> {
250     os_imp::getenv(key)
251         .unwrap_or_else(|e| panic!("failed to get environment variable `{:?}`: {}", key, e))
252 }
253
254 /// The error type for operations interacting with environment variables.
255 /// Possibly returned from the [`env::var`] function.
256 ///
257 /// [`env::var`]: fn.var.html
258 #[derive(Debug, PartialEq, Eq, Clone)]
259 #[stable(feature = "env", since = "1.0.0")]
260 pub enum VarError {
261     /// The specified environment variable was not present in the current
262     /// process's environment.
263     #[stable(feature = "env", since = "1.0.0")]
264     NotPresent,
265
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
268     /// variant.
269     #[stable(feature = "env", since = "1.0.0")]
270     NotUnicode(#[stable(feature = "env", since = "1.0.0")] OsString),
271 }
272
273 #[stable(feature = "env", since = "1.0.0")]
274 impl fmt::Display for VarError {
275     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276         match *self {
277             VarError::NotPresent => write!(f, "environment variable not found"),
278             VarError::NotUnicode(ref s) => {
279                 write!(f, "environment variable was not valid unicode: {:?}", s)
280             }
281         }
282     }
283 }
284
285 #[stable(feature = "env", since = "1.0.0")]
286 impl Error for VarError {
287     #[allow(deprecated)]
288     fn description(&self) -> &str {
289         match *self {
290             VarError::NotPresent => "environment variable not found",
291             VarError::NotUnicode(..) => "environment variable was not valid unicode",
292         }
293     }
294 }
295
296 /// Sets the environment variable `k` to the value `v` for the currently running
297 /// process.
298 ///
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.
304 ///
305 /// Discussion of this unsafety on Unix may be found in:
306 ///
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)
309 ///
310 /// # Panics
311 ///
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
314 /// character.
315 ///
316 /// # Examples
317 ///
318 /// ```
319 /// use std::env;
320 ///
321 /// let key = "KEY";
322 /// env::set_var(key, "VALUE");
323 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
324 /// ```
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())
328 }
329
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)
333     })
334 }
335
336 /// Removes an environment variable from the environment of the currently running process.
337 ///
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.
343 ///
344 /// Discussion of this unsafety on Unix may be found in:
345 ///
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)
348 ///
349 /// # Panics
350 ///
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
353 /// character.
354 ///
355 /// # Examples
356 ///
357 /// ```
358 /// use std::env;
359 ///
360 /// let key = "KEY";
361 /// env::set_var(key, "VALUE");
362 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
363 ///
364 /// env::remove_var(key);
365 /// assert!(env::var(key).is_err());
366 /// ```
367 #[stable(feature = "env", since = "1.0.0")]
368 pub fn remove_var<K: AsRef<OsStr>>(k: K) {
369     _remove_var(k.as_ref())
370 }
371
372 fn _remove_var(k: &OsStr) {
373     os_imp::unsetenv(k)
374         .unwrap_or_else(|e| panic!("failed to remove environment variable `{:?}`: {}", k, e))
375 }
376
377 /// An iterator that splits an environment variable into paths according to
378 /// platform-specific conventions.
379 ///
380 /// The iterator element type is [`PathBuf`].
381 ///
382 /// This structure is created by the [`std::env::split_paths`] function. See its
383 /// documentation for more.
384 ///
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>,
390 }
391
392 /// Parses input according to platform conventions for the `PATH`
393 /// environment variable.
394 ///
395 /// Returns an iterator over the paths contained in `unparsed`. The iterator
396 /// element type is [`PathBuf`].
397 ///
398 /// # Examples
399 ///
400 /// ```
401 /// use std::env;
402 ///
403 /// let key = "PATH";
404 /// match env::var_os(key) {
405 ///     Some(paths) => {
406 ///         for path in env::split_paths(&paths) {
407 ///             println!("'{}'", path.display());
408 ///         }
409 ///     }
410 ///     None => println!("{} is not defined in the environment.", key)
411 /// }
412 /// ```
413 ///
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()) }
418 }
419
420 #[stable(feature = "env", since = "1.0.0")]
421 impl<'a> Iterator for SplitPaths<'a> {
422     type Item = PathBuf;
423     fn next(&mut self) -> Option<PathBuf> {
424         self.inner.next()
425     }
426     fn size_hint(&self) -> (usize, Option<usize>) {
427         self.inner.size_hint()
428     }
429 }
430
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 { .. }")
435     }
436 }
437
438 /// The error type for operations on the `PATH` variable. Possibly returned from
439 /// the [`env::join_paths`] function.
440 ///
441 /// [`env::join_paths`]: fn.join_paths.html
442 #[derive(Debug)]
443 #[stable(feature = "env", since = "1.0.0")]
444 pub struct JoinPathsError {
445     inner: os_imp::JoinPathsError,
446 }
447
448 /// Joins a collection of [`Path`]s appropriately for the `PATH`
449 /// environment variable.
450 ///
451 /// # Errors
452 ///
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).
456 ///
457 /// [`Path`]: ../../std/path/struct.Path.html
458 /// [`OsString`]: ../../std/ffi/struct.OsString.html
459 /// [err]: ../../std/result/enum.Result.html#variant.Err
460 ///
461 /// # Examples
462 ///
463 /// Joining paths on a Unix-like platform:
464 ///
465 /// ```
466 /// use std::env;
467 /// use std::ffi::OsString;
468 /// use std::path::Path;
469 ///
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"));
475 /// # }
476 ///     Ok(())
477 /// }
478 /// ```
479 ///
480 /// Joining a path containing a colon on a Unix-like platform results in an error:
481 ///
482 /// ```
483 /// # if cfg!(unix) {
484 /// use std::env;
485 /// use std::path::Path;
486 ///
487 /// let paths = [Path::new("/bin"), Path::new("/usr/bi:n")];
488 /// assert!(env::join_paths(paths.iter()).is_err());
489 /// # }
490 /// ```
491 ///
492 /// Using `env::join_paths` with [`env::split_paths`] to append an item to the `PATH` environment
493 /// variable:
494 ///
495 /// ```
496 /// use std::env;
497 /// use std::path::PathBuf;
498 ///
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);
505 ///     }
506 ///
507 ///     Ok(())
508 /// }
509 /// ```
510 ///
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>
514 where
515     I: IntoIterator<Item = T>,
516     T: AsRef<OsStr>,
517 {
518     os_imp::join_paths(paths.into_iter()).map_err(|e| JoinPathsError { inner: e })
519 }
520
521 #[stable(feature = "env", since = "1.0.0")]
522 impl fmt::Display for JoinPathsError {
523     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
524         self.inner.fmt(f)
525     }
526 }
527
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()
533     }
534 }
535
536 /// Returns the path of the current user's home directory if known.
537 ///
538 /// # Unix
539 ///
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.
546 ///
547 /// # Windows
548 ///
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.
554 ///
555 /// [msdn]: https://docs.microsoft.com/en-us/windows/win32/api/userenv/nf-userenv-getuserprofiledirectorya
556 ///
557 /// # Examples
558 ///
559 /// ```
560 /// use std::env;
561 ///
562 /// match env::home_dir() {
563 ///     Some(path) => println!("Your home directory, probably: {}", path.display()),
564 ///     None => println!("Impossible to get your home dir!"),
565 /// }
566 /// ```
567 #[rustc_deprecated(
568     since = "1.29.0",
569     reason = "This function's behavior is unexpected and probably not what you want. \
570               Consider using the home_dir function from https://crates.io/crates/dirs instead."
571 )]
572 #[stable(feature = "env", since = "1.0.0")]
573 pub fn home_dir() -> Option<PathBuf> {
574     os_imp::home_dir()
575 }
576
577 /// Returns the path of a temporary directory.
578 ///
579 /// # Unix
580 ///
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`.
585 ///
586 /// # Windows
587 ///
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.
593 ///
594 /// [msdn]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppatha
595 ///
596 /// ```no_run
597 /// use std::env;
598 /// use std::fs::File;
599 ///
600 /// fn main() -> std::io::Result<()> {
601 ///     let mut dir = env::temp_dir();
602 ///     dir.push("foo.txt");
603 ///
604 ///     let f = File::create(dir)?;
605 ///     Ok(())
606 /// }
607 /// ```
608 #[stable(feature = "env", since = "1.0.0")]
609 pub fn temp_dir() -> PathBuf {
610     os_imp::temp_dir()
611 }
612
613 /// Returns the full filesystem path of the current running executable.
614 ///
615 /// # Platform-specific behavior
616 ///
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.
620 ///
621 /// # Errors
622 ///
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.
626 ///
627 /// # Security
628 ///
629 /// The output of this function should not be used in anything that might have
630 /// security implications. For example:
631 ///
632 /// ```
633 /// fn main() {
634 ///     println!("{:?}", std::env::current_exe());
635 /// }
636 /// ```
637 ///
638 /// On Linux systems, if this is compiled as `foo`:
639 ///
640 /// ```bash
641 /// $ rustc foo.rs
642 /// $ ./foo
643 /// Ok("/home/alex/foo")
644 /// ```
645 ///
646 /// And you make a hard link of the program:
647 ///
648 /// ```bash
649 /// $ ln foo bar
650 /// ```
651 ///
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:
654 ///
655 /// ```bash
656 /// $ ./bar
657 /// Ok("/home/alex/bar")
658 /// ```
659 ///
660 /// This sort of behavior has been known to [lead to privilege escalation] when
661 /// used incorrectly.
662 ///
663 /// [lead to privilege escalation]: https://securityvulns.com/Wdocument183.html
664 ///
665 /// # Examples
666 ///
667 /// ```
668 /// use std::env;
669 ///
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),
674 /// };
675 /// ```
676 #[stable(feature = "env", since = "1.0.0")]
677 pub fn current_exe() -> io::Result<PathBuf> {
678     os_imp::current_exe()
679 }
680
681 /// An iterator over the arguments of a process, yielding a [`String`] value for
682 /// each argument.
683 ///
684 /// This struct is created by the [`std::env::args`] function. See its
685 /// documentation for more.
686 ///
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.
690 ///
691 /// [`String`]: ../string/struct.String.html
692 /// [`std::env::args`]: ./fn.args.html
693 #[stable(feature = "env", since = "1.0.0")]
694 pub struct Args {
695     inner: ArgsOs,
696 }
697
698 /// An iterator over the arguments of a process, yielding an [`OsString`] value
699 /// for each argument.
700 ///
701 /// This struct is created by the [`std::env::args_os`] function. See its
702 /// documentation for more.
703 ///
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.
707 ///
708 /// [`OsString`]: ../ffi/struct.OsString.html
709 /// [`std::env::args_os`]: ./fn.args_os.html
710 #[stable(feature = "env", since = "1.0.0")]
711 pub struct ArgsOs {
712     inner: sys::args::Args,
713 }
714
715 /// Returns the arguments which this program was started with (normally passed
716 /// via the command line).
717 ///
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.
721 ///
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
724 /// passed as-is.
725 ///
726 /// On glibc Linux, 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
729 /// and Windows.
730 ///
731 /// # Panics
732 ///
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.
736 ///
737 /// # Examples
738 ///
739 /// ```
740 /// use std::env;
741 ///
742 /// // Prints each argument on a separate line
743 /// for argument in env::args() {
744 ///     println!("{}", argument);
745 /// }
746 /// ```
747 ///
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() }
752 }
753
754 /// Returns the arguments which this program was started with (normally passed
755 /// via the command line).
756 ///
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.
760 ///
761 /// On glibc Linux, 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
764 /// and Windows.
765 ///
766 /// # Examples
767 ///
768 /// ```
769 /// use std::env;
770 ///
771 /// // Prints each argument on a separate line
772 /// for argument in env::args_os() {
773 ///     println!("{:?}", argument);
774 /// }
775 /// ```
776 #[stable(feature = "env", since = "1.0.0")]
777 pub fn args_os() -> ArgsOs {
778     ArgsOs { inner: sys::args::args() }
779 }
780
781 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
782 impl !Send for Args {}
783
784 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
785 impl !Sync for Args {}
786
787 #[stable(feature = "env", since = "1.0.0")]
788 impl Iterator for Args {
789     type Item = String;
790     fn next(&mut self) -> Option<String> {
791         self.inner.next().map(|s| s.into_string().unwrap())
792     }
793     fn size_hint(&self) -> (usize, Option<usize>) {
794         self.inner.size_hint()
795     }
796 }
797
798 #[stable(feature = "env", since = "1.0.0")]
799 impl ExactSizeIterator for Args {
800     fn len(&self) -> usize {
801         self.inner.len()
802     }
803     fn is_empty(&self) -> bool {
804         self.inner.is_empty()
805     }
806 }
807
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())
812     }
813 }
814
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()
819     }
820 }
821
822 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
823 impl !Send for ArgsOs {}
824
825 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
826 impl !Sync for ArgsOs {}
827
828 #[stable(feature = "env", since = "1.0.0")]
829 impl Iterator for ArgsOs {
830     type Item = OsString;
831     fn next(&mut self) -> Option<OsString> {
832         self.inner.next()
833     }
834     fn size_hint(&self) -> (usize, Option<usize>) {
835         self.inner.size_hint()
836     }
837 }
838
839 #[stable(feature = "env", since = "1.0.0")]
840 impl ExactSizeIterator for ArgsOs {
841     fn len(&self) -> usize {
842         self.inner.len()
843     }
844     fn is_empty(&self) -> bool {
845         self.inner.is_empty()
846     }
847 }
848
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()
853     }
854 }
855
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()
860     }
861 }
862
863 /// Constants associated with the current target
864 #[stable(feature = "env", since = "1.0.0")]
865 pub mod consts {
866     use crate::sys::env::os;
867
868     /// A string describing the architecture of the CPU that is currently
869     /// in use.
870     ///
871     /// Some possible values:
872     ///
873     /// - x86
874     /// - x86_64
875     /// - arm
876     /// - aarch64
877     /// - mips
878     /// - mips64
879     /// - powerpc
880     /// - powerpc64
881     /// - riscv64
882     /// - s390x
883     /// - sparc64
884     #[stable(feature = "env", since = "1.0.0")]
885     pub const ARCH: &str = super::arch::ARCH;
886
887     /// The family of the operating system. Example value is `unix`.
888     ///
889     /// Some possible values:
890     ///
891     /// - unix
892     /// - windows
893     #[stable(feature = "env", since = "1.0.0")]
894     pub const FAMILY: &str = os::FAMILY;
895
896     /// A string describing the specific operating system in use.
897     /// Example value is `linux`.
898     ///
899     /// Some possible values:
900     ///
901     /// - linux
902     /// - macos
903     /// - ios
904     /// - freebsd
905     /// - dragonfly
906     /// - netbsd
907     /// - openbsd
908     /// - solaris
909     /// - android
910     /// - windows
911     #[stable(feature = "env", since = "1.0.0")]
912     pub const OS: &str = os::OS;
913
914     /// Specifies the filename prefix used for shared libraries on this
915     /// platform. Example value is `lib`.
916     ///
917     /// Some possible values:
918     ///
919     /// - lib
920     /// - `""` (an empty string)
921     #[stable(feature = "env", since = "1.0.0")]
922     pub const DLL_PREFIX: &str = os::DLL_PREFIX;
923
924     /// Specifies the filename suffix used for shared libraries on this
925     /// platform. Example value is `.so`.
926     ///
927     /// Some possible values:
928     ///
929     /// - .so
930     /// - .dylib
931     /// - .dll
932     #[stable(feature = "env", since = "1.0.0")]
933     pub const DLL_SUFFIX: &str = os::DLL_SUFFIX;
934
935     /// Specifies the file extension used for shared libraries on this
936     /// platform that goes after the dot. Example value is `so`.
937     ///
938     /// Some possible values:
939     ///
940     /// - so
941     /// - dylib
942     /// - dll
943     #[stable(feature = "env", since = "1.0.0")]
944     pub const DLL_EXTENSION: &str = os::DLL_EXTENSION;
945
946     /// Specifies the filename suffix used for executable binaries on this
947     /// platform. Example value is `.exe`.
948     ///
949     /// Some possible values:
950     ///
951     /// - .exe
952     /// - .nexe
953     /// - .pexe
954     /// - `""` (an empty string)
955     #[stable(feature = "env", since = "1.0.0")]
956     pub const EXE_SUFFIX: &str = os::EXE_SUFFIX;
957
958     /// Specifies the file extension, if any, used for executable binaries
959     /// on this platform. Example value is `exe`.
960     ///
961     /// Some possible values:
962     ///
963     /// - exe
964     /// - `""` (an empty string)
965     #[stable(feature = "env", since = "1.0.0")]
966     pub const EXE_EXTENSION: &str = os::EXE_EXTENSION;
967 }
968
969 #[cfg(target_arch = "x86")]
970 mod arch {
971     pub const ARCH: &str = "x86";
972 }
973
974 #[cfg(target_arch = "x86_64")]
975 mod arch {
976     pub const ARCH: &str = "x86_64";
977 }
978
979 #[cfg(target_arch = "arm")]
980 mod arch {
981     pub const ARCH: &str = "arm";
982 }
983
984 #[cfg(target_arch = "aarch64")]
985 mod arch {
986     pub const ARCH: &str = "aarch64";
987 }
988
989 #[cfg(target_arch = "mips")]
990 mod arch {
991     pub const ARCH: &str = "mips";
992 }
993
994 #[cfg(target_arch = "mips64")]
995 mod arch {
996     pub const ARCH: &str = "mips64";
997 }
998
999 #[cfg(target_arch = "powerpc")]
1000 mod arch {
1001     pub const ARCH: &str = "powerpc";
1002 }
1003
1004 #[cfg(target_arch = "powerpc64")]
1005 mod arch {
1006     pub const ARCH: &str = "powerpc64";
1007 }
1008
1009 #[cfg(target_arch = "s390x")]
1010 mod arch {
1011     pub const ARCH: &str = "s390x";
1012 }
1013
1014 #[cfg(target_arch = "sparc64")]
1015 mod arch {
1016     pub const ARCH: &str = "sparc64";
1017 }
1018
1019 #[cfg(target_arch = "le32")]
1020 mod arch {
1021     pub const ARCH: &str = "le32";
1022 }
1023
1024 #[cfg(target_arch = "asmjs")]
1025 mod arch {
1026     pub const ARCH: &str = "asmjs";
1027 }
1028
1029 #[cfg(target_arch = "wasm32")]
1030 mod arch {
1031     pub const ARCH: &str = "wasm32";
1032 }
1033
1034 #[cfg(target_arch = "hexagon")]
1035 mod arch {
1036     pub const ARCH: &'static str = "hexagon";
1037 }
1038
1039 #[cfg(target_arch = "riscv64")]
1040 mod arch {
1041     pub const ARCH: &'static str = "riscv64";
1042 }
1043
1044 #[cfg(test)]
1045 mod tests {
1046     use super::*;
1047
1048     use crate::path::Path;
1049
1050     #[test]
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();
1056
1057         // Hard to test this function
1058         assert!(path.is_absolute());
1059     }
1060
1061     #[test]
1062     fn test() {
1063         assert!((!Path::new("test-path").is_absolute()));
1064
1065         #[cfg(not(target_env = "sgx"))]
1066         current_dir().unwrap();
1067     }
1068
1069     #[test]
1070     #[cfg(windows)]
1071     fn split_paths_windows() {
1072         use crate::path::PathBuf;
1073
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<_>>()
1077         }
1078
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"]
1089         ));
1090     }
1091
1092     #[test]
1093     #[cfg(unix)]
1094     fn split_paths_unix() {
1095         use crate::path::PathBuf;
1096
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<_>>()
1100         }
1101
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"]));
1107     }
1108
1109     #[test]
1110     #[cfg(unix)]
1111     fn join_paths_unix() {
1112         use crate::ffi::OsStr;
1113
1114         fn test_eq(input: &[&str], output: &str) -> bool {
1115             &*join_paths(input.iter().cloned()).unwrap() == OsStr::new(output)
1116         }
1117
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());
1122     }
1123
1124     #[test]
1125     #[cfg(windows)]
1126     fn join_paths_windows() {
1127         use crate::ffi::OsStr;
1128
1129         fn test_eq(input: &[&str], output: &str) -> bool {
1130             &*join_paths(input.iter().cloned()).unwrap() == OsStr::new(output)
1131         }
1132
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());
1138     }
1139
1140     #[test]
1141     fn args_debug() {
1142         assert_eq!(
1143             format!("Args {{ inner: {:?} }}", args().collect::<Vec<_>>()),
1144             format!("{:?}", args())
1145         );
1146         assert_eq!(
1147             format!("ArgsOs {{ inner: {:?} }}", args_os().collect::<Vec<_>>()),
1148             format!("{:?}", args_os())
1149         );
1150     }
1151 }