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 varibles, process arguments, the current directory, and various
15 //! other important directories.
17 #![stable(feature = "env", since = "1.0.0")]
21 use iter::IntoIterator;
23 use ffi::{OsString, AsOsStr};
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;
31 /// Returns the current working directory as a `Path`.
35 /// Returns an `Err` if the current working directory value is invalid.
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.
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());
51 #[stable(feature = "env", since = "1.0.0")]
52 pub fn current_dir() -> io::Result<PathBuf> {
56 /// Changes the current working directory to the specified path, returning
57 /// whether the change was completed successfully or not.
63 /// use std::path::Path;
65 /// let root = Path::new("/");
66 /// assert!(env::set_current_dir(&root).is_ok());
67 /// println!("Successfully changed working directory to {}!", root.display());
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())
74 static ENV_LOCK: StaticMutex = MUTEX_INIT;
76 /// An iterator over a snapshot of the environment variables of this process.
78 /// This iterator is created through `std::env::vars()` and yields `(String,
80 #[stable(feature = "env", since = "1.0.0")]
81 pub struct Vars { inner: VarsOs }
83 /// An iterator over a snapshot of the environment variables of this process.
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 }
90 /// Returns an iterator of (variable, value) pairs of strings, for all the
91 /// environment variables of the current process.
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.
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.
108 /// // We will iterate through the references to the element returned by
110 /// for (key, value) in env::vars() {
111 /// println!("{}: {}", key, value);
114 #[stable(feature = "env", since = "1.0.0")]
115 pub fn vars() -> Vars {
116 Vars { inner: vars_os() }
119 /// Returns an iterator of (variable, value) pairs of OS strings, for all the
120 /// environment variables of the current process.
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.
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);
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() }
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())
151 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
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() }
161 /// Fetches the environment variable `key` from the current process.
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.
172 /// let key = "HOME";
173 /// match env::var(key) {
174 /// Ok(val) => println!("{}: {:?}", key, val),
175 /// Err(e) => println!("couldn't interpret {}: {}", key, e),
178 #[stable(feature = "env", since = "1.0.0")]
179 pub fn var<K: ?Sized>(key: &K) -> Result<String, VarError> where K: AsOsStr {
181 Some(s) => s.into_string().map_err(VarError::NotUnicode),
182 None => Err(VarError::NotPresent)
186 /// Fetches the environment variable `key` from the current process, returning
187 /// None if the variable isn't set.
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)
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())
206 /// Possible errors from the `env::var` method.
207 #[derive(Debug, PartialEq, Eq, Clone)]
208 #[stable(feature = "env", since = "1.0.0")]
210 /// The specified environment variable was not present in the current
211 /// process's environment.
212 #[stable(feature = "env", since = "1.0.0")]
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
218 #[stable(feature = "env", since = "1.0.0")]
219 NotUnicode(OsString),
222 #[stable(feature = "env", since = "1.0.0")]
223 impl fmt::Display for VarError {
224 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
226 VarError::NotPresent => write!(f, "environment variable not found"),
227 VarError::NotUnicode(ref s) => {
228 write!(f, "environment variable was not valid unicode: {:?}", s)
234 #[stable(feature = "env", since = "1.0.0")]
235 impl Error for VarError {
236 fn description(&self) -> &str {
238 VarError::NotPresent => "environment variable not found",
239 VarError::NotUnicode(..) => "environment variable was not valid unicode",
244 /// Sets the environment variable `k` to the value `v` for the currently running
253 /// env::set_var(key, "VALUE");
254 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
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
260 let _g = ENV_LOCK.lock();
261 os_imp::setenv(k.as_os_str(), v.as_os_str())
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())
271 /// An iterator over `Path` instances for parsing an environment variable
272 /// according to platform-specific conventions.
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> }
278 /// Parses input according to platform conventions for the `PATH`
279 /// environment variable.
281 /// Returns an iterator over the paths contained in `unparsed`.
288 /// let key = "PATH";
289 /// match env::var_os(key) {
291 /// for path in env::split_paths(&paths) {
292 /// println!("'{}'", path.display());
295 /// None => println!("{} is not defined in the environment.", key)
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()) }
303 #[stable(feature = "env", since = "1.0.0")]
304 impl<'a> Iterator for SplitPaths<'a> {
306 fn next(&mut self) -> Option<PathBuf> { self.inner.next() }
307 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
310 /// Error type returned from `std::env::join_paths` when paths fail to be
313 #[stable(feature = "env", since = "1.0.0")]
314 pub struct JoinPathsError {
315 inner: os_imp::JoinPathsError
318 /// Joins a collection of `Path`s appropriately for the `PATH`
319 /// environment variable.
321 /// Returns an `OsString` on success.
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).
330 /// # #![feature(convert)]
332 /// use std::path::PathBuf;
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);
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
345 os_imp::join_paths(paths.into_iter()).map_err(|e| {
346 JoinPathsError { inner: e }
350 #[stable(feature = "env", since = "1.0.0")]
351 impl fmt::Display for JoinPathsError {
352 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
357 #[stable(feature = "env", since = "1.0.0")]
358 impl Error for JoinPathsError {
359 fn description(&self) -> &str { self.inner.description() }
362 /// Optionally returns the path to the current user's home directory if known.
366 /// Returns the value of the 'HOME' environment variable if it is set
367 /// and not equal to the empty string.
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
381 /// match env::home_dir() {
382 /// Some(ref p) => println!("{}", p.display()),
383 /// None => println!("Impossible to get your home dir!")
386 #[stable(feature = "env", since = "1.0.0")]
387 pub fn home_dir() -> Option<PathBuf> {
391 /// Returns the path to a temporary directory.
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'.
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 {
406 /// Optionally returns the filesystem path to the current executable which is
407 /// running but with the executable name.
409 /// The path returned is not necessarily a "real path" to the executable as
410 /// there may be intermediate symlinks.
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.
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),
429 #[stable(feature = "env", since = "1.0.0")]
430 pub fn current_exe() -> io::Result<PathBuf> {
431 os_imp::current_exe()
434 static EXIT_STATUS: AtomicIsize = ATOMIC_ISIZE_INIT;
436 /// Sets the process exit code
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.
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)
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
456 /// An iterator over the arguments of a process, yielding a `String` value
457 /// for each argument.
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 }
463 /// An iterator over the arguments of a process, yielding an `OsString` value
464 /// for each argument.
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 }
470 /// Returns the arguments which this program was started with (normally passed
471 /// via the command line).
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.
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.
488 /// // Prints each argument on a separate line
489 /// for argument in env::args() {
490 /// println!("{}", argument);
493 #[stable(feature = "env", since = "1.0.0")]
494 pub fn args() -> Args {
495 Args { inner: args_os() }
498 /// Returns the arguments which this program was started with (normally passed
499 /// via the command line).
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.
510 /// // Prints each argument on a separate line
511 /// for argument in env::args_os() {
512 /// println!("{:?}", argument);
515 #[stable(feature = "env", since = "1.0.0")]
516 pub fn args_os() -> ArgsOs {
517 ArgsOs { inner: os_imp::args() }
520 #[stable(feature = "env", since = "1.0.0")]
521 impl Iterator for Args {
523 fn next(&mut self) -> Option<String> {
524 self.inner.next().map(|s| s.into_string().unwrap())
526 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
529 #[stable(feature = "env", since = "1.0.0")]
530 impl ExactSizeIterator for Args {
531 fn len(&self) -> usize { self.inner.len() }
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() }
541 #[stable(feature = "env", since = "1.0.0")]
542 impl ExactSizeIterator for ArgsOs {
543 fn len(&self) -> usize { self.inner.len() }
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 {
552 /// Constants associated with the current target
553 #[stable(feature = "env", since = "1.0.0")]
555 /// A string describing the architecture of the CPU that this is currently
557 #[stable(feature = "env", since = "1.0.0")]
558 pub const ARCH: &'static str = super::arch::ARCH;
560 #[stable(feature = "env", since = "1.0.0")]
561 pub const FAMILY: &'static str = super::os::FAMILY;
563 /// A string describing the specific operating system in use: in this
565 #[stable(feature = "env", since = "1.0.0")]
566 pub const OS: &'static str = super::os::OS;
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;
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;
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;
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;
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;
595 #[cfg(target_os = "linux")]
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 = "";
606 #[cfg(target_os = "macos")]
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 = "";
617 #[cfg(target_os = "ios")]
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 = "";
628 #[cfg(target_os = "freebsd")]
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 = "";
639 #[cfg(target_os = "dragonfly")]
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 = "";
650 #[cfg(target_os = "bitrig")]
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 = "";
661 #[cfg(target_os = "openbsd")]
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 = "";
672 #[cfg(target_os = "android")]
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 = "";
683 #[cfg(target_os = "windows")]
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";
694 #[cfg(target_arch = "x86")]
696 pub const ARCH: &'static str = "x86";
699 #[cfg(target_arch = "x86_64")]
701 pub const ARCH: &'static str = "x86_64";
704 #[cfg(target_arch = "arm")]
706 pub const ARCH: &'static str = "arm";
709 #[cfg(target_arch = "aarch64")]
711 pub const ARCH: &'static str = "aarch64";
714 #[cfg(target_arch = "mips")]
716 pub const ARCH: &'static str = "mips";
719 #[cfg(target_arch = "mipsel")]
721 pub const ARCH: &'static str = "mipsel";
724 #[cfg(target_arch = "powerpc")]
726 pub const ARCH: &'static str = "powerpc";
735 use rand::{self, Rng};
736 use ffi::{OsString, OsStr};
737 use path::{Path, PathBuf};
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());
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));
754 let n = make_rand_name();
755 set_var(&n, "VALUE");
756 eq(var_os(&n), Some("VALUE"));
760 fn test_remove_var() {
761 let n = make_rand_name();
762 set_var(&n, "VALUE");
764 eq(var_os(&n), None);
768 fn test_set_var_overwrite() {
769 let n = make_rand_name();
772 eq(var_os(&n), Some("2"));
774 eq(var_os(&n), Some(""));
779 let mut s = "".to_string();
782 s.push_str("aaaaaaaaaa");
785 let n = make_rand_name();
787 eq(var_os(&n), Some(&s));
791 fn test_self_exe_path() {
792 let path = current_exe();
793 assert!(path.is_ok());
794 let path = path.unwrap();
796 // Hard to test this function
797 assert!(path.is_absolute());
801 fn test_env_set_get_huge() {
802 let n = make_rand_name();
803 let s = repeat("x").take(10000).collect::<String>();
805 eq(var_os(&n), Some(&s));
807 eq(var_os(&n), None);
811 fn test_env_set_var() {
812 let n = make_rand_name();
814 let mut e = vars_os();
815 set_var(&n, "VALUE");
816 assert!(!e.any(|(k, v)| {
817 &*k == &*n && &*v == "VALUE"
820 assert!(vars_os().any(|(k, v)| {
821 &*k == &*n && &*v == "VALUE"
827 assert!((!Path::new("test-path").is_absolute()));
829 current_dir().unwrap();
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::new(*s)).collect::<Vec<_>>()
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"]));
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<_>>()
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"]));
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)
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());
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)
891 assert!(test_eq(&[], ""));
892 assert!(test_eq(&[r"c:\windows", r"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());