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.
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.
11 //! Inspection and manipulation of the process's environment.
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.
17 #![stable(feature = "env", since = "1.0.0")]
22 use ffi
::{OsStr, OsString}
;
25 use path
::{Path, PathBuf}
;
26 use sys
::os
as os_imp
;
28 /// Returns the current working directory as a `PathBuf`.
32 /// Returns an `Err` if the current working directory value is invalid.
35 /// * Current directory does not exist.
36 /// * There are insufficient permissions to access the current directory.
43 /// // We assume that we are in a valid directory.
44 /// let p = env::current_dir().unwrap();
45 /// println!("The current directory is {}", p.display());
47 #[stable(feature = "env", since = "1.0.0")]
48 pub fn current_dir() -> io
::Result
<PathBuf
> {
52 /// Changes the current working directory to the specified path, returning
53 /// whether the change was completed successfully or not.
59 /// use std::path::Path;
61 /// let root = Path::new("/");
62 /// assert!(env::set_current_dir(&root).is_ok());
63 /// println!("Successfully changed working directory to {}!", root.display());
65 #[stable(feature = "env", since = "1.0.0")]
66 pub fn set_current_dir
<P
: AsRef
<Path
>>(p
: P
) -> io
::Result
<()> {
67 os_imp
::chdir(p
.as_ref())
70 /// An iterator over a snapshot of the environment variables of this process.
72 /// This iterator is created through `std::env::vars()` and yields `(String,
74 #[stable(feature = "env", since = "1.0.0")]
75 pub struct Vars { inner: VarsOs }
77 /// An iterator over a snapshot of the environment variables of this process.
79 /// This iterator is created through `std::env::vars_os()` and yields
80 /// `(OsString, OsString)` pairs.
81 #[stable(feature = "env", since = "1.0.0")]
82 pub struct VarsOs { inner: os_imp::Env }
84 /// Returns an iterator of (variable, value) pairs of strings, for all the
85 /// environment variables of the current process.
87 /// The returned iterator contains a snapshot of the process's environment
88 /// variables at the time of this invocation, modifications to environment
89 /// variables afterwards will not be reflected in the returned iterator.
93 /// While iterating, the returned iterator will panic if any key or value in the
94 /// environment is not valid unicode. If this is not desired, consider using the
95 /// `env::vars_os` function.
102 /// // We will iterate through the references to the element returned by
104 /// for (key, value) in env::vars() {
105 /// println!("{}: {}", key, value);
108 #[stable(feature = "env", since = "1.0.0")]
109 pub fn vars() -> Vars
{
110 Vars { inner: vars_os() }
113 /// Returns an iterator of (variable, value) pairs of OS strings, for all the
114 /// environment variables of the current process.
116 /// The returned iterator contains a snapshot of the process's environment
117 /// variables at the time of this invocation, modifications to environment
118 /// variables afterwards will not be reflected in the returned iterator.
125 /// // We will iterate through the references to the element returned by
126 /// // env::vars_os();
127 /// for (key, value) in env::vars_os() {
128 /// println!("{:?}: {:?}", key, value);
131 #[stable(feature = "env", since = "1.0.0")]
132 pub fn vars_os() -> VarsOs
{
133 VarsOs { inner: os_imp::env() }
136 #[stable(feature = "env", since = "1.0.0")]
137 impl Iterator
for Vars
{
138 type Item
= (String
, String
);
139 fn next(&mut self) -> Option
<(String
, String
)> {
140 self.inner
.next().map(|(a
, b
)| {
141 (a
.into_string().unwrap(), b
.into_string().unwrap())
144 fn size_hint(&self) -> (usize, Option
<usize>) { self.inner.size_hint() }
147 #[stable(feature = "env", since = "1.0.0")]
148 impl Iterator
for VarsOs
{
149 type Item
= (OsString
, OsString
);
150 fn next(&mut self) -> Option
<(OsString
, OsString
)> { self.inner.next() }
151 fn size_hint(&self) -> (usize, Option
<usize>) { self.inner.size_hint() }
154 /// Fetches the environment variable `key` from the current process.
156 /// The returned result is `Ok(s)` if the environment variable is present and is
157 /// valid unicode. If the environment variable is not present, or it is not
158 /// valid unicode, then `Err` will be returned.
165 /// let key = "HOME";
166 /// match env::var(key) {
167 /// Ok(val) => println!("{}: {:?}", key, val),
168 /// Err(e) => println!("couldn't interpret {}: {}", key, e),
171 #[stable(feature = "env", since = "1.0.0")]
172 pub fn var
<K
: AsRef
<OsStr
>>(key
: K
) -> Result
<String
, VarError
> {
176 fn _var(key
: &OsStr
) -> Result
<String
, VarError
> {
178 Some(s
) => s
.into_string().map_err(VarError
::NotUnicode
),
179 None
=> Err(VarError
::NotPresent
)
183 /// Fetches the environment variable `key` from the current process, returning
184 /// `None` if the variable isn't set.
191 /// let key = "HOME";
192 /// match env::var_os(key) {
193 /// Some(val) => println!("{}: {:?}", key, val),
194 /// None => println!("{} is not defined in the environment.", key)
197 #[stable(feature = "env", since = "1.0.0")]
198 pub fn var_os
<K
: AsRef
<OsStr
>>(key
: K
) -> Option
<OsString
> {
199 _var_os(key
.as_ref())
202 fn _var_os(key
: &OsStr
) -> Option
<OsString
> {
203 os_imp
::getenv(key
).unwrap_or_else(|e
| {
204 panic
!("failed to get environment variable `{:?}`: {}", key
, e
)
208 /// Possible errors from the `env::var` method.
209 #[derive(Debug, PartialEq, Eq, Clone)]
210 #[stable(feature = "env", since = "1.0.0")]
212 /// The specified environment variable was not present in the current
213 /// process's environment.
214 #[stable(feature = "env", since = "1.0.0")]
217 /// The specified environment variable was found, but it did not contain
218 /// valid unicode data. The found data is returned as a payload of this
220 #[stable(feature = "env", since = "1.0.0")]
221 NotUnicode(#[stable(feature = "env", since = "1.0.0")] OsString),
224 #[stable(feature = "env", since = "1.0.0")]
225 impl fmt
::Display
for VarError
{
226 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
228 VarError
::NotPresent
=> write
!(f
, "environment variable not found"),
229 VarError
::NotUnicode(ref s
) => {
230 write
!(f
, "environment variable was not valid unicode: {:?}", s
)
236 #[stable(feature = "env", since = "1.0.0")]
237 impl Error
for VarError
{
238 fn description(&self) -> &str {
240 VarError
::NotPresent
=> "environment variable not found",
241 VarError
::NotUnicode(..) => "environment variable was not valid unicode",
246 /// Sets the environment variable `k` to the value `v` for the currently running
249 /// Note that while concurrent access to environment variables is safe in Rust,
250 /// some platforms only expose inherently unsafe non-threadsafe APIs for
251 /// inspecting the environment. As a result extra care needs to be taken when
252 /// auditing calls to unsafe external FFI functions to ensure that any external
253 /// environment accesses are properly synchronized with accesses in Rust.
255 /// Discussion of this unsafety on Unix may be found in:
257 /// - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188)
258 /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
262 /// This function may panic if `key` is empty, contains an ASCII equals sign
263 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
272 /// env::set_var(key, "VALUE");
273 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
275 #[stable(feature = "env", since = "1.0.0")]
276 pub fn set_var
<K
: AsRef
<OsStr
>, V
: AsRef
<OsStr
>>(k
: K
, v
: V
) {
277 _set_var(k
.as_ref(), v
.as_ref())
280 fn _set_var(k
: &OsStr
, v
: &OsStr
) {
281 os_imp
::setenv(k
, v
).unwrap_or_else(|e
| {
282 panic
!("failed to set environment variable `{:?}` to `{:?}`: {}",
287 /// Removes an environment variable from the environment of the currently running process.
289 /// Note that while concurrent access to environment variables is safe in Rust,
290 /// some platforms only expose inherently unsafe non-threadsafe APIs for
291 /// inspecting the environment. As a result extra care needs to be taken when
292 /// auditing calls to unsafe external FFI functions to ensure that any external
293 /// environment accesses are properly synchronized with accesses in Rust.
295 /// Discussion of this unsafety on Unix may be found in:
297 /// - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188)
298 /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
302 /// This function may panic if `key` is empty, contains an ASCII equals sign
303 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
312 /// env::set_var(key, "VALUE");
313 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
315 /// env::remove_var(key);
316 /// assert!(env::var(key).is_err());
318 #[stable(feature = "env", since = "1.0.0")]
319 pub fn remove_var
<K
: AsRef
<OsStr
>>(k
: K
) {
320 _remove_var(k
.as_ref())
323 fn _remove_var(k
: &OsStr
) {
324 os_imp
::unsetenv(k
).unwrap_or_else(|e
| {
325 panic
!("failed to remove environment variable `{:?}`: {}", k
, e
)
329 /// An iterator over `PathBuf` instances for parsing an environment variable
330 /// according to platform-specific conventions.
332 /// This structure is returned from `std::env::split_paths`.
333 #[stable(feature = "env", since = "1.0.0")]
334 pub struct SplitPaths
<'a
> { inner: os_imp::SplitPaths<'a> }
336 /// Parses input according to platform conventions for the `PATH`
337 /// environment variable.
339 /// Returns an iterator over the paths contained in `unparsed`.
346 /// let key = "PATH";
347 /// match env::var_os(key) {
349 /// for path in env::split_paths(&paths) {
350 /// println!("'{}'", path.display());
353 /// None => println!("{} is not defined in the environment.", key)
356 #[stable(feature = "env", since = "1.0.0")]
357 pub fn split_paths
<T
: AsRef
<OsStr
> + ?Sized
>(unparsed
: &T
) -> SplitPaths
{
358 SplitPaths { inner: os_imp::split_paths(unparsed.as_ref()) }
361 #[stable(feature = "env", since = "1.0.0")]
362 impl<'a
> Iterator
for SplitPaths
<'a
> {
364 fn next(&mut self) -> Option
<PathBuf
> { self.inner.next() }
365 fn size_hint(&self) -> (usize, Option
<usize>) { self.inner.size_hint() }
368 /// Error type returned from `std::env::join_paths` when paths fail to be
371 #[stable(feature = "env", since = "1.0.0")]
372 pub struct JoinPathsError
{
373 inner
: os_imp
::JoinPathsError
376 /// Joins a collection of `Path`s appropriately for the `PATH`
377 /// environment variable.
379 /// Returns an `OsString` on success.
381 /// Returns an `Err` (containing an error message) if one of the input
382 /// `Path`s contains an invalid character for constructing the `PATH`
383 /// variable (a double quote on Windows or a colon on Unix).
389 /// use std::path::PathBuf;
391 /// if let Some(path) = env::var_os("PATH") {
392 /// let mut paths = env::split_paths(&path).collect::<Vec<_>>();
393 /// paths.push(PathBuf::from("/home/xyz/bin"));
394 /// let new_path = env::join_paths(paths).unwrap();
395 /// env::set_var("PATH", &new_path);
398 #[stable(feature = "env", since = "1.0.0")]
399 pub fn join_paths
<I
, T
>(paths
: I
) -> Result
<OsString
, JoinPathsError
>
400 where I
: IntoIterator
<Item
=T
>, T
: AsRef
<OsStr
>
402 os_imp
::join_paths(paths
.into_iter()).map_err(|e
| {
403 JoinPathsError { inner: e }
407 #[stable(feature = "env", since = "1.0.0")]
408 impl fmt
::Display
for JoinPathsError
{
409 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
414 #[stable(feature = "env", since = "1.0.0")]
415 impl Error
for JoinPathsError
{
416 fn description(&self) -> &str { self.inner.description() }
419 /// Returns the path of the current user's home directory if known.
423 /// Returns the value of the 'HOME' environment variable if it is set
424 /// and not equal to the empty string. Otherwise, it tries to determine the
425 /// home directory by invoking the `getpwuid_r` function on the UID of the
430 /// Returns the value of the 'HOME' environment variable if it is
431 /// set and not equal to the empty string. Otherwise, returns the value of the
432 /// 'USERPROFILE' environment variable if it is set and not equal to the empty
433 /// string. If both do not exist, [`GetUserProfileDirectory`][msdn] is used to
434 /// return the appropriate path.
436 /// [msdn]: https://msdn.microsoft.com/en-us/library/windows/desktop/bb762280(v=vs.85).aspx
443 /// match env::home_dir() {
444 /// Some(path) => println!("{}", path.display()),
445 /// None => println!("Impossible to get your home dir!"),
448 #[stable(feature = "env", since = "1.0.0")]
449 pub fn home_dir() -> Option
<PathBuf
> {
453 /// Returns the path of a temporary directory.
455 /// On Unix, returns the value of the 'TMPDIR' environment variable if it is
456 /// set, otherwise for non-Android it returns '/tmp'. If Android, since there
457 /// is no global temporary folder (it is usually allocated per-app), we return
458 /// '/data/local/tmp'.
460 /// On Windows, returns the value of, in order, the 'TMP', 'TEMP',
461 /// 'USERPROFILE' environment variable if any are set and not the empty
462 /// string. Otherwise, tmpdir returns the path of the Windows directory. This
463 /// behavior is identical to that of [GetTempPath][msdn], which this function
466 /// [msdn]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa364992(v=vs.85).aspx
470 /// use std::fs::File;
472 /// # fn foo() -> std::io::Result<()> {
473 /// let mut dir = env::temp_dir();
474 /// dir.push("foo.txt");
476 /// let f = try!(File::create(dir));
480 #[stable(feature = "env", since = "1.0.0")]
481 pub fn temp_dir() -> PathBuf
{
485 /// Returns the full filesystem path of the current running executable.
487 /// The path returned is not necessarily a "real path" of the executable as
488 /// there may be intermediate symlinks.
492 /// Acquiring the path of the current executable is a platform-specific operation
493 /// that can fail for a good number of reasons. Some errors can include, but not
494 /// be limited to, filesystem operations failing or general syscall failures.
501 /// match env::current_exe() {
502 /// Ok(exe_path) => println!("Path of this executable is: {}",
503 /// exe_path.display()),
504 /// Err(e) => println!("failed to get current exe path: {}", e),
507 #[stable(feature = "env", since = "1.0.0")]
508 pub fn current_exe() -> io
::Result
<PathBuf
> {
509 os_imp
::current_exe()
512 /// An iterator over the arguments of a process, yielding a `String` value
513 /// for each argument.
515 /// This structure is created through the `std::env::args` method.
516 #[stable(feature = "env", since = "1.0.0")]
517 pub struct Args { inner: ArgsOs }
519 /// An iterator over the arguments of a process, yielding an `OsString` value
520 /// for each argument.
522 /// This structure is created through the `std::env::args_os` method.
523 #[stable(feature = "env", since = "1.0.0")]
524 pub struct ArgsOs { inner: os_imp::Args }
526 /// Returns the arguments which this program was started with (normally passed
527 /// via the command line).
529 /// The first element is traditionally the path of the executable, but it can be
530 /// set to arbitrary text, and may not even exist. This means this property should
531 /// not be relied upon for security purposes.
535 /// The returned iterator will panic during iteration if any argument to the
536 /// process is not valid unicode. If this is not desired,
537 /// use the `args_os` function instead.
544 /// // Prints each argument on a separate line
545 /// for argument in env::args() {
546 /// println!("{}", argument);
549 #[stable(feature = "env", since = "1.0.0")]
550 pub fn args() -> Args
{
551 Args { inner: args_os() }
554 /// Returns the arguments which this program was started with (normally passed
555 /// via the command line).
557 /// The first element is traditionally the path of the executable, but it can be
558 /// set to arbitrary text, and it may not even exist, so this property should
559 /// not be relied upon for security purposes.
566 /// // Prints each argument on a separate line
567 /// for argument in env::args_os() {
568 /// println!("{:?}", argument);
571 #[stable(feature = "env", since = "1.0.0")]
572 pub fn args_os() -> ArgsOs
{
573 ArgsOs { inner: os_imp::args() }
576 #[stable(feature = "env", since = "1.0.0")]
577 impl Iterator
for Args
{
579 fn next(&mut self) -> Option
<String
> {
580 self.inner
.next().map(|s
| s
.into_string().unwrap())
582 fn size_hint(&self) -> (usize, Option
<usize>) { self.inner.size_hint() }
585 #[stable(feature = "env", since = "1.0.0")]
586 impl ExactSizeIterator
for Args
{
587 fn len(&self) -> usize { self.inner.len() }
590 #[stable(feature = "env", since = "1.0.0")]
591 impl Iterator
for ArgsOs
{
592 type Item
= OsString
;
593 fn next(&mut self) -> Option
<OsString
> { self.inner.next() }
594 fn size_hint(&self) -> (usize, Option
<usize>) { self.inner.size_hint() }
597 #[stable(feature = "env", since = "1.0.0")]
598 impl ExactSizeIterator
for ArgsOs
{
599 fn len(&self) -> usize { self.inner.len() }
602 /// Constants associated with the current target
603 #[stable(feature = "env", since = "1.0.0")]
605 /// A string describing the architecture of the CPU that is currently
608 /// Some possible values:
617 #[stable(feature = "env", since = "1.0.0")]
618 pub const ARCH
: &'
static str = super::arch
::ARCH
;
620 /// The family of the operating system. Example value is `unix`.
622 /// Some possible values:
626 #[stable(feature = "env", since = "1.0.0")]
627 pub const FAMILY
: &'
static str = super::os
::FAMILY
;
629 /// A string describing the specific operating system in use.
630 /// Example value is `linux`.
632 /// Some possible values:
645 #[stable(feature = "env", since = "1.0.0")]
646 pub const OS
: &'
static str = super::os
::OS
;
648 /// Specifies the filename prefix used for shared libraries on this
649 /// platform. Example value is `lib`.
651 /// Some possible values:
654 /// - `""` (an empty string)
655 #[stable(feature = "env", since = "1.0.0")]
656 pub const DLL_PREFIX
: &'
static str = super::os
::DLL_PREFIX
;
658 /// Specifies the filename suffix used for shared libraries on this
659 /// platform. Example value is `.so`.
661 /// Some possible values:
666 #[stable(feature = "env", since = "1.0.0")]
667 pub const DLL_SUFFIX
: &'
static str = super::os
::DLL_SUFFIX
;
669 /// Specifies the file extension used for shared libraries on this
670 /// platform that goes after the dot. Example value is `so`.
672 /// Some possible values:
677 #[stable(feature = "env", since = "1.0.0")]
678 pub const DLL_EXTENSION
: &'
static str = super::os
::DLL_EXTENSION
;
680 /// Specifies the filename suffix used for executable binaries on this
681 /// platform. Example value is `.exe`.
683 /// Some possible values:
688 /// - `""` (an empty string)
689 #[stable(feature = "env", since = "1.0.0")]
690 pub const EXE_SUFFIX
: &'
static str = super::os
::EXE_SUFFIX
;
692 /// Specifies the file extension, if any, used for executable binaries
693 /// on this platform. Example value is `exe`.
695 /// Some possible values:
698 /// - `""` (an empty string)
699 #[stable(feature = "env", since = "1.0.0")]
700 pub const EXE_EXTENSION
: &'
static str = super::os
::EXE_EXTENSION
;
704 #[cfg(target_os = "linux")]
706 pub const FAMILY
: &'
static str = "unix";
707 pub const OS
: &'
static str = "linux";
708 pub const DLL_PREFIX
: &'
static str = "lib";
709 pub const DLL_SUFFIX
: &'
static str = ".so";
710 pub const DLL_EXTENSION
: &'
static str = "so";
711 pub const EXE_SUFFIX
: &'
static str = "";
712 pub const EXE_EXTENSION
: &'
static str = "";
715 #[cfg(target_os = "macos")]
717 pub const FAMILY
: &'
static str = "unix";
718 pub const OS
: &'
static str = "macos";
719 pub const DLL_PREFIX
: &'
static str = "lib";
720 pub const DLL_SUFFIX
: &'
static str = ".dylib";
721 pub const DLL_EXTENSION
: &'
static str = "dylib";
722 pub const EXE_SUFFIX
: &'
static str = "";
723 pub const EXE_EXTENSION
: &'
static str = "";
726 #[cfg(target_os = "ios")]
728 pub const FAMILY
: &'
static str = "unix";
729 pub const OS
: &'
static str = "ios";
730 pub const DLL_PREFIX
: &'
static str = "lib";
731 pub const DLL_SUFFIX
: &'
static str = ".dylib";
732 pub const DLL_EXTENSION
: &'
static str = "dylib";
733 pub const EXE_SUFFIX
: &'
static str = "";
734 pub const EXE_EXTENSION
: &'
static str = "";
737 #[cfg(target_os = "freebsd")]
739 pub const FAMILY
: &'
static str = "unix";
740 pub const OS
: &'
static str = "freebsd";
741 pub const DLL_PREFIX
: &'
static str = "lib";
742 pub const DLL_SUFFIX
: &'
static str = ".so";
743 pub const DLL_EXTENSION
: &'
static str = "so";
744 pub const EXE_SUFFIX
: &'
static str = "";
745 pub const EXE_EXTENSION
: &'
static str = "";
748 #[cfg(target_os = "dragonfly")]
750 pub const FAMILY
: &'
static str = "unix";
751 pub const OS
: &'
static str = "dragonfly";
752 pub const DLL_PREFIX
: &'
static str = "lib";
753 pub const DLL_SUFFIX
: &'
static str = ".so";
754 pub const DLL_EXTENSION
: &'
static str = "so";
755 pub const EXE_SUFFIX
: &'
static str = "";
756 pub const EXE_EXTENSION
: &'
static str = "";
759 #[cfg(target_os = "bitrig")]
761 pub const FAMILY
: &'
static str = "unix";
762 pub const OS
: &'
static str = "bitrig";
763 pub const DLL_PREFIX
: &'
static str = "lib";
764 pub const DLL_SUFFIX
: &'
static str = ".so";
765 pub const DLL_EXTENSION
: &'
static str = "so";
766 pub const EXE_SUFFIX
: &'
static str = "";
767 pub const EXE_EXTENSION
: &'
static str = "";
770 #[cfg(target_os = "netbsd")]
772 pub const FAMILY
: &'
static str = "unix";
773 pub const OS
: &'
static str = "netbsd";
774 pub const DLL_PREFIX
: &'
static str = "lib";
775 pub const DLL_SUFFIX
: &'
static str = ".so";
776 pub const DLL_EXTENSION
: &'
static str = "so";
777 pub const EXE_SUFFIX
: &'
static str = "";
778 pub const EXE_EXTENSION
: &'
static str = "";
781 #[cfg(target_os = "openbsd")]
783 pub const FAMILY
: &'
static str = "unix";
784 pub const OS
: &'
static str = "openbsd";
785 pub const DLL_PREFIX
: &'
static str = "lib";
786 pub const DLL_SUFFIX
: &'
static str = ".so";
787 pub const DLL_EXTENSION
: &'
static str = "so";
788 pub const EXE_SUFFIX
: &'
static str = "";
789 pub const EXE_EXTENSION
: &'
static str = "";
792 #[cfg(target_os = "android")]
794 pub const FAMILY
: &'
static str = "unix";
795 pub const OS
: &'
static str = "android";
796 pub const DLL_PREFIX
: &'
static str = "lib";
797 pub const DLL_SUFFIX
: &'
static str = ".so";
798 pub const DLL_EXTENSION
: &'
static str = "so";
799 pub const EXE_SUFFIX
: &'
static str = "";
800 pub const EXE_EXTENSION
: &'
static str = "";
803 #[cfg(target_os = "solaris")]
805 pub const FAMILY
: &'
static str = "unix";
806 pub const OS
: &'
static str = "solaris";
807 pub const DLL_PREFIX
: &'
static str = "lib";
808 pub const DLL_SUFFIX
: &'
static str = ".so";
809 pub const DLL_EXTENSION
: &'
static str = "so";
810 pub const EXE_SUFFIX
: &'
static str = "";
811 pub const EXE_EXTENSION
: &'
static str = "";
814 #[cfg(target_os = "windows")]
816 pub const FAMILY
: &'
static str = "windows";
817 pub const OS
: &'
static str = "windows";
818 pub const DLL_PREFIX
: &'
static str = "";
819 pub const DLL_SUFFIX
: &'
static str = ".dll";
820 pub const DLL_EXTENSION
: &'
static str = "dll";
821 pub const EXE_SUFFIX
: &'
static str = ".exe";
822 pub const EXE_EXTENSION
: &'
static str = "exe";
825 #[cfg(all(target_os = "nacl", not(target_arch = "le32")))]
827 pub const FAMILY
: &'
static str = "unix";
828 pub const OS
: &'
static str = "nacl";
829 pub const DLL_PREFIX
: &'
static str = "lib";
830 pub const DLL_SUFFIX
: &'
static str = ".so";
831 pub const DLL_EXTENSION
: &'
static str = "so";
832 pub const EXE_SUFFIX
: &'
static str = ".nexe";
833 pub const EXE_EXTENSION
: &'
static str = "nexe";
835 #[cfg(all(target_os = "nacl", target_arch = "le32"))]
837 pub const FAMILY
: &'
static str = "unix";
838 pub const OS
: &'
static str = "pnacl";
839 pub const DLL_PREFIX
: &'
static str = "lib";
840 pub const DLL_SUFFIX
: &'
static str = ".pso";
841 pub const DLL_EXTENSION
: &'
static str = "pso";
842 pub const EXE_SUFFIX
: &'
static str = ".pexe";
843 pub const EXE_EXTENSION
: &'
static str = "pexe";
846 #[cfg(target_os = "emscripten")]
848 pub const FAMILY
: &'
static str = "unix";
849 pub const OS
: &'
static str = "emscripten";
850 pub const DLL_PREFIX
: &'
static str = "lib";
851 pub const DLL_SUFFIX
: &'
static str = ".so";
852 pub const DLL_EXTENSION
: &'
static str = "so";
853 pub const EXE_SUFFIX
: &'
static str = ".js";
854 pub const EXE_EXTENSION
: &'
static str = "js";
857 #[cfg(target_arch = "x86")]
859 pub const ARCH
: &'
static str = "x86";
862 #[cfg(target_arch = "x86_64")]
864 pub const ARCH
: &'
static str = "x86_64";
867 #[cfg(target_arch = "arm")]
869 pub const ARCH
: &'
static str = "arm";
872 #[cfg(target_arch = "aarch64")]
874 pub const ARCH
: &'
static str = "aarch64";
877 #[cfg(target_arch = "mips")]
879 pub const ARCH
: &'
static str = "mips";
882 #[cfg(target_arch = "powerpc")]
884 pub const ARCH
: &'
static str = "powerpc";
887 #[cfg(target_arch = "powerpc64")]
889 pub const ARCH
: &'
static str = "powerpc64";
892 #[cfg(target_arch = "le32")]
894 pub const ARCH
: &'
static str = "le32";
897 #[cfg(target_arch = "asmjs")]
899 pub const ARCH
: &'
static str = "asmjs";
908 use rand
::{self, Rng}
;
909 use ffi
::{OsString, OsStr}
;
910 use path
::{Path, PathBuf}
;
912 fn make_rand_name() -> OsString
{
913 let mut rng
= rand
::thread_rng();
914 let n
= format
!("TEST{}", rng
.gen_ascii_chars().take(10)
915 .collect
::<String
>());
916 let n
= OsString
::from(n
);
917 assert
!(var_os(&n
).is_none());
921 fn eq(a
: Option
<OsString
>, b
: Option
<&str>) {
922 assert_eq
!(a
.as_ref().map(|s
| &**s
), b
.map(OsStr
::new
).map(|s
| &*s
));
927 let n
= make_rand_name();
928 set_var(&n
, "VALUE");
929 eq(var_os(&n
), Some("VALUE"));
933 fn test_remove_var() {
934 let n
= make_rand_name();
935 set_var(&n
, "VALUE");
937 eq(var_os(&n
), None
);
941 fn test_set_var_overwrite() {
942 let n
= make_rand_name();
945 eq(var_os(&n
), Some("2"));
947 eq(var_os(&n
), Some(""));
952 let mut s
= "".to_string();
955 s
.push_str("aaaaaaaaaa");
958 let n
= make_rand_name();
960 eq(var_os(&n
), Some(&s
));
964 fn test_self_exe_path() {
965 let path
= current_exe();
966 assert
!(path
.is_ok());
967 let path
= path
.unwrap();
969 // Hard to test this function
970 assert
!(path
.is_absolute());
974 fn test_env_set_get_huge() {
975 let n
= make_rand_name();
976 let s
= repeat("x").take(10000).collect
::<String
>();
978 eq(var_os(&n
), Some(&s
));
980 eq(var_os(&n
), None
);
984 fn test_env_set_var() {
985 let n
= make_rand_name();
987 let mut e
= vars_os();
988 set_var(&n
, "VALUE");
989 assert
!(!e
.any(|(k
, v
)| {
990 &*k
== &*n
&& &*v
== "VALUE"
993 assert
!(vars_os().any(|(k
, v
)| {
994 &*k
== &*n
&& &*v
== "VALUE"
1000 assert
!((!Path
::new("test-path").is_absolute()));
1002 current_dir().unwrap();
1007 fn split_paths_windows() {
1008 fn check_parse(unparsed
: &str, parsed
: &[&str]) -> bool
{
1009 split_paths(unparsed
).collect
::<Vec
<_
>>() ==
1010 parsed
.iter().map(|s
| PathBuf
::from(*s
)).collect
::<Vec
<_
>>()
1013 assert
!(check_parse("", &mut [""]));
1014 assert
!(check_parse(r
#""""#, &mut [""]));
1015 assert
!(check_parse(";;", &mut ["", "", ""]));
1016 assert
!(check_parse(r
"c:\", &mut [r
"c:\"]));
1017 assert
!(check_parse(r
"c:\;", &mut [r
"c:\", ""]));
1018 assert
!(check_parse(r
"c:\;c:\Program Files\",
1019 &mut [r
"c:\", r
"c:\Program Files\"]));
1020 assert
!(check_parse(r
#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
1021 assert
!(check_parse(r
#"c:\;c:\"foo;bar"\;c:\baz"#,
1022 &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
1027 fn split_paths_unix() {
1028 fn check_parse(unparsed
: &str, parsed
: &[&str]) -> bool
{
1029 split_paths(unparsed
).collect
::<Vec
<_
>>() ==
1030 parsed
.iter().map(|s
| PathBuf
::from(*s
)).collect
::<Vec
<_
>>()
1033 assert
!(check_parse("", &mut [""]));
1034 assert
!(check_parse("::", &mut ["", "", ""]));
1035 assert
!(check_parse("/", &mut ["/"]));
1036 assert
!(check_parse("/:", &mut ["/", ""]));
1037 assert
!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
1042 fn join_paths_unix() {
1043 fn test_eq(input
: &[&str], output
: &str) -> bool
{
1044 &*join_paths(input
.iter().cloned()).unwrap() ==
1048 assert
!(test_eq(&[], ""));
1049 assert
!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"],
1050 "/bin:/usr/bin:/usr/local/bin"));
1051 assert
!(test_eq(&["", "/bin", "", "", "/usr/bin", ""],
1052 ":/bin:::/usr/bin:"));
1053 assert
!(join_paths(["/te:st"].iter().cloned()).is_err());
1058 fn join_paths_windows() {
1059 fn test_eq(input
: &[&str], output
: &str) -> bool
{
1060 &*join_paths(input
.iter().cloned()).unwrap() ==
1064 assert
!(test_eq(&[], ""));
1065 assert
!(test_eq(&[r
"c:\windows", r
"c:\"],
1066 r
"c:\windows;c:\"));
1067 assert
!(test_eq(&["", r
"c:\windows", "", "", r
"c:\", ""],
1068 r
";c:\windows;;;c:\;"));
1069 assert
!(test_eq(&[r
"c:\te;st", r
"c:\"],
1070 r
#""c:\te;st";c:\"#));
1071 assert!(join_paths([r#"c:\te"st"#].iter().cloned()).is_err());