]> git.lizzy.rs Git - rust.git/blob - library/std/src/env.rs
Rollup merge of #86673 - m-ou-se:disjoint-capture-edition-lint, r=nikomatsakis
[rust.git] / library / std / src / 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 #![stable(feature = "env", since = "1.0.0")]
12
13 #[cfg(test)]
14 mod tests;
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 /// # Examples
35 ///
36 /// ```
37 /// use std::env;
38 ///
39 /// fn main() -> std::io::Result<()> {
40 ///     let path = env::current_dir()?;
41 ///     println!("The current directory is {}", path.display());
42 ///     Ok(())
43 /// }
44 /// ```
45 #[stable(feature = "env", since = "1.0.0")]
46 pub fn current_dir() -> io::Result<PathBuf> {
47     os_imp::getcwd()
48 }
49
50 /// Changes the current working directory to the specified path.
51 ///
52 /// Returns an [`Err`] if the operation fails.
53 ///
54 /// # Examples
55 ///
56 /// ```
57 /// use std::env;
58 /// use std::path::Path;
59 ///
60 /// let root = Path::new("/");
61 /// assert!(env::set_current_dir(&root).is_ok());
62 /// println!("Successfully changed working directory to {}!", root.display());
63 /// ```
64 #[doc(alias = "chdir")]
65 #[stable(feature = "env", since = "1.0.0")]
66 pub fn set_current_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
67     os_imp::chdir(path.as_ref())
68 }
69
70 /// An iterator over a snapshot of the environment variables of this process.
71 ///
72 /// This structure is created by [`env::vars()`]. See its documentation for more.
73 ///
74 /// [`env::vars()`]: vars
75 #[stable(feature = "env", since = "1.0.0")]
76 pub struct Vars {
77     inner: VarsOs,
78 }
79
80 /// An iterator over a snapshot of the environment variables of this process.
81 ///
82 /// This structure is created by [`env::vars_os()`]. See its documentation for more.
83 ///
84 /// [`env::vars_os()`]: vars_os
85 #[stable(feature = "env", since = "1.0.0")]
86 pub struct VarsOs {
87     inner: os_imp::Env,
88 }
89
90 /// Returns an iterator of (variable, value) pairs of strings, for all the
91 /// environment variables of the current process.
92 ///
93 /// The returned iterator contains a snapshot of the process's environment
94 /// variables at the time of this invocation. Modifications to environment
95 /// variables afterwards will not be reflected in the returned iterator.
96 ///
97 /// # Panics
98 ///
99 /// While iterating, the returned iterator will panic if any key or value in the
100 /// environment is not valid unicode. If this is not desired, consider using
101 /// [`env::vars_os()`].
102 ///
103 /// # Examples
104 ///
105 /// ```
106 /// use std::env;
107 ///
108 /// // We will iterate through the references to the element returned by
109 /// // env::vars();
110 /// for (key, value) in env::vars() {
111 ///     println!("{}: {}", key, value);
112 /// }
113 /// ```
114 ///
115 /// [`env::vars_os()`]: vars_os
116 #[stable(feature = "env", since = "1.0.0")]
117 pub fn vars() -> Vars {
118     Vars { inner: vars_os() }
119 }
120
121 /// Returns an iterator of (variable, value) pairs of OS strings, for all the
122 /// environment variables of the current process.
123 ///
124 /// The returned iterator contains a snapshot of the process's environment
125 /// variables at the time of this invocation. Modifications to environment
126 /// variables afterwards will not be reflected in the returned iterator.
127 ///
128 /// Note that the returned iterator will not check if the environment variables
129 /// are valid Unicode. If you want to panic on invalid UTF-8,
130 /// use the [`vars`] function instead.
131 ///
132 /// # Examples
133 ///
134 /// ```
135 /// use std::env;
136 ///
137 /// // We will iterate through the references to the element returned by
138 /// // env::vars_os();
139 /// for (key, value) in env::vars_os() {
140 ///     println!("{:?}: {:?}", key, value);
141 /// }
142 /// ```
143 #[stable(feature = "env", since = "1.0.0")]
144 pub fn vars_os() -> VarsOs {
145     VarsOs { inner: os_imp::env() }
146 }
147
148 #[stable(feature = "env", since = "1.0.0")]
149 impl Iterator for Vars {
150     type Item = (String, String);
151     fn next(&mut self) -> Option<(String, String)> {
152         self.inner.next().map(|(a, b)| (a.into_string().unwrap(), b.into_string().unwrap()))
153     }
154     fn size_hint(&self) -> (usize, Option<usize>) {
155         self.inner.size_hint()
156     }
157 }
158
159 #[stable(feature = "std_debug", since = "1.16.0")]
160 impl fmt::Debug for Vars {
161     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162         f.debug_struct("Vars").finish_non_exhaustive()
163     }
164 }
165
166 #[stable(feature = "env", since = "1.0.0")]
167 impl Iterator for VarsOs {
168     type Item = (OsString, OsString);
169     fn next(&mut self) -> Option<(OsString, OsString)> {
170         self.inner.next()
171     }
172     fn size_hint(&self) -> (usize, Option<usize>) {
173         self.inner.size_hint()
174     }
175 }
176
177 #[stable(feature = "std_debug", since = "1.16.0")]
178 impl fmt::Debug for VarsOs {
179     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180         f.debug_struct("VarOs").finish_non_exhaustive()
181     }
182 }
183
184 /// Fetches the environment variable `key` from the current process.
185 ///
186 /// # Errors
187 ///
188 /// Errors if the environment variable is not present.
189 /// Errors if the environment variable is not valid Unicode. If this is not desired, consider using
190 /// [`var_os`].
191 ///
192 /// # Panics
193 ///
194 /// This function may panic if `key` is empty, contains an ASCII equals sign
195 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
196 /// character.
197 ///
198 /// # Examples
199 ///
200 /// ```
201 /// use std::env;
202 ///
203 /// let key = "HOME";
204 /// match env::var(key) {
205 ///     Ok(val) => println!("{}: {:?}", key, val),
206 ///     Err(e) => println!("couldn't interpret {}: {}", key, e),
207 /// }
208 /// ```
209 #[stable(feature = "env", since = "1.0.0")]
210 pub fn var<K: AsRef<OsStr>>(key: K) -> Result<String, VarError> {
211     _var(key.as_ref())
212 }
213
214 fn _var(key: &OsStr) -> Result<String, VarError> {
215     match var_os(key) {
216         Some(s) => s.into_string().map_err(VarError::NotUnicode),
217         None => Err(VarError::NotPresent),
218     }
219 }
220
221 /// Fetches the environment variable `key` from the current process, returning
222 /// [`None`] if the variable isn't set.
223 ///
224 /// # Panics
225 ///
226 /// This function may panic if `key` is empty, contains an ASCII equals sign
227 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
228 /// character.
229 ///
230 /// Note that the method will not check if the environment variable
231 /// is valid Unicode. If you want to have an error on invalid UTF-8,
232 /// use the [`var`] function instead.
233 ///
234 /// # Examples
235 ///
236 /// ```
237 /// use std::env;
238 ///
239 /// let key = "HOME";
240 /// match env::var_os(key) {
241 ///     Some(val) => println!("{}: {:?}", key, val),
242 ///     None => println!("{} is not defined in the environment.", key)
243 /// }
244 /// ```
245 #[stable(feature = "env", since = "1.0.0")]
246 pub fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> {
247     _var_os(key.as_ref())
248 }
249
250 fn _var_os(key: &OsStr) -> Option<OsString> {
251     os_imp::getenv(key)
252         .unwrap_or_else(|e| panic!("failed to get environment variable `{:?}`: {}", key, e))
253 }
254
255 /// The error type for operations interacting with environment variables.
256 /// Possibly returned from [`env::var()`].
257 ///
258 /// [`env::var()`]: var
259 #[derive(Debug, PartialEq, Eq, Clone)]
260 #[stable(feature = "env", since = "1.0.0")]
261 pub enum VarError {
262     /// The specified environment variable was not present in the current
263     /// process's environment.
264     #[stable(feature = "env", since = "1.0.0")]
265     NotPresent,
266
267     /// The specified environment variable was found, but it did not contain
268     /// valid unicode data. The found data is returned as a payload of this
269     /// variant.
270     #[stable(feature = "env", since = "1.0.0")]
271     NotUnicode(#[stable(feature = "env", since = "1.0.0")] OsString),
272 }
273
274 #[stable(feature = "env", since = "1.0.0")]
275 impl fmt::Display for VarError {
276     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
277         match *self {
278             VarError::NotPresent => write!(f, "environment variable not found"),
279             VarError::NotUnicode(ref s) => {
280                 write!(f, "environment variable was not valid unicode: {:?}", s)
281             }
282         }
283     }
284 }
285
286 #[stable(feature = "env", since = "1.0.0")]
287 impl Error for VarError {
288     #[allow(deprecated)]
289     fn description(&self) -> &str {
290         match *self {
291             VarError::NotPresent => "environment variable not found",
292             VarError::NotUnicode(..) => "environment variable was not valid unicode",
293         }
294     }
295 }
296
297 /// Sets the environment variable `k` to the value `v` for the currently running
298 /// process.
299 ///
300 /// Note that while concurrent access to environment variables is safe in Rust,
301 /// some platforms only expose inherently unsafe non-threadsafe APIs for
302 /// inspecting the environment. As a result, extra care needs to be taken when
303 /// auditing calls to unsafe external FFI functions to ensure that any external
304 /// environment accesses are properly synchronized with accesses in Rust.
305 ///
306 /// Discussion of this unsafety on Unix may be found in:
307 ///
308 ///  - [Austin Group Bugzilla](https://austingroupbugs.net/view.php?id=188)
309 ///  - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
310 ///
311 /// # Panics
312 ///
313 /// This function may panic if `key` is empty, contains an ASCII equals sign
314 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
315 /// character.
316 ///
317 /// # Examples
318 ///
319 /// ```
320 /// use std::env;
321 ///
322 /// let key = "KEY";
323 /// env::set_var(key, "VALUE");
324 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
325 /// ```
326 #[stable(feature = "env", since = "1.0.0")]
327 pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(key: K, value: V) {
328     _set_var(key.as_ref(), value.as_ref())
329 }
330
331 fn _set_var(key: &OsStr, value: &OsStr) {
332     os_imp::setenv(key, value).unwrap_or_else(|e| {
333         panic!("failed to set environment variable `{:?}` to `{:?}`: {}", key, value, e)
334     })
335 }
336
337 /// Removes an environment variable from the environment of the currently running process.
338 ///
339 /// Note that while concurrent access to environment variables is safe in Rust,
340 /// some platforms only expose inherently unsafe non-threadsafe APIs for
341 /// inspecting the environment. As a result extra care needs to be taken when
342 /// auditing calls to unsafe external FFI functions to ensure that any external
343 /// environment accesses are properly synchronized with accesses in Rust.
344 ///
345 /// Discussion of this unsafety on Unix may be found in:
346 ///
347 ///  - [Austin Group Bugzilla](https://austingroupbugs.net/view.php?id=188)
348 ///  - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
349 ///
350 /// # Panics
351 ///
352 /// This function may panic if `key` is empty, contains an ASCII equals sign
353 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
354 /// character.
355 ///
356 /// # Examples
357 ///
358 /// ```
359 /// use std::env;
360 ///
361 /// let key = "KEY";
362 /// env::set_var(key, "VALUE");
363 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
364 ///
365 /// env::remove_var(key);
366 /// assert!(env::var(key).is_err());
367 /// ```
368 #[stable(feature = "env", since = "1.0.0")]
369 pub fn remove_var<K: AsRef<OsStr>>(key: K) {
370     _remove_var(key.as_ref())
371 }
372
373 fn _remove_var(key: &OsStr) {
374     os_imp::unsetenv(key)
375         .unwrap_or_else(|e| panic!("failed to remove environment variable `{:?}`: {}", key, e))
376 }
377
378 /// An iterator that splits an environment variable into paths according to
379 /// platform-specific conventions.
380 ///
381 /// The iterator element type is [`PathBuf`].
382 ///
383 /// This structure is created by [`env::split_paths()`]. See its
384 /// documentation for more.
385 ///
386 /// [`env::split_paths()`]: split_paths
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 #[stable(feature = "env", since = "1.0.0")]
414 pub fn split_paths<T: AsRef<OsStr> + ?Sized>(unparsed: &T) -> SplitPaths<'_> {
415     SplitPaths { inner: os_imp::split_paths(unparsed.as_ref()) }
416 }
417
418 #[stable(feature = "env", since = "1.0.0")]
419 impl<'a> Iterator for SplitPaths<'a> {
420     type Item = PathBuf;
421     fn next(&mut self) -> Option<PathBuf> {
422         self.inner.next()
423     }
424     fn size_hint(&self) -> (usize, Option<usize>) {
425         self.inner.size_hint()
426     }
427 }
428
429 #[stable(feature = "std_debug", since = "1.16.0")]
430 impl fmt::Debug for SplitPaths<'_> {
431     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
432         f.debug_struct("SplitPaths").finish_non_exhaustive()
433     }
434 }
435
436 /// The error type for operations on the `PATH` variable. Possibly returned from
437 /// [`env::join_paths()`].
438 ///
439 /// [`env::join_paths()`]: join_paths
440 #[derive(Debug)]
441 #[stable(feature = "env", since = "1.0.0")]
442 pub struct JoinPathsError {
443     inner: os_imp::JoinPathsError,
444 }
445
446 /// Joins a collection of [`Path`]s appropriately for the `PATH`
447 /// environment variable.
448 ///
449 /// # Errors
450 ///
451 /// Returns an [`Err`] (containing an error message) if one of the input
452 /// [`Path`]s contains an invalid character for constructing the `PATH`
453 /// variable (a double quote on Windows or a colon on Unix).
454 ///
455 /// # Examples
456 ///
457 /// Joining paths on a Unix-like platform:
458 ///
459 /// ```
460 /// use std::env;
461 /// use std::ffi::OsString;
462 /// use std::path::Path;
463 ///
464 /// fn main() -> Result<(), env::JoinPathsError> {
465 /// # if cfg!(unix) {
466 ///     let paths = [Path::new("/bin"), Path::new("/usr/bin")];
467 ///     let path_os_string = env::join_paths(paths.iter())?;
468 ///     assert_eq!(path_os_string, OsString::from("/bin:/usr/bin"));
469 /// # }
470 ///     Ok(())
471 /// }
472 /// ```
473 ///
474 /// Joining a path containing a colon on a Unix-like platform results in an
475 /// error:
476 ///
477 /// ```
478 /// # if cfg!(unix) {
479 /// use std::env;
480 /// use std::path::Path;
481 ///
482 /// let paths = [Path::new("/bin"), Path::new("/usr/bi:n")];
483 /// assert!(env::join_paths(paths.iter()).is_err());
484 /// # }
485 /// ```
486 ///
487 /// Using `env::join_paths()` with [`env::split_paths()`] to append an item to
488 /// the `PATH` environment variable:
489 ///
490 /// ```
491 /// use std::env;
492 /// use std::path::PathBuf;
493 ///
494 /// fn main() -> Result<(), env::JoinPathsError> {
495 ///     if let Some(path) = env::var_os("PATH") {
496 ///         let mut paths = env::split_paths(&path).collect::<Vec<_>>();
497 ///         paths.push(PathBuf::from("/home/xyz/bin"));
498 ///         let new_path = env::join_paths(paths)?;
499 ///         env::set_var("PATH", &new_path);
500 ///     }
501 ///
502 ///     Ok(())
503 /// }
504 /// ```
505 ///
506 /// [`env::split_paths()`]: split_paths
507 #[stable(feature = "env", since = "1.0.0")]
508 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
509 where
510     I: IntoIterator<Item = T>,
511     T: AsRef<OsStr>,
512 {
513     os_imp::join_paths(paths.into_iter()).map_err(|e| JoinPathsError { inner: e })
514 }
515
516 #[stable(feature = "env", since = "1.0.0")]
517 impl fmt::Display for JoinPathsError {
518     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
519         self.inner.fmt(f)
520     }
521 }
522
523 #[stable(feature = "env", since = "1.0.0")]
524 impl Error for JoinPathsError {
525     #[allow(deprecated, deprecated_in_future)]
526     fn description(&self) -> &str {
527         self.inner.description()
528     }
529 }
530
531 /// Returns the path of the current user's home directory if known.
532 ///
533 /// # Unix
534 ///
535 /// - Returns the value of the 'HOME' environment variable if it is set
536 ///   (including to an empty string).
537 /// - Otherwise, it tries to determine the home directory by invoking the `getpwuid_r` function
538 ///   using the UID of the current user. An empty home directory field returned from the
539 ///   `getpwuid_r` function is considered to be a valid value.
540 /// - Returns `None` if the current user has no entry in the /etc/passwd file.
541 ///
542 /// # Windows
543 ///
544 /// - Returns the value of the 'HOME' environment variable if it is set
545 ///   (including to an empty string).
546 /// - Otherwise, returns the value of the 'USERPROFILE' environment variable if it is set
547 ///   (including to an empty string).
548 /// - If both do not exist, [`GetUserProfileDirectory`][msdn] is used to return the path.
549 ///
550 /// [msdn]: https://docs.microsoft.com/en-us/windows/win32/api/userenv/nf-userenv-getuserprofiledirectorya
551 ///
552 /// # Examples
553 ///
554 /// ```
555 /// use std::env;
556 ///
557 /// match env::home_dir() {
558 ///     Some(path) => println!("Your home directory, probably: {}", path.display()),
559 ///     None => println!("Impossible to get your home dir!"),
560 /// }
561 /// ```
562 #[rustc_deprecated(
563     since = "1.29.0",
564     reason = "This function's behavior is unexpected and probably not what you want. \
565               Consider using a crate from crates.io instead."
566 )]
567 #[stable(feature = "env", since = "1.0.0")]
568 pub fn home_dir() -> Option<PathBuf> {
569     os_imp::home_dir()
570 }
571
572 /// Returns the path of a temporary directory.
573 ///
574 /// The temporary directory may be shared among users, or between processes
575 /// with different privileges; thus, the creation of any files or directories
576 /// in the temporary directory must use a secure method to create a uniquely
577 /// named file. Creating a file or directory with a fixed or predictable name
578 /// may result in "insecure temporary file" security vulnerabilities. Consider
579 /// using a crate that securely creates temporary files or directories.
580 ///
581 /// # Unix
582 ///
583 /// Returns the value of the `TMPDIR` environment variable if it is
584 /// set, otherwise for non-Android it returns `/tmp`. If Android, since there
585 /// is no global temporary folder (it is usually allocated per-app), it returns
586 /// `/data/local/tmp`.
587 ///
588 /// # Windows
589 ///
590 /// Returns the value of, in order, the `TMP`, `TEMP`,
591 /// `USERPROFILE` environment variable if any are set and not the empty
592 /// string. Otherwise, `temp_dir` returns the path of the Windows directory.
593 /// This behavior is identical to that of [`GetTempPath`][msdn], which this
594 /// function uses internally.
595 ///
596 /// [msdn]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppatha
597 ///
598 /// ```no_run
599 /// use std::env;
600 ///
601 /// fn main() {
602 ///     let mut dir = env::temp_dir();
603 ///     println!("Temporary directory: {}", dir.display());
604 /// }
605 /// ```
606 #[stable(feature = "env", since = "1.0.0")]
607 pub fn temp_dir() -> PathBuf {
608     os_imp::temp_dir()
609 }
610
611 /// Returns the full filesystem path of the current running executable.
612 ///
613 /// # Platform-specific behavior
614 ///
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.
618 ///
619 /// # Errors
620 ///
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.
624 ///
625 /// # Security
626 ///
627 /// The output of this function should not be used in anything that might have
628 /// security implications. For example:
629 ///
630 /// ```
631 /// fn main() {
632 ///     println!("{:?}", std::env::current_exe());
633 /// }
634 /// ```
635 ///
636 /// On Linux systems, if this is compiled as `foo`:
637 ///
638 /// ```bash
639 /// $ rustc foo.rs
640 /// $ ./foo
641 /// Ok("/home/alex/foo")
642 /// ```
643 ///
644 /// And you make a hard link of the program:
645 ///
646 /// ```bash
647 /// $ ln foo bar
648 /// ```
649 ///
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:
652 ///
653 /// ```bash
654 /// $ ./bar
655 /// Ok("/home/alex/bar")
656 /// ```
657 ///
658 /// This sort of behavior has been known to [lead to privilege escalation] when
659 /// used incorrectly.
660 ///
661 /// [lead to privilege escalation]: https://securityvulns.com/Wdocument183.html
662 ///
663 /// # Examples
664 ///
665 /// ```
666 /// use std::env;
667 ///
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),
672 /// };
673 /// ```
674 #[stable(feature = "env", since = "1.0.0")]
675 pub fn current_exe() -> io::Result<PathBuf> {
676     os_imp::current_exe()
677 }
678
679 /// An iterator over the arguments of a process, yielding a [`String`] value for
680 /// each argument.
681 ///
682 /// This struct is created by [`env::args()`]. See its documentation
683 /// for more.
684 ///
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.
688 ///
689 /// [`env::args()`]: args
690 #[stable(feature = "env", since = "1.0.0")]
691 pub struct Args {
692     inner: ArgsOs,
693 }
694
695 /// An iterator over the arguments of a process, yielding an [`OsString`] value
696 /// for each argument.
697 ///
698 /// This struct is created by [`env::args_os()`]. See its documentation
699 /// for more.
700 ///
701 /// The first element is traditionally the path of the executable, but it can be
702 /// set to arbitrary text, and may not even exist. This means this property
703 /// should not be relied upon for security purposes.
704 ///
705 /// [`env::args_os()`]: args_os
706 #[stable(feature = "env", since = "1.0.0")]
707 pub struct ArgsOs {
708     inner: sys::args::Args,
709 }
710
711 /// Returns the arguments that this program was started with (normally passed
712 /// via the command line).
713 ///
714 /// The first element is traditionally the path of the executable, but it can be
715 /// set to arbitrary text, and may not even exist. This means this property should
716 /// not be relied upon for security purposes.
717 ///
718 /// On Unix systems the shell usually expands unquoted arguments with glob patterns
719 /// (such as `*` and `?`). On Windows this is not done, and such arguments are
720 /// passed as-is.
721 ///
722 /// On glibc Linux systems, arguments are retrieved by placing a function in `.init_array`.
723 /// glibc passes `argc`, `argv`, and `envp` to functions in `.init_array`, as a non-standard
724 /// extension. This allows `std::env::args` to work even in a `cdylib` or `staticlib`, as it
725 /// does on macOS and Windows.
726 ///
727 /// # Panics
728 ///
729 /// The returned iterator will panic during iteration if any argument to the
730 /// process is not valid Unicode. If this is not desired,
731 /// use the [`args_os`] function instead.
732 ///
733 /// # Examples
734 ///
735 /// ```
736 /// use std::env;
737 ///
738 /// // Prints each argument on a separate line
739 /// for argument in env::args() {
740 ///     println!("{}", argument);
741 /// }
742 /// ```
743 #[stable(feature = "env", since = "1.0.0")]
744 pub fn args() -> Args {
745     Args { inner: args_os() }
746 }
747
748 /// Returns the arguments that this program was started with (normally passed
749 /// via the command line).
750 ///
751 /// The first element is traditionally the path of the executable, but it can be
752 /// set to arbitrary text, and may not even exist. This means this property should
753 /// not be relied upon for security purposes.
754 ///
755 /// On Unix systems the shell usually expands unquoted arguments with glob patterns
756 /// (such as `*` and `?`). On Windows this is not done, and such arguments are
757 /// passed as-is.
758 ///
759 /// On glibc Linux systems, 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
761 /// extension. This allows `std::env::args_os` to work even in a `cdylib` or `staticlib`, as it
762 /// does on macOS and Windows.
763 ///
764 /// Note that the returned iterator will not check if the arguments to the
765 /// process are valid Unicode. If you want to panic on invalid UTF-8,
766 /// use the [`args`] function instead.
767 ///
768 /// # Examples
769 ///
770 /// ```
771 /// use std::env;
772 ///
773 /// // Prints each argument on a separate line
774 /// for argument in env::args_os() {
775 ///     println!("{:?}", argument);
776 /// }
777 /// ```
778 #[stable(feature = "env", since = "1.0.0")]
779 pub fn args_os() -> ArgsOs {
780     ArgsOs { inner: sys::args::args() }
781 }
782
783 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
784 impl !Send for Args {}
785
786 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
787 impl !Sync for Args {}
788
789 #[stable(feature = "env", since = "1.0.0")]
790 impl Iterator for Args {
791     type Item = String;
792     fn next(&mut self) -> Option<String> {
793         self.inner.next().map(|s| s.into_string().unwrap())
794     }
795     fn size_hint(&self) -> (usize, Option<usize>) {
796         self.inner.size_hint()
797     }
798 }
799
800 #[stable(feature = "env", since = "1.0.0")]
801 impl ExactSizeIterator for Args {
802     fn len(&self) -> usize {
803         self.inner.len()
804     }
805     fn is_empty(&self) -> bool {
806         self.inner.is_empty()
807     }
808 }
809
810 #[stable(feature = "env_iterators", since = "1.12.0")]
811 impl DoubleEndedIterator for Args {
812     fn next_back(&mut self) -> Option<String> {
813         self.inner.next_back().map(|s| s.into_string().unwrap())
814     }
815 }
816
817 #[stable(feature = "std_debug", since = "1.16.0")]
818 impl fmt::Debug for Args {
819     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
820         f.debug_struct("Args").field("inner", &self.inner.inner).finish()
821     }
822 }
823
824 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
825 impl !Send for ArgsOs {}
826
827 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
828 impl !Sync for ArgsOs {}
829
830 #[stable(feature = "env", since = "1.0.0")]
831 impl Iterator for ArgsOs {
832     type Item = OsString;
833     fn next(&mut self) -> Option<OsString> {
834         self.inner.next()
835     }
836     fn size_hint(&self) -> (usize, Option<usize>) {
837         self.inner.size_hint()
838     }
839 }
840
841 #[stable(feature = "env", since = "1.0.0")]
842 impl ExactSizeIterator for ArgsOs {
843     fn len(&self) -> usize {
844         self.inner.len()
845     }
846     fn is_empty(&self) -> bool {
847         self.inner.is_empty()
848     }
849 }
850
851 #[stable(feature = "env_iterators", since = "1.12.0")]
852 impl DoubleEndedIterator for ArgsOs {
853     fn next_back(&mut self) -> Option<OsString> {
854         self.inner.next_back()
855     }
856 }
857
858 #[stable(feature = "std_debug", since = "1.16.0")]
859 impl fmt::Debug for ArgsOs {
860     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
861         f.debug_struct("ArgsOs").field("inner", &self.inner).finish()
862     }
863 }
864
865 /// Constants associated with the current target
866 #[stable(feature = "env", since = "1.0.0")]
867 pub mod consts {
868     use crate::sys::env::os;
869
870     /// A string describing the architecture of the CPU that is currently
871     /// in use.
872     ///
873     /// Some possible values:
874     ///
875     /// - x86
876     /// - x86_64
877     /// - arm
878     /// - aarch64
879     /// - mips
880     /// - mips64
881     /// - powerpc
882     /// - powerpc64
883     /// - riscv64
884     /// - s390x
885     /// - sparc64
886     #[stable(feature = "env", since = "1.0.0")]
887     pub const ARCH: &str = env!("STD_ENV_ARCH");
888
889     /// The family of the operating system. Example value is `unix`.
890     ///
891     /// Some possible values:
892     ///
893     /// - unix
894     /// - windows
895     #[stable(feature = "env", since = "1.0.0")]
896     pub const FAMILY: &str = os::FAMILY;
897
898     /// A string describing the specific operating system in use.
899     /// Example value is `linux`.
900     ///
901     /// Some possible values:
902     ///
903     /// - linux
904     /// - macos
905     /// - ios
906     /// - freebsd
907     /// - dragonfly
908     /// - netbsd
909     /// - openbsd
910     /// - solaris
911     /// - android
912     /// - windows
913     #[stable(feature = "env", since = "1.0.0")]
914     pub const OS: &str = os::OS;
915
916     /// Specifies the filename prefix used for shared libraries on this
917     /// platform. Example value is `lib`.
918     ///
919     /// Some possible values:
920     ///
921     /// - lib
922     /// - `""` (an empty string)
923     #[stable(feature = "env", since = "1.0.0")]
924     pub const DLL_PREFIX: &str = os::DLL_PREFIX;
925
926     /// Specifies the filename suffix used for shared libraries on this
927     /// platform. Example value is `.so`.
928     ///
929     /// Some possible values:
930     ///
931     /// - .so
932     /// - .dylib
933     /// - .dll
934     #[stable(feature = "env", since = "1.0.0")]
935     pub const DLL_SUFFIX: &str = os::DLL_SUFFIX;
936
937     /// Specifies the file extension used for shared libraries on this
938     /// platform that goes after the dot. Example value is `so`.
939     ///
940     /// Some possible values:
941     ///
942     /// - so
943     /// - dylib
944     /// - dll
945     #[stable(feature = "env", since = "1.0.0")]
946     pub const DLL_EXTENSION: &str = os::DLL_EXTENSION;
947
948     /// Specifies the filename suffix used for executable binaries on this
949     /// platform. Example value is `.exe`.
950     ///
951     /// Some possible values:
952     ///
953     /// - .exe
954     /// - .nexe
955     /// - .pexe
956     /// - `""` (an empty string)
957     #[stable(feature = "env", since = "1.0.0")]
958     pub const EXE_SUFFIX: &str = os::EXE_SUFFIX;
959
960     /// Specifies the file extension, if any, used for executable binaries
961     /// on this platform. Example value is `exe`.
962     ///
963     /// Some possible values:
964     ///
965     /// - exe
966     /// - `""` (an empty string)
967     #[stable(feature = "env", since = "1.0.0")]
968     pub const EXE_EXTENSION: &str = os::EXE_EXTENSION;
969 }