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