]> git.proxmox.com Git - rustc.git/blob - src/libstd/env.rs
2e00e126e2378f8b7f9d385e4d184ad35b9d4411
[rustc.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).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 #[deprecated(since = "1.2.0", reason = "use process::exit instead")]
490 pub fn set_exit_status(code: i32) {
491 EXIT_STATUS.store(code as isize, Ordering::SeqCst)
492 }
493
494 /// Fetches the process's current exit code. This defaults to 0 and can change
495 /// by calling `set_exit_status`.
496 #[unstable(feature = "exit_status", reason = "managing the exit status may change")]
497 #[deprecated(since = "1.2.0", reason = "use process::exit instead")]
498 pub fn get_exit_status() -> i32 {
499 EXIT_STATUS.load(Ordering::SeqCst) as i32
500 }
501
502 /// An iterator over the arguments of a process, yielding a `String` value
503 /// for each argument.
504 ///
505 /// This structure is created through the `std::env::args` method.
506 #[stable(feature = "env", since = "1.0.0")]
507 pub struct Args { inner: ArgsOs }
508
509 /// An iterator over the arguments of a process, yielding an `OsString` value
510 /// for each argument.
511 ///
512 /// This structure is created through the `std::env::args_os` method.
513 #[stable(feature = "env", since = "1.0.0")]
514 pub struct ArgsOs { inner: os_imp::Args }
515
516 /// Returns the arguments which this program was started with (normally passed
517 /// via the command line).
518 ///
519 /// The first element is traditionally the path to the executable, but it can be
520 /// set to arbitrary text, and it may not even exist, so this property should
521 /// not be relied upon for security purposes.
522 ///
523 /// # Panics
524 ///
525 /// The returned iterator will panic during iteration if any argument to the
526 /// process is not valid unicode. If this is not desired it is recommended to
527 /// use the `args_os` function instead.
528 ///
529 /// # Examples
530 ///
531 /// ```
532 /// use std::env;
533 ///
534 /// // Prints each argument on a separate line
535 /// for argument in env::args() {
536 /// println!("{}", argument);
537 /// }
538 /// ```
539 #[stable(feature = "env", since = "1.0.0")]
540 pub fn args() -> Args {
541 Args { inner: args_os() }
542 }
543
544 /// Returns the arguments which this program was started with (normally passed
545 /// via the command line).
546 ///
547 /// The first element is traditionally the path to the executable, but it can be
548 /// set to arbitrary text, and it may not even exist, so this property should
549 /// not be relied upon for security purposes.
550 ///
551 /// # Examples
552 ///
553 /// ```
554 /// use std::env;
555 ///
556 /// // Prints each argument on a separate line
557 /// for argument in env::args_os() {
558 /// println!("{:?}", argument);
559 /// }
560 /// ```
561 #[stable(feature = "env", since = "1.0.0")]
562 pub fn args_os() -> ArgsOs {
563 ArgsOs { inner: os_imp::args() }
564 }
565
566 #[stable(feature = "env", since = "1.0.0")]
567 impl Iterator for Args {
568 type Item = String;
569 fn next(&mut self) -> Option<String> {
570 self.inner.next().map(|s| s.into_string().unwrap())
571 }
572 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
573 }
574
575 #[stable(feature = "env", since = "1.0.0")]
576 impl ExactSizeIterator for Args {
577 fn len(&self) -> usize { self.inner.len() }
578 }
579
580 #[stable(feature = "env", since = "1.0.0")]
581 impl Iterator for ArgsOs {
582 type Item = OsString;
583 fn next(&mut self) -> Option<OsString> { self.inner.next() }
584 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
585 }
586
587 #[stable(feature = "env", since = "1.0.0")]
588 impl ExactSizeIterator for ArgsOs {
589 fn len(&self) -> usize { self.inner.len() }
590 }
591
592 /// Returns the page size of the current architecture in bytes.
593 #[unstable(feature = "page_size", reason = "naming and/or location may change")]
594 pub fn page_size() -> usize {
595 os_imp::page_size()
596 }
597
598 /// Constants associated with the current target
599 #[stable(feature = "env", since = "1.0.0")]
600 pub mod consts {
601 /// A string describing the architecture of the CPU that this is currently
602 /// in use.
603 ///
604 /// Some possible values:
605 ///
606 /// - x86
607 /// - x86_64
608 /// - arm
609 /// - aarch64
610 /// - mips
611 /// - mipsel
612 /// - powerpc
613 #[stable(feature = "env", since = "1.0.0")]
614 pub const ARCH: &'static str = super::arch::ARCH;
615
616 /// The family of the operating system. In this case, `unix`.
617 ///
618 /// Some possible values:
619 ///
620 /// - unix
621 /// - windows
622 #[stable(feature = "env", since = "1.0.0")]
623 pub const FAMILY: &'static str = super::os::FAMILY;
624
625 /// A string describing the specific operating system in use: in this
626 /// case, `linux`.
627 ///
628 /// Some possible values:
629 ///
630 /// - linux
631 /// - macos
632 /// - ios
633 /// - freebsd
634 /// - dragonfly
635 /// - bitrig
636 /// - openbsd
637 /// - android
638 /// - windows
639 #[stable(feature = "env", since = "1.0.0")]
640 pub const OS: &'static str = super::os::OS;
641
642 /// Specifies the filename prefix used for shared libraries on this
643 /// platform: in this case, `lib`.
644 ///
645 /// Some possible values:
646 ///
647 /// - lib
648 /// - `""` (an empty string)
649 #[stable(feature = "env", since = "1.0.0")]
650 pub const DLL_PREFIX: &'static str = super::os::DLL_PREFIX;
651
652 /// Specifies the filename suffix used for shared libraries on this
653 /// platform: in this case, `.so`.
654 ///
655 /// Some possible values:
656 ///
657 /// - .so
658 /// - .dylib
659 /// - .dll
660 #[stable(feature = "env", since = "1.0.0")]
661 pub const DLL_SUFFIX: &'static str = super::os::DLL_SUFFIX;
662
663 /// Specifies the file extension used for shared libraries on this
664 /// platform that goes after the dot: in this case, `so`.
665 ///
666 /// Some possible values:
667 ///
668 /// - .so
669 /// - .dylib
670 /// - .dll
671 #[stable(feature = "env", since = "1.0.0")]
672 pub const DLL_EXTENSION: &'static str = super::os::DLL_EXTENSION;
673
674 /// Specifies the filename suffix used for executable binaries on this
675 /// platform: in this case, the empty string.
676 ///
677 /// Some possible values:
678 ///
679 /// - exe
680 /// - `""` (an empty string)
681 #[stable(feature = "env", since = "1.0.0")]
682 pub const EXE_SUFFIX: &'static str = super::os::EXE_SUFFIX;
683
684 /// Specifies the file extension, if any, used for executable binaries
685 /// on this platform: in this case, the empty string.
686 ///
687 /// Some possible values:
688 ///
689 /// - exe
690 /// - `""` (an empty string)
691 #[stable(feature = "env", since = "1.0.0")]
692 pub const EXE_EXTENSION: &'static str = super::os::EXE_EXTENSION;
693
694 }
695
696 #[cfg(target_os = "linux")]
697 mod os {
698 pub const FAMILY: &'static str = "unix";
699 pub const OS: &'static str = "linux";
700 pub const DLL_PREFIX: &'static str = "lib";
701 pub const DLL_SUFFIX: &'static str = ".so";
702 pub const DLL_EXTENSION: &'static str = "so";
703 pub const EXE_SUFFIX: &'static str = "";
704 pub const EXE_EXTENSION: &'static str = "";
705 }
706
707 #[cfg(target_os = "macos")]
708 mod os {
709 pub const FAMILY: &'static str = "unix";
710 pub const OS: &'static str = "macos";
711 pub const DLL_PREFIX: &'static str = "lib";
712 pub const DLL_SUFFIX: &'static str = ".dylib";
713 pub const DLL_EXTENSION: &'static str = "dylib";
714 pub const EXE_SUFFIX: &'static str = "";
715 pub const EXE_EXTENSION: &'static str = "";
716 }
717
718 #[cfg(target_os = "ios")]
719 mod os {
720 pub const FAMILY: &'static str = "unix";
721 pub const OS: &'static str = "ios";
722 pub const DLL_PREFIX: &'static str = "lib";
723 pub const DLL_SUFFIX: &'static str = ".dylib";
724 pub const DLL_EXTENSION: &'static str = "dylib";
725 pub const EXE_SUFFIX: &'static str = "";
726 pub const EXE_EXTENSION: &'static str = "";
727 }
728
729 #[cfg(target_os = "freebsd")]
730 mod os {
731 pub const FAMILY: &'static str = "unix";
732 pub const OS: &'static str = "freebsd";
733 pub const DLL_PREFIX: &'static str = "lib";
734 pub const DLL_SUFFIX: &'static str = ".so";
735 pub const DLL_EXTENSION: &'static str = "so";
736 pub const EXE_SUFFIX: &'static str = "";
737 pub const EXE_EXTENSION: &'static str = "";
738 }
739
740 #[cfg(target_os = "dragonfly")]
741 mod os {
742 pub const FAMILY: &'static str = "unix";
743 pub const OS: &'static str = "dragonfly";
744 pub const DLL_PREFIX: &'static str = "lib";
745 pub const DLL_SUFFIX: &'static str = ".so";
746 pub const DLL_EXTENSION: &'static str = "so";
747 pub const EXE_SUFFIX: &'static str = "";
748 pub const EXE_EXTENSION: &'static str = "";
749 }
750
751 #[cfg(target_os = "bitrig")]
752 mod os {
753 pub const FAMILY: &'static str = "unix";
754 pub const OS: &'static str = "bitrig";
755 pub const DLL_PREFIX: &'static str = "lib";
756 pub const DLL_SUFFIX: &'static str = ".so";
757 pub const DLL_EXTENSION: &'static str = "so";
758 pub const EXE_SUFFIX: &'static str = "";
759 pub const EXE_EXTENSION: &'static str = "";
760 }
761
762 #[cfg(target_os = "openbsd")]
763 mod os {
764 pub const FAMILY: &'static str = "unix";
765 pub const OS: &'static str = "openbsd";
766 pub const DLL_PREFIX: &'static str = "lib";
767 pub const DLL_SUFFIX: &'static str = ".so";
768 pub const DLL_EXTENSION: &'static str = "so";
769 pub const EXE_SUFFIX: &'static str = "";
770 pub const EXE_EXTENSION: &'static str = "";
771 }
772
773 #[cfg(target_os = "android")]
774 mod os {
775 pub const FAMILY: &'static str = "unix";
776 pub const OS: &'static str = "android";
777 pub const DLL_PREFIX: &'static str = "lib";
778 pub const DLL_SUFFIX: &'static str = ".so";
779 pub const DLL_EXTENSION: &'static str = "so";
780 pub const EXE_SUFFIX: &'static str = "";
781 pub const EXE_EXTENSION: &'static str = "";
782 }
783
784 #[cfg(target_os = "windows")]
785 mod os {
786 pub const FAMILY: &'static str = "windows";
787 pub const OS: &'static str = "windows";
788 pub const DLL_PREFIX: &'static str = "";
789 pub const DLL_SUFFIX: &'static str = ".dll";
790 pub const DLL_EXTENSION: &'static str = "dll";
791 pub const EXE_SUFFIX: &'static str = ".exe";
792 pub const EXE_EXTENSION: &'static str = "exe";
793 }
794
795 #[cfg(target_arch = "x86")]
796 mod arch {
797 pub const ARCH: &'static str = "x86";
798 }
799
800 #[cfg(target_arch = "x86_64")]
801 mod arch {
802 pub const ARCH: &'static str = "x86_64";
803 }
804
805 #[cfg(target_arch = "arm")]
806 mod arch {
807 pub const ARCH: &'static str = "arm";
808 }
809
810 #[cfg(target_arch = "aarch64")]
811 mod arch {
812 pub const ARCH: &'static str = "aarch64";
813 }
814
815 #[cfg(target_arch = "mips")]
816 mod arch {
817 pub const ARCH: &'static str = "mips";
818 }
819
820 #[cfg(target_arch = "mipsel")]
821 mod arch {
822 pub const ARCH: &'static str = "mipsel";
823 }
824
825 #[cfg(target_arch = "powerpc")]
826 mod arch {
827 pub const ARCH: &'static str = "powerpc";
828 }
829
830 #[cfg(test)]
831 mod tests {
832 use prelude::v1::*;
833 use super::*;
834
835 use iter::repeat;
836 use rand::{self, Rng};
837 use ffi::{OsString, OsStr};
838 use path::{Path, PathBuf};
839
840 fn make_rand_name() -> OsString {
841 let mut rng = rand::thread_rng();
842 let n = format!("TEST{}", rng.gen_ascii_chars().take(10)
843 .collect::<String>());
844 let n = OsString::from(n);
845 assert!(var_os(&n).is_none());
846 n
847 }
848
849 fn eq(a: Option<OsString>, b: Option<&str>) {
850 assert_eq!(a.as_ref().map(|s| &**s), b.map(OsStr::new).map(|s| &*s));
851 }
852
853 #[test]
854 fn test_set_var() {
855 let n = make_rand_name();
856 set_var(&n, "VALUE");
857 eq(var_os(&n), Some("VALUE"));
858 }
859
860 #[test]
861 fn test_remove_var() {
862 let n = make_rand_name();
863 set_var(&n, "VALUE");
864 remove_var(&n);
865 eq(var_os(&n), None);
866 }
867
868 #[test]
869 fn test_set_var_overwrite() {
870 let n = make_rand_name();
871 set_var(&n, "1");
872 set_var(&n, "2");
873 eq(var_os(&n), Some("2"));
874 set_var(&n, "");
875 eq(var_os(&n), Some(""));
876 }
877
878 #[test]
879 fn test_var_big() {
880 let mut s = "".to_string();
881 let mut i = 0;
882 while i < 100 {
883 s.push_str("aaaaaaaaaa");
884 i += 1;
885 }
886 let n = make_rand_name();
887 set_var(&n, &s);
888 eq(var_os(&n), Some(&s));
889 }
890
891 #[test]
892 fn test_self_exe_path() {
893 let path = current_exe();
894 assert!(path.is_ok());
895 let path = path.unwrap();
896
897 // Hard to test this function
898 assert!(path.is_absolute());
899 }
900
901 #[test]
902 fn test_env_set_get_huge() {
903 let n = make_rand_name();
904 let s = repeat("x").take(10000).collect::<String>();
905 set_var(&n, &s);
906 eq(var_os(&n), Some(&s));
907 remove_var(&n);
908 eq(var_os(&n), None);
909 }
910
911 #[test]
912 fn test_env_set_var() {
913 let n = make_rand_name();
914
915 let mut e = vars_os();
916 set_var(&n, "VALUE");
917 assert!(!e.any(|(k, v)| {
918 &*k == &*n && &*v == "VALUE"
919 }));
920
921 assert!(vars_os().any(|(k, v)| {
922 &*k == &*n && &*v == "VALUE"
923 }));
924 }
925
926 #[test]
927 fn test() {
928 assert!((!Path::new("test-path").is_absolute()));
929
930 current_dir().unwrap();
931 }
932
933 #[test]
934 #[cfg(windows)]
935 fn split_paths_windows() {
936 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
937 split_paths(unparsed).collect::<Vec<_>>() ==
938 parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
939 }
940
941 assert!(check_parse("", &mut [""]));
942 assert!(check_parse(r#""""#, &mut [""]));
943 assert!(check_parse(";;", &mut ["", "", ""]));
944 assert!(check_parse(r"c:\", &mut [r"c:\"]));
945 assert!(check_parse(r"c:\;", &mut [r"c:\", ""]));
946 assert!(check_parse(r"c:\;c:\Program Files\",
947 &mut [r"c:\", r"c:\Program Files\"]));
948 assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
949 assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
950 &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
951 }
952
953 #[test]
954 #[cfg(unix)]
955 fn split_paths_unix() {
956 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
957 split_paths(unparsed).collect::<Vec<_>>() ==
958 parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
959 }
960
961 assert!(check_parse("", &mut [""]));
962 assert!(check_parse("::", &mut ["", "", ""]));
963 assert!(check_parse("/", &mut ["/"]));
964 assert!(check_parse("/:", &mut ["/", ""]));
965 assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
966 }
967
968 #[test]
969 #[cfg(unix)]
970 fn join_paths_unix() {
971 fn test_eq(input: &[&str], output: &str) -> bool {
972 &*join_paths(input.iter().cloned()).unwrap() ==
973 OsStr::new(output)
974 }
975
976 assert!(test_eq(&[], ""));
977 assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"],
978 "/bin:/usr/bin:/usr/local/bin"));
979 assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""],
980 ":/bin:::/usr/bin:"));
981 assert!(join_paths(["/te:st"].iter().cloned()).is_err());
982 }
983
984 #[test]
985 #[cfg(windows)]
986 fn join_paths_windows() {
987 fn test_eq(input: &[&str], output: &str) -> bool {
988 &*join_paths(input.iter().cloned()).unwrap() ==
989 OsStr::new(output)
990 }
991
992 assert!(test_eq(&[], ""));
993 assert!(test_eq(&[r"c:\windows", r"c:\"],
994 r"c:\windows;c:\"));
995 assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""],
996 r";c:\windows;;;c:\;"));
997 assert!(test_eq(&[r"c:\te;st", r"c:\"],
998 r#""c:\te;st";c:\"#));
999 assert!(join_paths([r#"c:\te"st"#].iter().cloned()).is_err());
1000 }
1001 }