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