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