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