]> git.lizzy.rs Git - rust.git/blob - library/std/src/env.rs
Rollup merge of #97215 - AngelicosPhosphoros:add_hashtable_iteration_complexity_note...
[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 #[deprecated(
581     since = "1.29.0",
582     note = "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 trusted for anything
648 /// that might have security implications. Basically, if users can run
649 /// the executable, they can change the output arbitrarily.
650 ///
651 /// As an example, you can easily introduce a race condition. It goes
652 /// like this:
653 ///
654 /// 1. You get the path to the current executable using `current_exe()`, and
655 ///    store it in a variable.
656 /// 2. Time passes. A malicious actor removes the current executable, and
657 ///    replaces it with a malicious one.
658 /// 3. You then use the stored path to re-execute the current
659 ///    executable.
660 ///
661 /// You expected to safely execute the current executable, but you're
662 /// instead executing something completely different. The code you
663 /// just executed run with your privileges.
664 ///
665 /// This sort of behavior has been known to [lead to privilege escalation] when
666 /// used incorrectly.
667 ///
668 /// [lead to privilege escalation]: https://securityvulns.com/Wdocument183.html
669 ///
670 /// # Examples
671 ///
672 /// ```
673 /// use std::env;
674 ///
675 /// match env::current_exe() {
676 ///     Ok(exe_path) => println!("Path of this executable is: {}",
677 ///                              exe_path.display()),
678 ///     Err(e) => println!("failed to get current exe path: {e}"),
679 /// };
680 /// ```
681 #[stable(feature = "env", since = "1.0.0")]
682 pub fn current_exe() -> io::Result<PathBuf> {
683     os_imp::current_exe()
684 }
685
686 /// An iterator over the arguments of a process, yielding a [`String`] value for
687 /// each argument.
688 ///
689 /// This struct is created by [`env::args()`]. See its documentation
690 /// for more.
691 ///
692 /// The first element is traditionally the path of the executable, but it can be
693 /// set to arbitrary text, and might not even exist. This means this property
694 /// should not be relied upon for security purposes.
695 ///
696 /// [`env::args()`]: args
697 #[must_use = "iterators are lazy and do nothing unless consumed"]
698 #[stable(feature = "env", since = "1.0.0")]
699 pub struct Args {
700     inner: ArgsOs,
701 }
702
703 /// An iterator over the arguments of a process, yielding an [`OsString`] value
704 /// for each argument.
705 ///
706 /// This struct is created by [`env::args_os()`]. See its documentation
707 /// for more.
708 ///
709 /// The first element is traditionally the path of the executable, but it can be
710 /// set to arbitrary text, and might not even exist. This means this property
711 /// should not be relied upon for security purposes.
712 ///
713 /// [`env::args_os()`]: args_os
714 #[must_use = "iterators are lazy and do nothing unless consumed"]
715 #[stable(feature = "env", since = "1.0.0")]
716 pub struct ArgsOs {
717     inner: sys::args::Args,
718 }
719
720 /// Returns the arguments that this program was started with (normally passed
721 /// via the command line).
722 ///
723 /// The first element is traditionally the path of the executable, but it can be
724 /// set to arbitrary text, and might not even exist. This means this property should
725 /// not be relied upon for security purposes.
726 ///
727 /// On Unix systems the shell usually expands unquoted arguments with glob patterns
728 /// (such as `*` and `?`). On Windows this is not done, and such arguments are
729 /// passed as-is.
730 ///
731 /// On glibc Linux systems, arguments are retrieved by placing a function in `.init_array`.
732 /// glibc passes `argc`, `argv`, and `envp` to functions in `.init_array`, as a non-standard
733 /// extension. This allows `std::env::args` to work even in a `cdylib` or `staticlib`, as it
734 /// does on macOS and Windows.
735 ///
736 /// # Panics
737 ///
738 /// The returned iterator will panic during iteration if any argument to the
739 /// process is not valid Unicode. If this is not desired,
740 /// use the [`args_os`] function instead.
741 ///
742 /// # Examples
743 ///
744 /// ```
745 /// use std::env;
746 ///
747 /// // Prints each argument on a separate line
748 /// for argument in env::args() {
749 ///     println!("{argument}");
750 /// }
751 /// ```
752 #[stable(feature = "env", since = "1.0.0")]
753 pub fn args() -> Args {
754     Args { inner: args_os() }
755 }
756
757 /// Returns the arguments that this program was started with (normally passed
758 /// via the command line).
759 ///
760 /// The first element is traditionally the path of the executable, but it can be
761 /// set to arbitrary text, and might not even exist. This means this property should
762 /// not be relied upon for security purposes.
763 ///
764 /// On Unix systems the shell usually expands unquoted arguments with glob patterns
765 /// (such as `*` and `?`). On Windows this is not done, and such arguments are
766 /// passed as-is.
767 ///
768 /// On glibc Linux systems, arguments are retrieved by placing a function in `.init_array`.
769 /// glibc passes `argc`, `argv`, and `envp` to functions in `.init_array`, as a non-standard
770 /// extension. This allows `std::env::args_os` to work even in a `cdylib` or `staticlib`, as it
771 /// does on macOS and Windows.
772 ///
773 /// Note that the returned iterator will not check if the arguments to the
774 /// process are valid Unicode. If you want to panic on invalid UTF-8,
775 /// use the [`args`] function instead.
776 ///
777 /// # Examples
778 ///
779 /// ```
780 /// use std::env;
781 ///
782 /// // Prints each argument on a separate line
783 /// for argument in env::args_os() {
784 ///     println!("{argument:?}");
785 /// }
786 /// ```
787 #[stable(feature = "env", since = "1.0.0")]
788 pub fn args_os() -> ArgsOs {
789     ArgsOs { inner: sys::args::args() }
790 }
791
792 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
793 impl !Send for Args {}
794
795 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
796 impl !Sync for Args {}
797
798 #[stable(feature = "env", since = "1.0.0")]
799 impl Iterator for Args {
800     type Item = String;
801     fn next(&mut self) -> Option<String> {
802         self.inner.next().map(|s| s.into_string().unwrap())
803     }
804     fn size_hint(&self) -> (usize, Option<usize>) {
805         self.inner.size_hint()
806     }
807 }
808
809 #[stable(feature = "env", since = "1.0.0")]
810 impl ExactSizeIterator for Args {
811     fn len(&self) -> usize {
812         self.inner.len()
813     }
814     fn is_empty(&self) -> bool {
815         self.inner.is_empty()
816     }
817 }
818
819 #[stable(feature = "env_iterators", since = "1.12.0")]
820 impl DoubleEndedIterator for Args {
821     fn next_back(&mut self) -> Option<String> {
822         self.inner.next_back().map(|s| s.into_string().unwrap())
823     }
824 }
825
826 #[stable(feature = "std_debug", since = "1.16.0")]
827 impl fmt::Debug for Args {
828     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
829         f.debug_struct("Args").field("inner", &self.inner.inner).finish()
830     }
831 }
832
833 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
834 impl !Send for ArgsOs {}
835
836 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
837 impl !Sync for ArgsOs {}
838
839 #[stable(feature = "env", since = "1.0.0")]
840 impl Iterator for ArgsOs {
841     type Item = OsString;
842     fn next(&mut self) -> Option<OsString> {
843         self.inner.next()
844     }
845     fn size_hint(&self) -> (usize, Option<usize>) {
846         self.inner.size_hint()
847     }
848 }
849
850 #[stable(feature = "env", since = "1.0.0")]
851 impl ExactSizeIterator for ArgsOs {
852     fn len(&self) -> usize {
853         self.inner.len()
854     }
855     fn is_empty(&self) -> bool {
856         self.inner.is_empty()
857     }
858 }
859
860 #[stable(feature = "env_iterators", since = "1.12.0")]
861 impl DoubleEndedIterator for ArgsOs {
862     fn next_back(&mut self) -> Option<OsString> {
863         self.inner.next_back()
864     }
865 }
866
867 #[stable(feature = "std_debug", since = "1.16.0")]
868 impl fmt::Debug for ArgsOs {
869     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
870         f.debug_struct("ArgsOs").field("inner", &self.inner).finish()
871     }
872 }
873
874 /// Constants associated with the current target
875 #[stable(feature = "env", since = "1.0.0")]
876 pub mod consts {
877     use crate::sys::env::os;
878
879     /// A string describing the architecture of the CPU that is currently
880     /// in use.
881     ///
882     /// Some possible values:
883     ///
884     /// - x86
885     /// - x86_64
886     /// - arm
887     /// - aarch64
888     /// - m68k
889     /// - mips
890     /// - mips64
891     /// - powerpc
892     /// - powerpc64
893     /// - riscv64
894     /// - s390x
895     /// - sparc64
896     #[stable(feature = "env", since = "1.0.0")]
897     pub const ARCH: &str = env!("STD_ENV_ARCH");
898
899     /// The family of the operating system. Example value is `unix`.
900     ///
901     /// Some possible values:
902     ///
903     /// - unix
904     /// - windows
905     #[stable(feature = "env", since = "1.0.0")]
906     pub const FAMILY: &str = os::FAMILY;
907
908     /// A string describing the specific operating system in use.
909     /// Example value is `linux`.
910     ///
911     /// Some possible values:
912     ///
913     /// - linux
914     /// - macos
915     /// - ios
916     /// - freebsd
917     /// - dragonfly
918     /// - netbsd
919     /// - openbsd
920     /// - solaris
921     /// - android
922     /// - windows
923     #[stable(feature = "env", since = "1.0.0")]
924     pub const OS: &str = os::OS;
925
926     /// Specifies the filename prefix used for shared libraries on this
927     /// platform. Example value is `lib`.
928     ///
929     /// Some possible values:
930     ///
931     /// - lib
932     /// - `""` (an empty string)
933     #[stable(feature = "env", since = "1.0.0")]
934     pub const DLL_PREFIX: &str = os::DLL_PREFIX;
935
936     /// Specifies the filename suffix used for shared libraries on this
937     /// platform. 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_SUFFIX: &str = os::DLL_SUFFIX;
946
947     /// Specifies the file extension used for shared libraries on this
948     /// platform that goes after the dot. Example value is `so`.
949     ///
950     /// Some possible values:
951     ///
952     /// - so
953     /// - dylib
954     /// - dll
955     #[stable(feature = "env", since = "1.0.0")]
956     pub const DLL_EXTENSION: &str = os::DLL_EXTENSION;
957
958     /// Specifies the filename suffix used for executable binaries on this
959     /// platform. Example value is `.exe`.
960     ///
961     /// Some possible values:
962     ///
963     /// - .exe
964     /// - .nexe
965     /// - .pexe
966     /// - `""` (an empty string)
967     #[stable(feature = "env", since = "1.0.0")]
968     pub const EXE_SUFFIX: &str = os::EXE_SUFFIX;
969
970     /// Specifies the file extension, if any, used for executable binaries
971     /// on this platform. Example value is `exe`.
972     ///
973     /// Some possible values:
974     ///
975     /// - exe
976     /// - `""` (an empty string)
977     #[stable(feature = "env", since = "1.0.0")]
978     pub const EXE_EXTENSION: &str = os::EXE_EXTENSION;
979 }