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