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