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