]> git.lizzy.rs Git - rust.git/blob - src/libstd/env.rs
Rollup merge of #60915 - michaelwoerister:hashstablestuff, r=estebank
[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::spit_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 #[stable(feature = "env", since = "1.0.0")]
487 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
488     where I: IntoIterator<Item=T>, T: AsRef<OsStr>
489 {
490     os_imp::join_paths(paths.into_iter()).map_err(|e| {
491         JoinPathsError { inner: e }
492     })
493 }
494
495 #[stable(feature = "env", since = "1.0.0")]
496 impl fmt::Display for JoinPathsError {
497     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
498         self.inner.fmt(f)
499     }
500 }
501
502 #[stable(feature = "env", since = "1.0.0")]
503 impl Error for JoinPathsError {
504     fn description(&self) -> &str { self.inner.description() }
505 }
506
507 /// Returns the path of the current user's home directory if known.
508 ///
509 /// # Unix
510 ///
511 /// - Returns the value of the 'HOME' environment variable if it is set
512 ///   (including to an empty string).
513 /// - Otherwise, it tries to determine the home directory by invoking the `getpwuid_r` function
514 ///   using the UID of the current user. An empty home directory field returned from the
515 ///   `getpwuid_r` function is considered to be a valid value.
516 /// - Returns `None` if the current user has no entry in the /etc/passwd file.
517 ///
518 /// # Windows
519 ///
520 /// - Returns the value of the 'HOME' environment variable if it is set
521 ///   (including to an empty string).
522 /// - Otherwise, returns the value of the 'USERPROFILE' environment variable if it is set
523 ///   (including to an empty string).
524 /// - If both do not exist, [`GetUserProfileDirectory`][msdn] is used to return the path.
525 ///
526 /// [msdn]: https://msdn.microsoft.com/en-us/library/windows/desktop/bb762280(v=vs.85).aspx
527 ///
528 /// # Examples
529 ///
530 /// ```
531 /// use std::env;
532 ///
533 /// match env::home_dir() {
534 ///     Some(path) => println!("Your home directory, probably: {}", path.display()),
535 ///     None => println!("Impossible to get your home dir!"),
536 /// }
537 /// ```
538 #[rustc_deprecated(since = "1.29.0",
539     reason = "This function's behavior is unexpected and probably not what you want. \
540               Consider using the home_dir function from https://crates.io/crates/dirs instead.")]
541 #[stable(feature = "env", since = "1.0.0")]
542 pub fn home_dir() -> Option<PathBuf> {
543     os_imp::home_dir()
544 }
545
546 /// Returns the path of a temporary directory.
547 ///
548 /// # Unix
549 ///
550 /// Returns the value of the `TMPDIR` environment variable if it is
551 /// set, otherwise for non-Android it returns `/tmp`. If Android, since there
552 /// is no global temporary folder (it is usually allocated per-app), it returns
553 /// `/data/local/tmp`.
554 ///
555 /// # Windows
556 ///
557 /// Returns the value of, in order, the `TMP`, `TEMP`,
558 /// `USERPROFILE` environment variable if any are set and not the empty
559 /// string. Otherwise, `temp_dir` returns the path of the Windows directory.
560 /// This behavior is identical to that of [`GetTempPath`][msdn], which this
561 /// function uses internally.
562 ///
563 /// [msdn]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa364992(v=vs.85).aspx
564 ///
565 /// ```no_run
566 /// use std::env;
567 /// use std::fs::File;
568 ///
569 /// fn main() -> std::io::Result<()> {
570 ///     let mut dir = env::temp_dir();
571 ///     dir.push("foo.txt");
572 ///
573 ///     let f = File::create(dir)?;
574 ///     Ok(())
575 /// }
576 /// ```
577 #[stable(feature = "env", since = "1.0.0")]
578 pub fn temp_dir() -> PathBuf {
579     os_imp::temp_dir()
580 }
581
582 /// Returns the full filesystem path of the current running executable.
583 ///
584 /// # Platform-specific behavior
585 ///
586 /// If the executable was invoked through a symbolic link, some platforms will
587 /// return the path of the symbolic link and other platforms will return the
588 /// path of the symbolic link’s target.
589 ///
590 /// # Errors
591 ///
592 /// Acquiring the path of the current executable is a platform-specific operation
593 /// that can fail for a good number of reasons. Some errors can include, but not
594 /// be limited to, filesystem operations failing or general syscall failures.
595 ///
596 /// # Security
597 ///
598 /// The output of this function should not be used in anything that might have
599 /// security implications. For example:
600 ///
601 /// ```
602 /// fn main() {
603 ///     println!("{:?}", std::env::current_exe());
604 /// }
605 /// ```
606 ///
607 /// On Linux systems, if this is compiled as `foo`:
608 ///
609 /// ```bash
610 /// $ rustc foo.rs
611 /// $ ./foo
612 /// Ok("/home/alex/foo")
613 /// ```
614 ///
615 /// And you make a hard link of the program:
616 ///
617 /// ```bash
618 /// $ ln foo bar
619 /// ```
620 ///
621 /// When you run it, you won’t get the path of the original executable, you’ll
622 /// get the path of the hard link:
623 ///
624 /// ```bash
625 /// $ ./bar
626 /// Ok("/home/alex/bar")
627 /// ```
628 ///
629 /// This sort of behavior has been known to [lead to privilege escalation] when
630 /// used incorrectly.
631 ///
632 /// [lead to privilege escalation]: https://securityvulns.com/Wdocument183.html
633 ///
634 /// # Examples
635 ///
636 /// ```
637 /// use std::env;
638 ///
639 /// match env::current_exe() {
640 ///     Ok(exe_path) => println!("Path of this executable is: {}",
641 ///                              exe_path.display()),
642 ///     Err(e) => println!("failed to get current exe path: {}", e),
643 /// };
644 /// ```
645 #[stable(feature = "env", since = "1.0.0")]
646 pub fn current_exe() -> io::Result<PathBuf> {
647     os_imp::current_exe()
648 }
649
650 /// An iterator over the arguments of a process, yielding a [`String`] value for
651 /// each argument.
652 ///
653 /// This struct is created by the [`std::env::args`] function. See its
654 /// documentation for more.
655 ///
656 /// The first element is traditionally the path of the executable, but it can be
657 /// set to arbitrary text, and may not even exist. This means this property
658 /// should not be relied upon for security purposes.
659 ///
660 /// [`String`]: ../string/struct.String.html
661 /// [`std::env::args`]: ./fn.args.html
662 #[stable(feature = "env", since = "1.0.0")]
663 pub struct Args { inner: ArgsOs }
664
665 /// An iterator over the arguments of a process, yielding an [`OsString`] value
666 /// for each argument.
667 ///
668 /// This struct is created by the [`std::env::args_os`] function. See its
669 /// documentation for more.
670 ///
671 /// The first element is traditionally the path of the executable, but it can be
672 /// set to arbitrary text, and may not even exist. This means this property
673 /// should not be relied upon for security purposes.
674 ///
675 /// [`OsString`]: ../ffi/struct.OsString.html
676 /// [`std::env::args_os`]: ./fn.args_os.html
677 #[stable(feature = "env", since = "1.0.0")]
678 pub struct ArgsOs { inner: sys::args::Args }
679
680 /// Returns the arguments which this program was started with (normally passed
681 /// via the command line).
682 ///
683 /// The first element is traditionally the path of the executable, but it can be
684 /// set to arbitrary text, and may not even exist. This means this property should
685 /// not be relied upon for security purposes.
686 ///
687 /// On Unix systems shell usually expands unquoted arguments with glob patterns
688 /// (such as `*` and `?`). On Windows this is not done, and such arguments are
689 /// passed as-is.
690 ///
691 /// # Panics
692 ///
693 /// The returned iterator will panic during iteration if any argument to the
694 /// process is not valid unicode. If this is not desired,
695 /// use the [`args_os`] function instead.
696 ///
697 /// # Examples
698 ///
699 /// ```
700 /// use std::env;
701 ///
702 /// // Prints each argument on a separate line
703 /// for argument in env::args() {
704 ///     println!("{}", argument);
705 /// }
706 /// ```
707 ///
708 /// [`args_os`]: ./fn.args_os.html
709 #[stable(feature = "env", since = "1.0.0")]
710 pub fn args() -> Args {
711     Args { inner: args_os() }
712 }
713
714 /// Returns the arguments which this program was started with (normally passed
715 /// via the command line).
716 ///
717 /// The first element is traditionally the path of the executable, but it can be
718 /// set to arbitrary text, and it may not even exist, so this property should
719 /// not be relied upon for security purposes.
720 ///
721 /// # Examples
722 ///
723 /// ```
724 /// use std::env;
725 ///
726 /// // Prints each argument on a separate line
727 /// for argument in env::args_os() {
728 ///     println!("{:?}", argument);
729 /// }
730 /// ```
731 #[stable(feature = "env", since = "1.0.0")]
732 pub fn args_os() -> ArgsOs {
733     ArgsOs { inner: sys::args::args() }
734 }
735
736 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
737 impl !Send for Args {}
738
739 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
740 impl !Sync for Args {}
741
742 #[stable(feature = "env", since = "1.0.0")]
743 impl Iterator for Args {
744     type Item = String;
745     fn next(&mut self) -> Option<String> {
746         self.inner.next().map(|s| s.into_string().unwrap())
747     }
748     fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
749     #[inline]
750     fn last(mut self) -> Option<String> {
751         self.next_back()
752     }
753 }
754
755 #[stable(feature = "env", since = "1.0.0")]
756 impl ExactSizeIterator for Args {
757     fn len(&self) -> usize { self.inner.len() }
758     fn is_empty(&self) -> bool { self.inner.is_empty() }
759 }
760
761 #[stable(feature = "env_iterators", since = "1.12.0")]
762 impl DoubleEndedIterator for Args {
763     fn next_back(&mut self) -> Option<String> {
764         self.inner.next_back().map(|s| s.into_string().unwrap())
765     }
766 }
767
768 #[stable(feature = "std_debug", since = "1.16.0")]
769 impl fmt::Debug for Args {
770     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
771         f.debug_struct("Args")
772             .field("inner", &self.inner.inner.inner_debug())
773             .finish()
774     }
775 }
776
777 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
778 impl !Send for ArgsOs {}
779
780 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
781 impl !Sync for ArgsOs {}
782
783 #[stable(feature = "env", since = "1.0.0")]
784 impl Iterator for ArgsOs {
785     type Item = OsString;
786     fn next(&mut self) -> Option<OsString> { self.inner.next() }
787     fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
788     #[inline]
789     fn last(mut self) -> Option<OsString> { self.next_back() }
790 }
791
792 #[stable(feature = "env", since = "1.0.0")]
793 impl ExactSizeIterator for ArgsOs {
794     fn len(&self) -> usize { self.inner.len() }
795     fn is_empty(&self) -> bool { self.inner.is_empty() }
796 }
797
798 #[stable(feature = "env_iterators", since = "1.12.0")]
799 impl DoubleEndedIterator for ArgsOs {
800     fn next_back(&mut self) -> Option<OsString> { self.inner.next_back() }
801 }
802
803 #[stable(feature = "std_debug", since = "1.16.0")]
804 impl fmt::Debug for ArgsOs {
805     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
806         f.debug_struct("ArgsOs")
807             .field("inner", &self.inner.inner_debug())
808             .finish()
809     }
810 }
811
812 /// Constants associated with the current target
813 #[stable(feature = "env", since = "1.0.0")]
814 pub mod consts {
815     use crate::sys::env::os;
816
817     /// A string describing the architecture of the CPU that is currently
818     /// in use.
819     ///
820     /// Some possible values:
821     ///
822     /// - x86
823     /// - x86_64
824     /// - arm
825     /// - aarch64
826     /// - mips
827     /// - mips64
828     /// - powerpc
829     /// - powerpc64
830     /// - s390x
831     /// - sparc64
832     #[stable(feature = "env", since = "1.0.0")]
833     pub const ARCH: &str = super::arch::ARCH;
834
835     /// The family of the operating system. Example value is `unix`.
836     ///
837     /// Some possible values:
838     ///
839     /// - unix
840     /// - windows
841     #[stable(feature = "env", since = "1.0.0")]
842     pub const FAMILY: &str = os::FAMILY;
843
844     /// A string describing the specific operating system in use.
845     /// Example value is `linux`.
846     ///
847     /// Some possible values:
848     ///
849     /// - linux
850     /// - macos
851     /// - ios
852     /// - freebsd
853     /// - dragonfly
854     /// - netbsd
855     /// - openbsd
856     /// - solaris
857     /// - android
858     /// - windows
859     #[stable(feature = "env", since = "1.0.0")]
860     pub const OS: &str = os::OS;
861
862     /// Specifies the filename prefix used for shared libraries on this
863     /// platform. Example value is `lib`.
864     ///
865     /// Some possible values:
866     ///
867     /// - lib
868     /// - `""` (an empty string)
869     #[stable(feature = "env", since = "1.0.0")]
870     pub const DLL_PREFIX: &str = os::DLL_PREFIX;
871
872     /// Specifies the filename suffix used for shared libraries on this
873     /// platform. Example value is `.so`.
874     ///
875     /// Some possible values:
876     ///
877     /// - .so
878     /// - .dylib
879     /// - .dll
880     #[stable(feature = "env", since = "1.0.0")]
881     pub const DLL_SUFFIX: &str = os::DLL_SUFFIX;
882
883     /// Specifies the file extension used for shared libraries on this
884     /// platform that goes after the dot. Example value is `so`.
885     ///
886     /// Some possible values:
887     ///
888     /// - so
889     /// - dylib
890     /// - dll
891     #[stable(feature = "env", since = "1.0.0")]
892     pub const DLL_EXTENSION: &str = os::DLL_EXTENSION;
893
894     /// Specifies the filename suffix used for executable binaries on this
895     /// platform. Example value is `.exe`.
896     ///
897     /// Some possible values:
898     ///
899     /// - .exe
900     /// - .nexe
901     /// - .pexe
902     /// - `""` (an empty string)
903     #[stable(feature = "env", since = "1.0.0")]
904     pub const EXE_SUFFIX: &str = os::EXE_SUFFIX;
905
906     /// Specifies the file extension, if any, used for executable binaries
907     /// on this platform. Example value is `exe`.
908     ///
909     /// Some possible values:
910     ///
911     /// - exe
912     /// - `""` (an empty string)
913     #[stable(feature = "env", since = "1.0.0")]
914     pub const EXE_EXTENSION: &str = os::EXE_EXTENSION;
915 }
916
917 #[cfg(target_arch = "x86")]
918 mod arch {
919     pub const ARCH: &str = "x86";
920 }
921
922 #[cfg(target_arch = "x86_64")]
923 mod arch {
924     pub const ARCH: &str = "x86_64";
925 }
926
927 #[cfg(target_arch = "arm")]
928 mod arch {
929     pub const ARCH: &str = "arm";
930 }
931
932 #[cfg(target_arch = "aarch64")]
933 mod arch {
934     pub const ARCH: &str = "aarch64";
935 }
936
937 #[cfg(target_arch = "mips")]
938 mod arch {
939     pub const ARCH: &str = "mips";
940 }
941
942 #[cfg(target_arch = "mips64")]
943 mod arch {
944     pub const ARCH: &str = "mips64";
945 }
946
947 #[cfg(target_arch = "powerpc")]
948 mod arch {
949     pub const ARCH: &str = "powerpc";
950 }
951
952 #[cfg(target_arch = "powerpc64")]
953 mod arch {
954     pub const ARCH: &str = "powerpc64";
955 }
956
957 #[cfg(target_arch = "s390x")]
958 mod arch {
959     pub const ARCH: &str = "s390x";
960 }
961
962 #[cfg(target_arch = "sparc64")]
963 mod arch {
964     pub const ARCH: &str = "sparc64";
965 }
966
967 #[cfg(target_arch = "le32")]
968 mod arch {
969     pub const ARCH: &str = "le32";
970 }
971
972 #[cfg(target_arch = "asmjs")]
973 mod arch {
974     pub const ARCH: &str = "asmjs";
975 }
976
977 #[cfg(target_arch = "wasm32")]
978 mod arch {
979     pub const ARCH: &str = "wasm32";
980 }
981
982 #[cfg(test)]
983 mod tests {
984     use super::*;
985
986     use crate::path::Path;
987
988     #[test]
989     #[cfg_attr(any(target_os = "emscripten", target_env = "sgx"), ignore)]
990     fn test_self_exe_path() {
991         let path = current_exe();
992         assert!(path.is_ok());
993         let path = path.unwrap();
994
995         // Hard to test this function
996         assert!(path.is_absolute());
997     }
998
999     #[test]
1000     fn test() {
1001         assert!((!Path::new("test-path").is_absolute()));
1002
1003         #[cfg(not(target_env = "sgx"))]
1004         current_dir().unwrap();
1005     }
1006
1007     #[test]
1008     #[cfg(windows)]
1009     fn split_paths_windows() {
1010         use crate::path::PathBuf;
1011
1012         fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1013             split_paths(unparsed).collect::<Vec<_>>() ==
1014                 parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
1015         }
1016
1017         assert!(check_parse("", &mut [""]));
1018         assert!(check_parse(r#""""#, &mut [""]));
1019         assert!(check_parse(";;", &mut ["", "", ""]));
1020         assert!(check_parse(r"c:\", &mut [r"c:\"]));
1021         assert!(check_parse(r"c:\;", &mut [r"c:\", ""]));
1022         assert!(check_parse(r"c:\;c:\Program Files\",
1023                             &mut [r"c:\", r"c:\Program Files\"]));
1024         assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
1025         assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
1026                             &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
1027     }
1028
1029     #[test]
1030     #[cfg(unix)]
1031     fn split_paths_unix() {
1032         use crate::path::PathBuf;
1033
1034         fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1035             split_paths(unparsed).collect::<Vec<_>>() ==
1036                 parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
1037         }
1038
1039         assert!(check_parse("", &mut [""]));
1040         assert!(check_parse("::", &mut ["", "", ""]));
1041         assert!(check_parse("/", &mut ["/"]));
1042         assert!(check_parse("/:", &mut ["/", ""]));
1043         assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
1044     }
1045
1046     #[test]
1047     #[cfg(unix)]
1048     fn join_paths_unix() {
1049         use crate::ffi::OsStr;
1050
1051         fn test_eq(input: &[&str], output: &str) -> bool {
1052             &*join_paths(input.iter().cloned()).unwrap() ==
1053                 OsStr::new(output)
1054         }
1055
1056         assert!(test_eq(&[], ""));
1057         assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"],
1058                          "/bin:/usr/bin:/usr/local/bin"));
1059         assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""],
1060                          ":/bin:::/usr/bin:"));
1061         assert!(join_paths(["/te:st"].iter().cloned()).is_err());
1062     }
1063
1064     #[test]
1065     #[cfg(windows)]
1066     fn join_paths_windows() {
1067         use crate::ffi::OsStr;
1068
1069         fn test_eq(input: &[&str], output: &str) -> bool {
1070             &*join_paths(input.iter().cloned()).unwrap() ==
1071                 OsStr::new(output)
1072         }
1073
1074         assert!(test_eq(&[], ""));
1075         assert!(test_eq(&[r"c:\windows", r"c:\"],
1076                         r"c:\windows;c:\"));
1077         assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""],
1078                         r";c:\windows;;;c:\;"));
1079         assert!(test_eq(&[r"c:\te;st", r"c:\"],
1080                         r#""c:\te;st";c:\"#));
1081         assert!(join_paths([r#"c:\te"st"#].iter().cloned()).is_err());
1082     }
1083
1084     #[test]
1085     fn args_debug() {
1086         assert_eq!(
1087             format!("Args {{ inner: {:?} }}", args().collect::<Vec<_>>()),
1088             format!("{:?}", args()));
1089         assert_eq!(
1090             format!("ArgsOs {{ inner: {:?} }}", args_os().collect::<Vec<_>>()),
1091             format!("{:?}", args_os()));
1092     }
1093 }