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