]> git.lizzy.rs Git - rust.git/blob - library/std/src/env.rs
Fix parameter names in std::env documentation.
[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 `key` to the value `value` 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 `value` contains the NUL 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>>(key: K, value: V) {
327     _set_var(key.as_ref(), value.as_ref())
328 }
329
330 fn _set_var(key: &OsStr, value: &OsStr) {
331     os_imp::setenv(key, value).unwrap_or_else(|e| {
332         panic!("failed to set environment variable `{:?}` to `{:?}`: {}", key, value, 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](https://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>>(key: K) {
369     _remove_var(key.as_ref())
370 }
371
372 fn _remove_var(key: &OsStr) {
373     os_imp::unsetenv(key)
374         .unwrap_or_else(|e| panic!("failed to remove environment variable `{:?}`: {}", key, 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 [`env::split_paths()`]. See its
383 /// documentation for more.
384 ///
385 /// [`env::split_paths()`]: split_paths
386 #[stable(feature = "env", since = "1.0.0")]
387 pub struct SplitPaths<'a> {
388     inner: os_imp::SplitPaths<'a>,
389 }
390
391 /// Parses input according to platform conventions for the `PATH`
392 /// environment variable.
393 ///
394 /// Returns an iterator over the paths contained in `unparsed`. The iterator
395 /// element type is [`PathBuf`].
396 ///
397 /// # Examples
398 ///
399 /// ```
400 /// use std::env;
401 ///
402 /// let key = "PATH";
403 /// match env::var_os(key) {
404 ///     Some(paths) => {
405 ///         for path in env::split_paths(&paths) {
406 ///             println!("'{}'", path.display());
407 ///         }
408 ///     }
409 ///     None => println!("{} is not defined in the environment.", key)
410 /// }
411 /// ```
412 #[stable(feature = "env", since = "1.0.0")]
413 pub fn split_paths<T: AsRef<OsStr> + ?Sized>(unparsed: &T) -> SplitPaths<'_> {
414     SplitPaths { inner: os_imp::split_paths(unparsed.as_ref()) }
415 }
416
417 #[stable(feature = "env", since = "1.0.0")]
418 impl<'a> Iterator for SplitPaths<'a> {
419     type Item = PathBuf;
420     fn next(&mut self) -> Option<PathBuf> {
421         self.inner.next()
422     }
423     fn size_hint(&self) -> (usize, Option<usize>) {
424         self.inner.size_hint()
425     }
426 }
427
428 #[stable(feature = "std_debug", since = "1.16.0")]
429 impl fmt::Debug for SplitPaths<'_> {
430     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
431         f.debug_struct("SplitPaths").finish_non_exhaustive()
432     }
433 }
434
435 /// The error type for operations on the `PATH` variable. Possibly returned from
436 /// [`env::join_paths()`].
437 ///
438 /// [`env::join_paths()`]: join_paths
439 #[derive(Debug)]
440 #[stable(feature = "env", since = "1.0.0")]
441 pub struct JoinPathsError {
442     inner: os_imp::JoinPathsError,
443 }
444
445 /// Joins a collection of [`Path`]s appropriately for the `PATH`
446 /// environment variable.
447 ///
448 /// # Errors
449 ///
450 /// Returns an [`Err`] (containing an error message) if one of the input
451 /// [`Path`]s contains an invalid character for constructing the `PATH`
452 /// variable (a double quote on Windows or a colon on Unix).
453 ///
454 /// # Examples
455 ///
456 /// Joining paths on a Unix-like platform:
457 ///
458 /// ```
459 /// use std::env;
460 /// use std::ffi::OsString;
461 /// use std::path::Path;
462 ///
463 /// fn main() -> Result<(), env::JoinPathsError> {
464 /// # if cfg!(unix) {
465 ///     let paths = [Path::new("/bin"), Path::new("/usr/bin")];
466 ///     let path_os_string = env::join_paths(paths.iter())?;
467 ///     assert_eq!(path_os_string, OsString::from("/bin:/usr/bin"));
468 /// # }
469 ///     Ok(())
470 /// }
471 /// ```
472 ///
473 /// Joining a path containing a colon on a Unix-like platform results in an
474 /// error:
475 ///
476 /// ```
477 /// # if cfg!(unix) {
478 /// use std::env;
479 /// use std::path::Path;
480 ///
481 /// let paths = [Path::new("/bin"), Path::new("/usr/bi:n")];
482 /// assert!(env::join_paths(paths.iter()).is_err());
483 /// # }
484 /// ```
485 ///
486 /// Using `env::join_paths()` with [`env::split_paths()`] to append an item to
487 /// the `PATH` environment variable:
488 ///
489 /// ```
490 /// use std::env;
491 /// use std::path::PathBuf;
492 ///
493 /// fn main() -> Result<(), env::JoinPathsError> {
494 ///     if let Some(path) = env::var_os("PATH") {
495 ///         let mut paths = env::split_paths(&path).collect::<Vec<_>>();
496 ///         paths.push(PathBuf::from("/home/xyz/bin"));
497 ///         let new_path = env::join_paths(paths)?;
498 ///         env::set_var("PATH", &new_path);
499 ///     }
500 ///
501 ///     Ok(())
502 /// }
503 /// ```
504 ///
505 /// [`env::split_paths()`]: split_paths
506 #[stable(feature = "env", since = "1.0.0")]
507 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
508 where
509     I: IntoIterator<Item = T>,
510     T: AsRef<OsStr>,
511 {
512     os_imp::join_paths(paths.into_iter()).map_err(|e| JoinPathsError { inner: e })
513 }
514
515 #[stable(feature = "env", since = "1.0.0")]
516 impl fmt::Display for JoinPathsError {
517     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
518         self.inner.fmt(f)
519     }
520 }
521
522 #[stable(feature = "env", since = "1.0.0")]
523 impl Error for JoinPathsError {
524     #[allow(deprecated, deprecated_in_future)]
525     fn description(&self) -> &str {
526         self.inner.description()
527     }
528 }
529
530 /// Returns the path of the current user's home directory if known.
531 ///
532 /// # Unix
533 ///
534 /// - Returns the value of the 'HOME' environment variable if it is set
535 ///   (including to an empty string).
536 /// - Otherwise, it tries to determine the home directory by invoking the `getpwuid_r` function
537 ///   using the UID of the current user. An empty home directory field returned from the
538 ///   `getpwuid_r` function is considered to be a valid value.
539 /// - Returns `None` if the current user has no entry in the /etc/passwd file.
540 ///
541 /// # Windows
542 ///
543 /// - Returns the value of the 'HOME' environment variable if it is set
544 ///   (including to an empty string).
545 /// - Otherwise, returns the value of the 'USERPROFILE' environment variable if it is set
546 ///   (including to an empty string).
547 /// - If both do not exist, [`GetUserProfileDirectory`][msdn] is used to return the path.
548 ///
549 /// [msdn]: https://docs.microsoft.com/en-us/windows/win32/api/userenv/nf-userenv-getuserprofiledirectorya
550 ///
551 /// # Examples
552 ///
553 /// ```
554 /// use std::env;
555 ///
556 /// match env::home_dir() {
557 ///     Some(path) => println!("Your home directory, probably: {}", path.display()),
558 ///     None => println!("Impossible to get your home dir!"),
559 /// }
560 /// ```
561 #[rustc_deprecated(
562     since = "1.29.0",
563     reason = "This function's behavior is unexpected and probably not what you want. \
564               Consider using a crate from crates.io instead."
565 )]
566 #[stable(feature = "env", since = "1.0.0")]
567 pub fn home_dir() -> Option<PathBuf> {
568     os_imp::home_dir()
569 }
570
571 /// Returns the path of a temporary directory.
572 ///
573 /// The temporary directory may be shared among users, or between processes
574 /// with different privileges; thus, the creation of any files or directories
575 /// in the temporary directory must use a secure method to create a uniquely
576 /// named file. Creating a file or directory with a fixed or predictable name
577 /// may result in "insecure temporary file" security vulnerabilities. Consider
578 /// using a crate that securely creates temporary files or directories.
579 ///
580 /// # Unix
581 ///
582 /// Returns the value of the `TMPDIR` environment variable if it is
583 /// set, otherwise for non-Android it returns `/tmp`. If Android, since there
584 /// is no global temporary folder (it is usually allocated per-app), it returns
585 /// `/data/local/tmp`.
586 ///
587 /// # Windows
588 ///
589 /// Returns the value of, in order, the `TMP`, `TEMP`,
590 /// `USERPROFILE` environment variable if any are set and not the empty
591 /// string. Otherwise, `temp_dir` returns the path of the Windows directory.
592 /// This behavior is identical to that of [`GetTempPath`][msdn], which this
593 /// function uses internally.
594 ///
595 /// [msdn]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppatha
596 ///
597 /// ```no_run
598 /// use std::env;
599 ///
600 /// fn main() {
601 ///     let mut dir = env::temp_dir();
602 ///     println!("Temporary directory: {}", dir.display());
603 /// }
604 /// ```
605 #[stable(feature = "env", since = "1.0.0")]
606 pub fn temp_dir() -> PathBuf {
607     os_imp::temp_dir()
608 }
609
610 /// Returns the full filesystem path of the current running executable.
611 ///
612 /// # Platform-specific behavior
613 ///
614 /// If the executable was invoked through a symbolic link, some platforms will
615 /// return the path of the symbolic link and other platforms will return the
616 /// path of the symbolic link’s target.
617 ///
618 /// # Errors
619 ///
620 /// Acquiring the path of the current executable is a platform-specific operation
621 /// that can fail for a good number of reasons. Some errors can include, but not
622 /// be limited to, filesystem operations failing or general syscall failures.
623 ///
624 /// # Security
625 ///
626 /// The output of this function should not be used in anything that might have
627 /// security implications. For example:
628 ///
629 /// ```
630 /// fn main() {
631 ///     println!("{:?}", std::env::current_exe());
632 /// }
633 /// ```
634 ///
635 /// On Linux systems, if this is compiled as `foo`:
636 ///
637 /// ```bash
638 /// $ rustc foo.rs
639 /// $ ./foo
640 /// Ok("/home/alex/foo")
641 /// ```
642 ///
643 /// And you make a hard link of the program:
644 ///
645 /// ```bash
646 /// $ ln foo bar
647 /// ```
648 ///
649 /// When you run it, you won’t get the path of the original executable, you’ll
650 /// get the path of the hard link:
651 ///
652 /// ```bash
653 /// $ ./bar
654 /// Ok("/home/alex/bar")
655 /// ```
656 ///
657 /// This sort of behavior has been known to [lead to privilege escalation] when
658 /// used incorrectly.
659 ///
660 /// [lead to privilege escalation]: https://securityvulns.com/Wdocument183.html
661 ///
662 /// # Examples
663 ///
664 /// ```
665 /// use std::env;
666 ///
667 /// match env::current_exe() {
668 ///     Ok(exe_path) => println!("Path of this executable is: {}",
669 ///                              exe_path.display()),
670 ///     Err(e) => println!("failed to get current exe path: {}", e),
671 /// };
672 /// ```
673 #[stable(feature = "env", since = "1.0.0")]
674 pub fn current_exe() -> io::Result<PathBuf> {
675     os_imp::current_exe()
676 }
677
678 /// An iterator over the arguments of a process, yielding a [`String`] value for
679 /// each argument.
680 ///
681 /// This struct is created by [`env::args()`]. See its documentation
682 /// for more.
683 ///
684 /// The first element is traditionally the path of the executable, but it can be
685 /// set to arbitrary text, and may not even exist. This means this property
686 /// should not be relied upon for security purposes.
687 ///
688 /// [`env::args()`]: args
689 #[stable(feature = "env", since = "1.0.0")]
690 pub struct Args {
691     inner: ArgsOs,
692 }
693
694 /// An iterator over the arguments of a process, yielding an [`OsString`] value
695 /// for each argument.
696 ///
697 /// This struct is created by [`env::args_os()`]. See its documentation
698 /// for more.
699 ///
700 /// The first element is traditionally the path of the executable, but it can be
701 /// set to arbitrary text, and may not even exist. This means this property
702 /// should not be relied upon for security purposes.
703 ///
704 /// [`env::args_os()`]: args_os
705 #[stable(feature = "env", since = "1.0.0")]
706 pub struct ArgsOs {
707     inner: sys::args::Args,
708 }
709
710 /// Returns the arguments that this program was started with (normally passed
711 /// via the command line).
712 ///
713 /// The first element is traditionally the path of the executable, but it can be
714 /// set to arbitrary text, and may not even exist. This means this property should
715 /// not be relied upon for security purposes.
716 ///
717 /// On Unix systems the shell usually expands unquoted arguments with glob patterns
718 /// (such as `*` and `?`). On Windows this is not done, and such arguments are
719 /// passed as-is.
720 ///
721 /// On glibc Linux systems, arguments are retrieved by placing a function in `.init_array`.
722 /// glibc passes `argc`, `argv`, and `envp` to functions in `.init_array`, as a non-standard
723 /// extension. This allows `std::env::args` to work even in a `cdylib` or `staticlib`, as it
724 /// does on macOS and Windows.
725 ///
726 /// # Panics
727 ///
728 /// The returned iterator will panic during iteration if any argument to the
729 /// process is not valid Unicode. If this is not desired,
730 /// use the [`args_os`] function instead.
731 ///
732 /// # Examples
733 ///
734 /// ```
735 /// use std::env;
736 ///
737 /// // Prints each argument on a separate line
738 /// for argument in env::args() {
739 ///     println!("{}", argument);
740 /// }
741 /// ```
742 #[stable(feature = "env", since = "1.0.0")]
743 pub fn args() -> Args {
744     Args { inner: args_os() }
745 }
746
747 /// Returns the arguments that this program was started with (normally passed
748 /// via the command line).
749 ///
750 /// The first element is traditionally the path of the executable, but it can be
751 /// set to arbitrary text, and may not even exist. This means this property should
752 /// not be relied upon for security purposes.
753 ///
754 /// On Unix systems the shell usually expands unquoted arguments with glob patterns
755 /// (such as `*` and `?`). On Windows this is not done, and such arguments are
756 /// passed as-is.
757 ///
758 /// On glibc Linux systems, arguments are retrieved by placing a function in `.init_array`.
759 /// glibc passes `argc`, `argv`, and `envp` to functions in `.init_array`, as a non-standard
760 /// extension. This allows `std::env::args_os` to work even in a `cdylib` or `staticlib`, as it
761 /// does on macOS and Windows.
762 ///
763 /// Note that the returned iterator will not check if the arguments to the
764 /// process are valid Unicode. If you want to panic on invalid UTF-8,
765 /// use the [`args`] function instead.
766 ///
767 /// # Examples
768 ///
769 /// ```
770 /// use std::env;
771 ///
772 /// // Prints each argument on a separate line
773 /// for argument in env::args_os() {
774 ///     println!("{:?}", argument);
775 /// }
776 /// ```
777 #[stable(feature = "env", since = "1.0.0")]
778 pub fn args_os() -> ArgsOs {
779     ArgsOs { inner: sys::args::args() }
780 }
781
782 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
783 impl !Send for Args {}
784
785 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
786 impl !Sync for Args {}
787
788 #[stable(feature = "env", since = "1.0.0")]
789 impl Iterator for Args {
790     type Item = String;
791     fn next(&mut self) -> Option<String> {
792         self.inner.next().map(|s| s.into_string().unwrap())
793     }
794     fn size_hint(&self) -> (usize, Option<usize>) {
795         self.inner.size_hint()
796     }
797 }
798
799 #[stable(feature = "env", since = "1.0.0")]
800 impl ExactSizeIterator for Args {
801     fn len(&self) -> usize {
802         self.inner.len()
803     }
804     fn is_empty(&self) -> bool {
805         self.inner.is_empty()
806     }
807 }
808
809 #[stable(feature = "env_iterators", since = "1.12.0")]
810 impl DoubleEndedIterator for Args {
811     fn next_back(&mut self) -> Option<String> {
812         self.inner.next_back().map(|s| s.into_string().unwrap())
813     }
814 }
815
816 #[stable(feature = "std_debug", since = "1.16.0")]
817 impl fmt::Debug for Args {
818     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
819         f.debug_struct("Args").field("inner", &self.inner.inner).finish()
820     }
821 }
822
823 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
824 impl !Send for ArgsOs {}
825
826 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
827 impl !Sync for ArgsOs {}
828
829 #[stable(feature = "env", since = "1.0.0")]
830 impl Iterator for ArgsOs {
831     type Item = OsString;
832     fn next(&mut self) -> Option<OsString> {
833         self.inner.next()
834     }
835     fn size_hint(&self) -> (usize, Option<usize>) {
836         self.inner.size_hint()
837     }
838 }
839
840 #[stable(feature = "env", since = "1.0.0")]
841 impl ExactSizeIterator for ArgsOs {
842     fn len(&self) -> usize {
843         self.inner.len()
844     }
845     fn is_empty(&self) -> bool {
846         self.inner.is_empty()
847     }
848 }
849
850 #[stable(feature = "env_iterators", since = "1.12.0")]
851 impl DoubleEndedIterator for ArgsOs {
852     fn next_back(&mut self) -> Option<OsString> {
853         self.inner.next_back()
854     }
855 }
856
857 #[stable(feature = "std_debug", since = "1.16.0")]
858 impl fmt::Debug for ArgsOs {
859     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
860         f.debug_struct("ArgsOs").field("inner", &self.inner).finish()
861     }
862 }
863
864 /// Constants associated with the current target
865 #[stable(feature = "env", since = "1.0.0")]
866 pub mod consts {
867     use crate::sys::env::os;
868
869     /// A string describing the architecture of the CPU that is currently
870     /// in use.
871     ///
872     /// Some possible values:
873     ///
874     /// - x86
875     /// - x86_64
876     /// - arm
877     /// - aarch64
878     /// - mips
879     /// - mips64
880     /// - powerpc
881     /// - powerpc64
882     /// - riscv64
883     /// - s390x
884     /// - sparc64
885     #[stable(feature = "env", since = "1.0.0")]
886     pub const ARCH: &str = env!("STD_ENV_ARCH");
887
888     /// The family of the operating system. Example value is `unix`.
889     ///
890     /// Some possible values:
891     ///
892     /// - unix
893     /// - windows
894     #[stable(feature = "env", since = "1.0.0")]
895     pub const FAMILY: &str = os::FAMILY;
896
897     /// A string describing the specific operating system in use.
898     /// Example value is `linux`.
899     ///
900     /// Some possible values:
901     ///
902     /// - linux
903     /// - macos
904     /// - ios
905     /// - freebsd
906     /// - dragonfly
907     /// - netbsd
908     /// - openbsd
909     /// - solaris
910     /// - android
911     /// - windows
912     #[stable(feature = "env", since = "1.0.0")]
913     pub const OS: &str = os::OS;
914
915     /// Specifies the filename prefix used for shared libraries on this
916     /// platform. Example value is `lib`.
917     ///
918     /// Some possible values:
919     ///
920     /// - lib
921     /// - `""` (an empty string)
922     #[stable(feature = "env", since = "1.0.0")]
923     pub const DLL_PREFIX: &str = os::DLL_PREFIX;
924
925     /// Specifies the filename suffix used for shared libraries on this
926     /// platform. Example value is `.so`.
927     ///
928     /// Some possible values:
929     ///
930     /// - .so
931     /// - .dylib
932     /// - .dll
933     #[stable(feature = "env", since = "1.0.0")]
934     pub const DLL_SUFFIX: &str = os::DLL_SUFFIX;
935
936     /// Specifies the file extension used for shared libraries on this
937     /// platform that goes after the dot. Example value is `so`.
938     ///
939     /// Some possible values:
940     ///
941     /// - so
942     /// - dylib
943     /// - dll
944     #[stable(feature = "env", since = "1.0.0")]
945     pub const DLL_EXTENSION: &str = os::DLL_EXTENSION;
946
947     /// Specifies the filename suffix used for executable binaries on this
948     /// platform. Example value is `.exe`.
949     ///
950     /// Some possible values:
951     ///
952     /// - .exe
953     /// - .nexe
954     /// - .pexe
955     /// - `""` (an empty string)
956     #[stable(feature = "env", since = "1.0.0")]
957     pub const EXE_SUFFIX: &str = os::EXE_SUFFIX;
958
959     /// Specifies the file extension, if any, used for executable binaries
960     /// on this platform. Example value is `exe`.
961     ///
962     /// Some possible values:
963     ///
964     /// - exe
965     /// - `""` (an empty string)
966     #[stable(feature = "env", since = "1.0.0")]
967     pub const EXE_EXTENSION: &str = os::EXE_EXTENSION;
968 }