]> git.proxmox.com Git - rustc.git/blob - library/std/src/env.rs
New upstream version 1.53.0+dfsg1
[rustc.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 #[stable(feature = "env", since = "1.0.0")]
65 pub fn set_current_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
66 os_imp::chdir(path.as_ref())
67 }
68
69 /// An iterator over a snapshot of the environment variables of this process.
70 ///
71 /// This structure is created by [`env::vars()`]. See its documentation for more.
72 ///
73 /// [`env::vars()`]: vars
74 #[stable(feature = "env", since = "1.0.0")]
75 pub struct Vars {
76 inner: VarsOs,
77 }
78
79 /// An iterator over a snapshot of the environment variables of this process.
80 ///
81 /// This structure is created by [`env::vars_os()`]. See its documentation for more.
82 ///
83 /// [`env::vars_os()`]: vars_os
84 #[stable(feature = "env", since = "1.0.0")]
85 pub struct VarsOs {
86 inner: os_imp::Env,
87 }
88
89 /// Returns an iterator of (variable, value) pairs of strings, for all the
90 /// environment variables of the current process.
91 ///
92 /// The returned iterator contains a snapshot of the process's environment
93 /// variables at the time of this invocation. Modifications to environment
94 /// variables afterwards will not be reflected in the returned iterator.
95 ///
96 /// # Panics
97 ///
98 /// While iterating, the returned iterator will panic if any key or value in the
99 /// environment is not valid unicode. If this is not desired, consider using
100 /// [`env::vars_os()`].
101 ///
102 /// # Examples
103 ///
104 /// ```
105 /// use std::env;
106 ///
107 /// // We will iterate through the references to the element returned by
108 /// // env::vars();
109 /// for (key, value) in env::vars() {
110 /// println!("{}: {}", key, value);
111 /// }
112 /// ```
113 ///
114 /// [`env::vars_os()`]: vars_os
115 #[stable(feature = "env", since = "1.0.0")]
116 pub fn vars() -> Vars {
117 Vars { inner: vars_os() }
118 }
119
120 /// Returns an iterator of (variable, value) pairs of OS strings, for all the
121 /// environment variables of the current process.
122 ///
123 /// The returned iterator contains a snapshot of the process's environment
124 /// variables at the time of this invocation. Modifications to environment
125 /// variables afterwards will not be reflected in the returned iterator.
126 ///
127 /// Note that the returned iterator will not check if the environment variables
128 /// are valid Unicode. If you want to panic on invalid UTF-8,
129 /// use the [`vars`] function instead.
130 ///
131 /// # Examples
132 ///
133 /// ```
134 /// use std::env;
135 ///
136 /// // We will iterate through the references to the element returned by
137 /// // env::vars_os();
138 /// for (key, value) in env::vars_os() {
139 /// println!("{:?}: {:?}", key, value);
140 /// }
141 /// ```
142 #[stable(feature = "env", since = "1.0.0")]
143 pub fn vars_os() -> VarsOs {
144 VarsOs { inner: os_imp::env() }
145 }
146
147 #[stable(feature = "env", since = "1.0.0")]
148 impl Iterator for Vars {
149 type Item = (String, String);
150 fn next(&mut self) -> Option<(String, String)> {
151 self.inner.next().map(|(a, b)| (a.into_string().unwrap(), b.into_string().unwrap()))
152 }
153 fn size_hint(&self) -> (usize, Option<usize>) {
154 self.inner.size_hint()
155 }
156 }
157
158 #[stable(feature = "std_debug", since = "1.16.0")]
159 impl fmt::Debug for Vars {
160 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161 f.debug_struct("Vars").finish_non_exhaustive()
162 }
163 }
164
165 #[stable(feature = "env", since = "1.0.0")]
166 impl Iterator for VarsOs {
167 type Item = (OsString, OsString);
168 fn next(&mut self) -> Option<(OsString, OsString)> {
169 self.inner.next()
170 }
171 fn size_hint(&self) -> (usize, Option<usize>) {
172 self.inner.size_hint()
173 }
174 }
175
176 #[stable(feature = "std_debug", since = "1.16.0")]
177 impl fmt::Debug for VarsOs {
178 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179 f.debug_struct("VarOs").finish_non_exhaustive()
180 }
181 }
182
183 /// Fetches the environment variable `key` from the current process.
184 ///
185 /// # Errors
186 ///
187 /// Errors if the environment variable is not present.
188 /// Errors if the environment variable is not valid Unicode. If this is not desired, consider using
189 /// [`var_os`].
190 ///
191 /// # Panics
192 ///
193 /// This function may panic if `key` is empty, contains an ASCII equals sign
194 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
195 /// character.
196 ///
197 /// # Examples
198 ///
199 /// ```
200 /// use std::env;
201 ///
202 /// let key = "HOME";
203 /// match env::var(key) {
204 /// Ok(val) => println!("{}: {:?}", key, val),
205 /// Err(e) => println!("couldn't interpret {}: {}", key, e),
206 /// }
207 /// ```
208 #[stable(feature = "env", since = "1.0.0")]
209 pub fn var<K: AsRef<OsStr>>(key: K) -> Result<String, VarError> {
210 _var(key.as_ref())
211 }
212
213 fn _var(key: &OsStr) -> Result<String, VarError> {
214 match var_os(key) {
215 Some(s) => s.into_string().map_err(VarError::NotUnicode),
216 None => Err(VarError::NotPresent),
217 }
218 }
219
220 /// Fetches the environment variable `key` from the current process, returning
221 /// [`None`] if the variable isn't set.
222 ///
223 /// # Panics
224 ///
225 /// This function may panic if `key` is empty, contains an ASCII equals sign
226 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
227 /// character.
228 ///
229 /// Note that the method will not check if the environment variable
230 /// is valid Unicode. If you want to have an error on invalid UTF-8,
231 /// use the [`var`] function instead.
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 [`env::var()`].
256 ///
257 /// [`env::var()`]: var
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 [`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 }