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