1 | //! Inspection and manipulation of the process's environment. |
2 | //! |
3 | //! This module contains functions to inspect various aspects such as |
4 | //! environment variables, process arguments, the current directory, and various |
5 | //! other important directories. |
6 | //! |
7 | //! There are several functions and structs in this module that have a |
8 | //! counterpart ending in `os`. Those ending in `os` will return an [`OsString`] |
9 | //! and those without will return a [`String`]. |
10 | |
11 | #![stable (feature = "env" , since = "1.0.0" )] |
12 | |
13 | #[cfg (test)] |
14 | mod tests; |
15 | |
16 | use crate::error::Error; |
17 | use crate::ffi::{OsStr, OsString}; |
18 | use crate::fmt; |
19 | use crate::io; |
20 | use crate::path::{Path, PathBuf}; |
21 | use crate::sys; |
22 | use crate::sys::os as os_imp; |
23 | |
24 | /// Returns the current working directory as a [`PathBuf`]. |
25 | /// |
26 | /// # Platform-specific behavior |
27 | /// |
28 | /// This function [currently] corresponds to the `getcwd` function on Unix |
29 | /// and the `GetCurrentDirectoryW` function on Windows. |
30 | /// |
31 | /// [currently]: crate::io#platform-specific-behavior |
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 | /// |
41 | /// # Examples |
42 | /// |
43 | /// ``` |
44 | /// use std::env; |
45 | /// |
46 | /// fn main() -> std::io::Result<()> { |
47 | /// let path = env::current_dir()?; |
48 | /// println!("The current directory is {}" , path.display()); |
49 | /// Ok(()) |
50 | /// } |
51 | /// ``` |
52 | #[doc (alias = "pwd" )] |
53 | #[doc (alias = "getcwd" )] |
54 | #[doc (alias = "GetCurrentDirectory" )] |
55 | #[stable (feature = "env" , since = "1.0.0" )] |
56 | pub fn current_dir() -> io::Result<PathBuf> { |
57 | os_imp::getcwd() |
58 | } |
59 | |
60 | /// Changes the current working directory to the specified path. |
61 | /// |
62 | /// # Platform-specific behavior |
63 | /// |
64 | /// This function [currently] corresponds to the `chdir` function on Unix |
65 | /// and the `SetCurrentDirectoryW` function on Windows. |
66 | /// |
67 | /// Returns an [`Err`] if the operation fails. |
68 | /// |
69 | /// [currently]: crate::io#platform-specific-behavior |
70 | /// |
71 | /// # Examples |
72 | /// |
73 | /// ``` |
74 | /// use std::env; |
75 | /// use std::path::Path; |
76 | /// |
77 | /// let root = Path::new("/" ); |
78 | /// assert!(env::set_current_dir(&root).is_ok()); |
79 | /// println!("Successfully changed working directory to {}!" , root.display()); |
80 | /// ``` |
81 | #[doc (alias = "chdir" , alias = "SetCurrentDirectory" , alias = "SetCurrentDirectoryW" )] |
82 | #[stable (feature = "env" , since = "1.0.0" )] |
83 | pub fn set_current_dir<P: AsRef<Path>>(path: P) -> io::Result<()> { |
84 | os_imp::chdir(path.as_ref()) |
85 | } |
86 | |
87 | /// An iterator over a snapshot of the environment variables of this process. |
88 | /// |
89 | /// This structure is created by [`env::vars()`]. See its documentation for more. |
90 | /// |
91 | /// [`env::vars()`]: vars |
92 | #[stable (feature = "env" , since = "1.0.0" )] |
93 | pub struct Vars { |
94 | inner: VarsOs, |
95 | } |
96 | |
97 | /// An iterator over a snapshot of the environment variables of this process. |
98 | /// |
99 | /// This structure is created by [`env::vars_os()`]. See its documentation for more. |
100 | /// |
101 | /// [`env::vars_os()`]: vars_os |
102 | #[stable (feature = "env" , since = "1.0.0" )] |
103 | pub struct VarsOs { |
104 | inner: os_imp::Env, |
105 | } |
106 | |
107 | /// Returns an iterator of (variable, value) pairs of strings, for all the |
108 | /// environment variables of the current process. |
109 | /// |
110 | /// The returned iterator contains a snapshot of the process's environment |
111 | /// variables at the time of this invocation. Modifications to environment |
112 | /// variables afterwards will not be reflected in the returned iterator. |
113 | /// |
114 | /// # Panics |
115 | /// |
116 | /// While iterating, the returned iterator will panic if any key or value in the |
117 | /// environment is not valid unicode. If this is not desired, consider using |
118 | /// [`env::vars_os()`]. |
119 | /// |
120 | /// # Examples |
121 | /// |
122 | /// ``` |
123 | /// use std::env; |
124 | /// |
125 | /// // We will iterate through the references to the element returned by |
126 | /// // env::vars(); |
127 | /// for (key, value) in env::vars() { |
128 | /// println!("{key}: {value}" ); |
129 | /// } |
130 | /// ``` |
131 | /// |
132 | /// [`env::vars_os()`]: vars_os |
133 | #[must_use ] |
134 | #[stable (feature = "env" , since = "1.0.0" )] |
135 | pub fn vars() -> Vars { |
136 | Vars { inner: vars_os() } |
137 | } |
138 | |
139 | /// Returns an iterator of (variable, value) pairs of OS strings, for all the |
140 | /// environment variables of the current process. |
141 | /// |
142 | /// The returned iterator contains a snapshot of the process's environment |
143 | /// variables at the time of this invocation. Modifications to environment |
144 | /// variables afterwards will not be reflected in the returned iterator. |
145 | /// |
146 | /// Note that the returned iterator will not check if the environment variables |
147 | /// are valid Unicode. If you want to panic on invalid UTF-8, |
148 | /// use the [`vars`] function instead. |
149 | /// |
150 | /// # Examples |
151 | /// |
152 | /// ``` |
153 | /// use std::env; |
154 | /// |
155 | /// // We will iterate through the references to the element returned by |
156 | /// // env::vars_os(); |
157 | /// for (key, value) in env::vars_os() { |
158 | /// println!("{key:?}: {value:?}" ); |
159 | /// } |
160 | /// ``` |
161 | #[must_use ] |
162 | #[stable (feature = "env" , since = "1.0.0" )] |
163 | pub fn vars_os() -> VarsOs { |
164 | VarsOs { inner: os_imp::env() } |
165 | } |
166 | |
167 | #[stable (feature = "env" , since = "1.0.0" )] |
168 | impl Iterator for Vars { |
169 | type Item = (String, String); |
170 | fn next(&mut self) -> Option<(String, String)> { |
171 | self.inner.next().map(|(a: OsString, b: OsString)| (a.into_string().unwrap(), b.into_string().unwrap())) |
172 | } |
173 | fn size_hint(&self) -> (usize, Option<usize>) { |
174 | self.inner.size_hint() |
175 | } |
176 | } |
177 | |
178 | #[stable (feature = "std_debug" , since = "1.16.0" )] |
179 | impl fmt::Debug for Vars { |
180 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
181 | let Self { inner: VarsOs { inner: &Env } } = self; |
182 | f.debug_struct("Vars" ).field(name:"inner" , &inner.str_debug()).finish() |
183 | } |
184 | } |
185 | |
186 | #[stable (feature = "env" , since = "1.0.0" )] |
187 | impl Iterator for VarsOs { |
188 | type Item = (OsString, OsString); |
189 | fn next(&mut self) -> Option<(OsString, OsString)> { |
190 | self.inner.next() |
191 | } |
192 | fn size_hint(&self) -> (usize, Option<usize>) { |
193 | self.inner.size_hint() |
194 | } |
195 | } |
196 | |
197 | #[stable (feature = "std_debug" , since = "1.16.0" )] |
198 | impl fmt::Debug for VarsOs { |
199 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
200 | let Self { inner: &Env } = self; |
201 | f.debug_struct("VarsOs" ).field(name:"inner" , value:inner).finish() |
202 | } |
203 | } |
204 | |
205 | /// Fetches the environment variable `key` from the current process. |
206 | /// |
207 | /// # Errors |
208 | /// |
209 | /// This function will return an error if the environment variable isn't set. |
210 | /// |
211 | /// This function may return an error if the environment variable's name contains |
212 | /// the equal sign character (`=`) or the NUL character. |
213 | /// |
214 | /// This function will return an error if the environment variable's value is |
215 | /// not valid Unicode. If this is not desired, consider using [`var_os`]. |
216 | /// |
217 | /// # Examples |
218 | /// |
219 | /// ``` |
220 | /// use std::env; |
221 | /// |
222 | /// let key = "HOME" ; |
223 | /// match env::var(key) { |
224 | /// Ok(val) => println!("{key}: {val:?}" ), |
225 | /// Err(e) => println!("couldn't interpret {key}: {e}" ), |
226 | /// } |
227 | /// ``` |
228 | #[stable (feature = "env" , since = "1.0.0" )] |
229 | pub fn var<K: AsRef<OsStr>>(key: K) -> Result<String, VarError> { |
230 | _var(key.as_ref()) |
231 | } |
232 | |
233 | fn _var(key: &OsStr) -> Result<String, VarError> { |
234 | match var_os(key) { |
235 | Some(s: OsString) => s.into_string().map_err(op:VarError::NotUnicode), |
236 | None => Err(VarError::NotPresent), |
237 | } |
238 | } |
239 | |
240 | /// Fetches the environment variable `key` from the current process, returning |
241 | /// [`None`] if the variable isn't set or if there is another error. |
242 | /// |
243 | /// It may return `None` if the environment variable's name contains |
244 | /// the equal sign character (`=`) or the NUL character. |
245 | /// |
246 | /// Note that this function will not check if the environment variable |
247 | /// is valid Unicode. If you want to have an error on invalid UTF-8, |
248 | /// use the [`var`] function instead. |
249 | /// |
250 | /// # Examples |
251 | /// |
252 | /// ``` |
253 | /// use std::env; |
254 | /// |
255 | /// let key = "HOME" ; |
256 | /// match env::var_os(key) { |
257 | /// Some(val) => println!("{key}: {val:?}" ), |
258 | /// None => println!("{key} is not defined in the environment." ) |
259 | /// } |
260 | /// ``` |
261 | /// |
262 | /// If expecting a delimited variable (such as `PATH`), [`split_paths`] |
263 | /// can be used to separate items. |
264 | #[must_use ] |
265 | #[stable (feature = "env" , since = "1.0.0" )] |
266 | pub fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> { |
267 | _var_os(key.as_ref()) |
268 | } |
269 | |
270 | fn _var_os(key: &OsStr) -> Option<OsString> { |
271 | os_imp::getenv(key) |
272 | } |
273 | |
274 | /// The error type for operations interacting with environment variables. |
275 | /// Possibly returned from [`env::var()`]. |
276 | /// |
277 | /// [`env::var()`]: var |
278 | #[derive (Debug, PartialEq, Eq, Clone)] |
279 | #[stable (feature = "env" , since = "1.0.0" )] |
280 | pub enum VarError { |
281 | /// The specified environment variable was not present in the current |
282 | /// process's environment. |
283 | #[stable (feature = "env" , since = "1.0.0" )] |
284 | NotPresent, |
285 | |
286 | /// The specified environment variable was found, but it did not contain |
287 | /// valid unicode data. The found data is returned as a payload of this |
288 | /// variant. |
289 | #[stable (feature = "env" , since = "1.0.0" )] |
290 | NotUnicode(#[stable (feature = "env" , since = "1.0.0" )] OsString), |
291 | } |
292 | |
293 | #[stable (feature = "env" , since = "1.0.0" )] |
294 | impl fmt::Display for VarError { |
295 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
296 | match *self { |
297 | VarError::NotPresent => write!(f, "environment variable not found" ), |
298 | VarError::NotUnicode(ref s: &OsString) => { |
299 | write!(f, "environment variable was not valid unicode: {:?}" , s) |
300 | } |
301 | } |
302 | } |
303 | } |
304 | |
305 | #[stable (feature = "env" , since = "1.0.0" )] |
306 | impl Error for VarError { |
307 | #[allow (deprecated)] |
308 | fn description(&self) -> &str { |
309 | match *self { |
310 | VarError::NotPresent => "environment variable not found" , |
311 | VarError::NotUnicode(..) => "environment variable was not valid unicode" , |
312 | } |
313 | } |
314 | } |
315 | |
316 | /// Sets the environment variable `key` to the value `value` for the currently running |
317 | /// process. |
318 | /// |
319 | /// # Safety |
320 | /// |
321 | /// Even though this function is currently not marked as `unsafe`, it needs to |
322 | /// be because invoking it can cause undefined behaviour. The function will be |
323 | /// marked `unsafe` in a future version of Rust. This is tracked in |
324 | /// [rust#27970](https://github.com/rust-lang/rust/issues/27970). |
325 | /// |
326 | /// This function is safe to call in a single-threaded program. |
327 | /// |
328 | /// In multi-threaded programs, you must ensure that are no other threads |
329 | /// concurrently writing or *reading*(!) from the environment through functions |
330 | /// other than the ones in this module. You are responsible for figuring out |
331 | /// how to achieve this, but we strongly suggest not using `set_var` or |
332 | /// `remove_var` in multi-threaded programs at all. |
333 | /// |
334 | /// Most C libraries, including libc itself do not advertise which functions |
335 | /// read from the environment. Even functions from the Rust standard library do |
336 | /// that, e.g. for DNS lookups from [`std::net::ToSocketAddrs`]. |
337 | /// |
338 | /// Discussion of this unsafety on Unix may be found in: |
339 | /// |
340 | /// - [Austin Group Bugzilla](https://austingroupbugs.net/view.php?id=188) |
341 | /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2) |
342 | /// |
343 | /// [`std::net::ToSocketAddrs`]: crate::net::ToSocketAddrs |
344 | /// |
345 | /// # Panics |
346 | /// |
347 | /// This function may panic if `key` is empty, contains an ASCII equals sign `'='` |
348 | /// or the NUL character `'\0'`, or when `value` contains the NUL character. |
349 | /// |
350 | /// # Examples |
351 | /// |
352 | /// ``` |
353 | /// use std::env; |
354 | /// |
355 | /// let key = "KEY" ; |
356 | /// env::set_var(key, "VALUE" ); |
357 | /// assert_eq!(env::var(key), Ok("VALUE" .to_string())); |
358 | /// ``` |
359 | #[stable (feature = "env" , since = "1.0.0" )] |
360 | pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(key: K, value: V) { |
361 | _set_var(key.as_ref(), value.as_ref()) |
362 | } |
363 | |
364 | fn _set_var(key: &OsStr, value: &OsStr) { |
365 | os_imp::setenv(key, value).unwrap_or_else(|e: Error| { |
366 | panic!("failed to set environment variable ` {key:?}` to ` {value:?}`: {e}" ) |
367 | }) |
368 | } |
369 | |
370 | /// Removes an environment variable from the environment of the currently running process. |
371 | /// |
372 | /// # Safety |
373 | /// |
374 | /// Even though this function is currently not marked as `unsafe`, it needs to |
375 | /// be because invoking it can cause undefined behaviour. The function will be |
376 | /// marked `unsafe` in a future version of Rust. This is tracked in |
377 | /// [rust#27970](https://github.com/rust-lang/rust/issues/27970). |
378 | /// |
379 | /// This function is safe to call in a single-threaded program. |
380 | /// |
381 | /// In multi-threaded programs, you must ensure that are no other threads |
382 | /// concurrently writing or *reading*(!) from the environment through functions |
383 | /// other than the ones in this module. You are responsible for figuring out |
384 | /// how to achieve this, but we strongly suggest not using `set_var` or |
385 | /// `remove_var` in multi-threaded programs at all. |
386 | /// |
387 | /// Most C libraries, including libc itself do not advertise which functions |
388 | /// read from the environment. Even functions from the Rust standard library do |
389 | /// that, e.g. for DNS lookups from [`std::net::ToSocketAddrs`]. |
390 | /// |
391 | /// Discussion of this unsafety on Unix may be found in: |
392 | /// |
393 | /// - [Austin Group Bugzilla](https://austingroupbugs.net/view.php?id=188) |
394 | /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2) |
395 | /// |
396 | /// [`std::net::ToSocketAddrs`]: crate::net::ToSocketAddrs |
397 | /// |
398 | /// # Panics |
399 | /// |
400 | /// This function may panic if `key` is empty, contains an ASCII equals sign |
401 | /// `'='` or the NUL character `'\0'`, or when the value contains the NUL |
402 | /// character. |
403 | /// |
404 | /// # Examples |
405 | /// |
406 | /// ``` |
407 | /// use std::env; |
408 | /// |
409 | /// let key = "KEY" ; |
410 | /// env::set_var(key, "VALUE" ); |
411 | /// assert_eq!(env::var(key), Ok("VALUE" .to_string())); |
412 | /// |
413 | /// env::remove_var(key); |
414 | /// assert!(env::var(key).is_err()); |
415 | /// ``` |
416 | #[stable (feature = "env" , since = "1.0.0" )] |
417 | pub fn remove_var<K: AsRef<OsStr>>(key: K) { |
418 | _remove_var(key.as_ref()) |
419 | } |
420 | |
421 | fn _remove_var(key: &OsStr) { |
422 | os_imp::unsetenv(key) |
423 | .unwrap_or_else(|e: Error| panic!("failed to remove environment variable ` {key:?}`: {e}" )) |
424 | } |
425 | |
426 | /// An iterator that splits an environment variable into paths according to |
427 | /// platform-specific conventions. |
428 | /// |
429 | /// The iterator element type is [`PathBuf`]. |
430 | /// |
431 | /// This structure is created by [`env::split_paths()`]. See its |
432 | /// documentation for more. |
433 | /// |
434 | /// [`env::split_paths()`]: split_paths |
435 | #[must_use = "iterators are lazy and do nothing unless consumed" ] |
436 | #[stable (feature = "env" , since = "1.0.0" )] |
437 | pub struct SplitPaths<'a> { |
438 | inner: os_imp::SplitPaths<'a>, |
439 | } |
440 | |
441 | /// Parses input according to platform conventions for the `PATH` |
442 | /// environment variable. |
443 | /// |
444 | /// Returns an iterator over the paths contained in `unparsed`. The iterator |
445 | /// element type is [`PathBuf`]. |
446 | /// |
447 | /// On most Unix platforms, the separator is `:` and on Windows it is `;`. This |
448 | /// also performs unquoting on Windows. |
449 | /// |
450 | /// [`join_paths`] can be used to recombine elements. |
451 | /// |
452 | /// # Panics |
453 | /// |
454 | /// This will panic on systems where there is no delimited `PATH` variable, |
455 | /// such as UEFI. |
456 | /// |
457 | /// # Examples |
458 | /// |
459 | /// ``` |
460 | /// use std::env; |
461 | /// |
462 | /// let key = "PATH" ; |
463 | /// match env::var_os(key) { |
464 | /// Some(paths) => { |
465 | /// for path in env::split_paths(&paths) { |
466 | /// println!("'{}'" , path.display()); |
467 | /// } |
468 | /// } |
469 | /// None => println!("{key} is not defined in the environment." ) |
470 | /// } |
471 | /// ``` |
472 | #[stable (feature = "env" , since = "1.0.0" )] |
473 | pub fn split_paths<T: AsRef<OsStr> + ?Sized>(unparsed: &T) -> SplitPaths<'_> { |
474 | SplitPaths { inner: os_imp::split_paths(unparsed.as_ref()) } |
475 | } |
476 | |
477 | #[stable (feature = "env" , since = "1.0.0" )] |
478 | impl<'a> Iterator for SplitPaths<'a> { |
479 | type Item = PathBuf; |
480 | fn next(&mut self) -> Option<PathBuf> { |
481 | self.inner.next() |
482 | } |
483 | fn size_hint(&self) -> (usize, Option<usize>) { |
484 | self.inner.size_hint() |
485 | } |
486 | } |
487 | |
488 | #[stable (feature = "std_debug" , since = "1.16.0" )] |
489 | impl fmt::Debug for SplitPaths<'_> { |
490 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
491 | f.debug_struct(name:"SplitPaths" ).finish_non_exhaustive() |
492 | } |
493 | } |
494 | |
495 | /// The error type for operations on the `PATH` variable. Possibly returned from |
496 | /// [`env::join_paths()`]. |
497 | /// |
498 | /// [`env::join_paths()`]: join_paths |
499 | #[derive (Debug)] |
500 | #[stable (feature = "env" , since = "1.0.0" )] |
501 | pub struct JoinPathsError { |
502 | inner: os_imp::JoinPathsError, |
503 | } |
504 | |
505 | /// Joins a collection of [`Path`]s appropriately for the `PATH` |
506 | /// environment variable. |
507 | /// |
508 | /// # Errors |
509 | /// |
510 | /// Returns an [`Err`] (containing an error message) if one of the input |
511 | /// [`Path`]s contains an invalid character for constructing the `PATH` |
512 | /// variable (a double quote on Windows or a colon on Unix), or if the system |
513 | /// does not have a `PATH`-like variable (e.g. UEFI or WASI). |
514 | /// |
515 | /// # Examples |
516 | /// |
517 | /// Joining paths on a Unix-like platform: |
518 | /// |
519 | /// ``` |
520 | /// use std::env; |
521 | /// use std::ffi::OsString; |
522 | /// use std::path::Path; |
523 | /// |
524 | /// fn main() -> Result<(), env::JoinPathsError> { |
525 | /// # if cfg!(unix) { |
526 | /// let paths = [Path::new("/bin" ), Path::new("/usr/bin" )]; |
527 | /// let path_os_string = env::join_paths(paths.iter())?; |
528 | /// assert_eq!(path_os_string, OsString::from("/bin:/usr/bin" )); |
529 | /// # } |
530 | /// Ok(()) |
531 | /// } |
532 | /// ``` |
533 | /// |
534 | /// Joining a path containing a colon on a Unix-like platform results in an |
535 | /// error: |
536 | /// |
537 | /// ``` |
538 | /// # if cfg!(unix) { |
539 | /// use std::env; |
540 | /// use std::path::Path; |
541 | /// |
542 | /// let paths = [Path::new("/bin" ), Path::new("/usr/bi:n" )]; |
543 | /// assert!(env::join_paths(paths.iter()).is_err()); |
544 | /// # } |
545 | /// ``` |
546 | /// |
547 | /// Using `env::join_paths()` with [`env::split_paths()`] to append an item to |
548 | /// the `PATH` environment variable: |
549 | /// |
550 | /// ``` |
551 | /// use std::env; |
552 | /// use std::path::PathBuf; |
553 | /// |
554 | /// fn main() -> Result<(), env::JoinPathsError> { |
555 | /// if let Some(path) = env::var_os("PATH" ) { |
556 | /// let mut paths = env::split_paths(&path).collect::<Vec<_>>(); |
557 | /// paths.push(PathBuf::from("/home/xyz/bin" )); |
558 | /// let new_path = env::join_paths(paths)?; |
559 | /// env::set_var("PATH" , &new_path); |
560 | /// } |
561 | /// |
562 | /// Ok(()) |
563 | /// } |
564 | /// ``` |
565 | /// |
566 | /// [`env::split_paths()`]: split_paths |
567 | #[stable (feature = "env" , since = "1.0.0" )] |
568 | pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError> |
569 | where |
570 | I: IntoIterator<Item = T>, |
571 | T: AsRef<OsStr>, |
572 | { |
573 | os_imp::join_paths(paths.into_iter()).map_err(|e: JoinPathsError| JoinPathsError { inner: e }) |
574 | } |
575 | |
576 | #[stable (feature = "env" , since = "1.0.0" )] |
577 | impl fmt::Display for JoinPathsError { |
578 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
579 | self.inner.fmt(f) |
580 | } |
581 | } |
582 | |
583 | #[stable (feature = "env" , since = "1.0.0" )] |
584 | impl Error for JoinPathsError { |
585 | #[allow (deprecated, deprecated_in_future)] |
586 | fn description(&self) -> &str { |
587 | self.inner.description() |
588 | } |
589 | } |
590 | |
591 | /// Returns the path of the current user's home directory if known. |
592 | /// |
593 | /// # Unix |
594 | /// |
595 | /// - Returns the value of the 'HOME' environment variable if it is set |
596 | /// (including to an empty string). |
597 | /// - Otherwise, it tries to determine the home directory by invoking the `getpwuid_r` function |
598 | /// using the UID of the current user. An empty home directory field returned from the |
599 | /// `getpwuid_r` function is considered to be a valid value. |
600 | /// - Returns `None` if the current user has no entry in the /etc/passwd file. |
601 | /// |
602 | /// # Windows |
603 | /// |
604 | /// - Returns the value of the 'HOME' environment variable if it is set |
605 | /// (including to an empty string). |
606 | /// - Otherwise, returns the value of the 'USERPROFILE' environment variable if it is set |
607 | /// (including to an empty string). |
608 | /// - If both do not exist, [`GetUserProfileDirectory`][msdn] is used to return the path. |
609 | /// |
610 | /// [msdn]: https://docs.microsoft.com/en-us/windows/win32/api/userenv/nf-userenv-getuserprofiledirectorya |
611 | /// |
612 | /// # Deprecation |
613 | /// |
614 | /// This function is deprecated because the behaviour on Windows is not correct. |
615 | /// The 'HOME' environment variable is not standard on Windows, and may not produce |
616 | /// desired results; for instance, under Cygwin or Mingw it will return `/home/you` |
617 | /// when it should return `C:\Users\you`. |
618 | /// |
619 | /// # Examples |
620 | /// |
621 | /// ``` |
622 | /// use std::env; |
623 | /// |
624 | /// match env::home_dir() { |
625 | /// Some(path) => println!("Your home directory, probably: {}" , path.display()), |
626 | /// None => println!("Impossible to get your home dir!" ), |
627 | /// } |
628 | /// ``` |
629 | #[deprecated ( |
630 | since = "1.29.0" , |
631 | note = "This function's behavior may be unexpected on Windows. \ |
632 | Consider using a crate from crates.io instead." |
633 | )] |
634 | #[must_use ] |
635 | #[stable (feature = "env" , since = "1.0.0" )] |
636 | pub fn home_dir() -> Option<PathBuf> { |
637 | os_imp::home_dir() |
638 | } |
639 | |
640 | /// Returns the path of a temporary directory. |
641 | /// |
642 | /// The temporary directory may be shared among users, or between processes |
643 | /// with different privileges; thus, the creation of any files or directories |
644 | /// in the temporary directory must use a secure method to create a uniquely |
645 | /// named file. Creating a file or directory with a fixed or predictable name |
646 | /// may result in "insecure temporary file" security vulnerabilities. Consider |
647 | /// using a crate that securely creates temporary files or directories. |
648 | /// |
649 | /// # Platform-specific behavior |
650 | /// |
651 | /// On Unix, returns the value of the `TMPDIR` environment variable if it is |
652 | /// set, otherwise for non-Android it returns `/tmp`. On Android, since there |
653 | /// is no global temporary folder (it is usually allocated per-app), it returns |
654 | /// `/data/local/tmp`. |
655 | /// On Windows, the behavior is equivalent to that of [`GetTempPath2`][GetTempPath2] / |
656 | /// [`GetTempPath`][GetTempPath], which this function uses internally. |
657 | /// Note that, this [may change in the future][changes]. |
658 | /// |
659 | /// [changes]: io#platform-specific-behavior |
660 | /// [GetTempPath2]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppath2a |
661 | /// [GetTempPath]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppatha |
662 | /// |
663 | /// ```no_run |
664 | /// use std::env; |
665 | /// |
666 | /// fn main() { |
667 | /// let dir = env::temp_dir(); |
668 | /// println!("Temporary directory: {}" , dir.display()); |
669 | /// } |
670 | /// ``` |
671 | #[must_use ] |
672 | #[doc (alias = "GetTempPath" , alias = "GetTempPath2" )] |
673 | #[stable (feature = "env" , since = "1.0.0" )] |
674 | pub fn temp_dir() -> PathBuf { |
675 | os_imp::temp_dir() |
676 | } |
677 | |
678 | /// Returns the full filesystem path of the current running executable. |
679 | /// |
680 | /// # Platform-specific behavior |
681 | /// |
682 | /// If the executable was invoked through a symbolic link, some platforms will |
683 | /// return the path of the symbolic link and other platforms will return the |
684 | /// path of the symbolic link’s target. |
685 | /// |
686 | /// If the executable is renamed while it is running, platforms may return the |
687 | /// path at the time it was loaded instead of the new path. |
688 | /// |
689 | /// # Errors |
690 | /// |
691 | /// Acquiring the path of the current executable is a platform-specific operation |
692 | /// that can fail for a good number of reasons. Some errors can include, but not |
693 | /// be limited to, filesystem operations failing or general syscall failures. |
694 | /// |
695 | /// # Security |
696 | /// |
697 | /// The output of this function should not be trusted for anything |
698 | /// that might have security implications. Basically, if users can run |
699 | /// the executable, they can change the output arbitrarily. |
700 | /// |
701 | /// As an example, you can easily introduce a race condition. It goes |
702 | /// like this: |
703 | /// |
704 | /// 1. You get the path to the current executable using `current_exe()`, and |
705 | /// store it in a variable. |
706 | /// 2. Time passes. A malicious actor removes the current executable, and |
707 | /// replaces it with a malicious one. |
708 | /// 3. You then use the stored path to re-execute the current |
709 | /// executable. |
710 | /// |
711 | /// You expected to safely execute the current executable, but you're |
712 | /// instead executing something completely different. The code you |
713 | /// just executed run with your privileges. |
714 | /// |
715 | /// This sort of behavior has been known to [lead to privilege escalation] when |
716 | /// used incorrectly. |
717 | /// |
718 | /// [lead to privilege escalation]: https://securityvulns.com/Wdocument183.html |
719 | /// |
720 | /// # Examples |
721 | /// |
722 | /// ``` |
723 | /// use std::env; |
724 | /// |
725 | /// match env::current_exe() { |
726 | /// Ok(exe_path) => println!("Path of this executable is: {}" , |
727 | /// exe_path.display()), |
728 | /// Err(e) => println!("failed to get current exe path: {e}" ), |
729 | /// }; |
730 | /// ``` |
731 | #[stable (feature = "env" , since = "1.0.0" )] |
732 | pub fn current_exe() -> io::Result<PathBuf> { |
733 | os_imp::current_exe() |
734 | } |
735 | |
736 | /// An iterator over the arguments of a process, yielding a [`String`] value for |
737 | /// each argument. |
738 | /// |
739 | /// This struct is created by [`env::args()`]. See its documentation |
740 | /// for more. |
741 | /// |
742 | /// The first element is traditionally the path of the executable, but it can be |
743 | /// set to arbitrary text, and might not even exist. This means this property |
744 | /// should not be relied upon for security purposes. |
745 | /// |
746 | /// [`env::args()`]: args |
747 | #[must_use = "iterators are lazy and do nothing unless consumed" ] |
748 | #[stable (feature = "env" , since = "1.0.0" )] |
749 | pub struct Args { |
750 | inner: ArgsOs, |
751 | } |
752 | |
753 | /// An iterator over the arguments of a process, yielding an [`OsString`] value |
754 | /// for each argument. |
755 | /// |
756 | /// This struct is created by [`env::args_os()`]. See its documentation |
757 | /// for more. |
758 | /// |
759 | /// The first element is traditionally the path of the executable, but it can be |
760 | /// set to arbitrary text, and might not even exist. This means this property |
761 | /// should not be relied upon for security purposes. |
762 | /// |
763 | /// [`env::args_os()`]: args_os |
764 | #[must_use = "iterators are lazy and do nothing unless consumed" ] |
765 | #[stable (feature = "env" , since = "1.0.0" )] |
766 | pub struct ArgsOs { |
767 | inner: sys::args::Args, |
768 | } |
769 | |
770 | /// Returns the arguments that this program was started with (normally passed |
771 | /// via the command line). |
772 | /// |
773 | /// The first element is traditionally the path of the executable, but it can be |
774 | /// set to arbitrary text, and might not even exist. This means this property should |
775 | /// not be relied upon for security purposes. |
776 | /// |
777 | /// On Unix systems the shell usually expands unquoted arguments with glob patterns |
778 | /// (such as `*` and `?`). On Windows this is not done, and such arguments are |
779 | /// passed as-is. |
780 | /// |
781 | /// On glibc Linux systems, arguments are retrieved by placing a function in `.init_array`. |
782 | /// glibc passes `argc`, `argv`, and `envp` to functions in `.init_array`, as a non-standard |
783 | /// extension. This allows `std::env::args` to work even in a `cdylib` or `staticlib`, as it |
784 | /// does on macOS and Windows. |
785 | /// |
786 | /// # Panics |
787 | /// |
788 | /// The returned iterator will panic during iteration if any argument to the |
789 | /// process is not valid Unicode. If this is not desired, |
790 | /// use the [`args_os`] function instead. |
791 | /// |
792 | /// # Examples |
793 | /// |
794 | /// ``` |
795 | /// use std::env; |
796 | /// |
797 | /// // Prints each argument on a separate line |
798 | /// for argument in env::args() { |
799 | /// println!("{argument}" ); |
800 | /// } |
801 | /// ``` |
802 | #[stable (feature = "env" , since = "1.0.0" )] |
803 | pub fn args() -> Args { |
804 | Args { inner: args_os() } |
805 | } |
806 | |
807 | /// Returns the arguments that this program was started with (normally passed |
808 | /// via the command line). |
809 | /// |
810 | /// The first element is traditionally the path of the executable, but it can be |
811 | /// set to arbitrary text, and might not even exist. This means this property should |
812 | /// not be relied upon for security purposes. |
813 | /// |
814 | /// On Unix systems the shell usually expands unquoted arguments with glob patterns |
815 | /// (such as `*` and `?`). On Windows this is not done, and such arguments are |
816 | /// passed as-is. |
817 | /// |
818 | /// On glibc Linux systems, arguments are retrieved by placing a function in `.init_array`. |
819 | /// glibc passes `argc`, `argv`, and `envp` to functions in `.init_array`, as a non-standard |
820 | /// extension. This allows `std::env::args_os` to work even in a `cdylib` or `staticlib`, as it |
821 | /// does on macOS and Windows. |
822 | /// |
823 | /// Note that the returned iterator will not check if the arguments to the |
824 | /// process are valid Unicode. If you want to panic on invalid UTF-8, |
825 | /// use the [`args`] function instead. |
826 | /// |
827 | /// # Examples |
828 | /// |
829 | /// ``` |
830 | /// use std::env; |
831 | /// |
832 | /// // Prints each argument on a separate line |
833 | /// for argument in env::args_os() { |
834 | /// println!("{argument:?}" ); |
835 | /// } |
836 | /// ``` |
837 | #[stable (feature = "env" , since = "1.0.0" )] |
838 | pub fn args_os() -> ArgsOs { |
839 | ArgsOs { inner: sys::args::args() } |
840 | } |
841 | |
842 | #[stable (feature = "env_unimpl_send_sync" , since = "1.26.0" )] |
843 | impl !Send for Args {} |
844 | |
845 | #[stable (feature = "env_unimpl_send_sync" , since = "1.26.0" )] |
846 | impl !Sync for Args {} |
847 | |
848 | #[stable (feature = "env" , since = "1.0.0" )] |
849 | impl Iterator for Args { |
850 | type Item = String; |
851 | fn next(&mut self) -> Option<String> { |
852 | self.inner.next().map(|s: OsString| s.into_string().unwrap()) |
853 | } |
854 | fn size_hint(&self) -> (usize, Option<usize>) { |
855 | self.inner.size_hint() |
856 | } |
857 | } |
858 | |
859 | #[stable (feature = "env" , since = "1.0.0" )] |
860 | impl ExactSizeIterator for Args { |
861 | fn len(&self) -> usize { |
862 | self.inner.len() |
863 | } |
864 | fn is_empty(&self) -> bool { |
865 | self.inner.is_empty() |
866 | } |
867 | } |
868 | |
869 | #[stable (feature = "env_iterators" , since = "1.12.0" )] |
870 | impl DoubleEndedIterator for Args { |
871 | fn next_back(&mut self) -> Option<String> { |
872 | self.inner.next_back().map(|s: OsString| s.into_string().unwrap()) |
873 | } |
874 | } |
875 | |
876 | #[stable (feature = "std_debug" , since = "1.16.0" )] |
877 | impl fmt::Debug for Args { |
878 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
879 | let Self { inner: ArgsOs { inner: &Args } } = self; |
880 | f.debug_struct("Args" ).field(name:"inner" , value:inner).finish() |
881 | } |
882 | } |
883 | |
884 | #[stable (feature = "env_unimpl_send_sync" , since = "1.26.0" )] |
885 | impl !Send for ArgsOs {} |
886 | |
887 | #[stable (feature = "env_unimpl_send_sync" , since = "1.26.0" )] |
888 | impl !Sync for ArgsOs {} |
889 | |
890 | #[stable (feature = "env" , since = "1.0.0" )] |
891 | impl Iterator for ArgsOs { |
892 | type Item = OsString; |
893 | fn next(&mut self) -> Option<OsString> { |
894 | self.inner.next() |
895 | } |
896 | fn size_hint(&self) -> (usize, Option<usize>) { |
897 | self.inner.size_hint() |
898 | } |
899 | } |
900 | |
901 | #[stable (feature = "env" , since = "1.0.0" )] |
902 | impl ExactSizeIterator for ArgsOs { |
903 | fn len(&self) -> usize { |
904 | self.inner.len() |
905 | } |
906 | fn is_empty(&self) -> bool { |
907 | self.inner.is_empty() |
908 | } |
909 | } |
910 | |
911 | #[stable (feature = "env_iterators" , since = "1.12.0" )] |
912 | impl DoubleEndedIterator for ArgsOs { |
913 | fn next_back(&mut self) -> Option<OsString> { |
914 | self.inner.next_back() |
915 | } |
916 | } |
917 | |
918 | #[stable (feature = "std_debug" , since = "1.16.0" )] |
919 | impl fmt::Debug for ArgsOs { |
920 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
921 | let Self { inner: &Args } = self; |
922 | f.debug_struct("ArgsOs" ).field(name:"inner" , value:inner).finish() |
923 | } |
924 | } |
925 | |
926 | /// Constants associated with the current target |
927 | #[stable (feature = "env" , since = "1.0.0" )] |
928 | pub mod consts { |
929 | use crate::sys::env::os; |
930 | |
931 | /// A string describing the architecture of the CPU that is currently |
932 | /// in use. |
933 | /// |
934 | /// Some possible values: |
935 | /// |
936 | /// - x86 |
937 | /// - x86_64 |
938 | /// - arm |
939 | /// - aarch64 |
940 | /// - loongarch64 |
941 | /// - m68k |
942 | /// - csky |
943 | /// - mips |
944 | /// - mips64 |
945 | /// - powerpc |
946 | /// - powerpc64 |
947 | /// - riscv64 |
948 | /// - s390x |
949 | /// - sparc64 |
950 | #[stable (feature = "env" , since = "1.0.0" )] |
951 | pub const ARCH: &str = env!("STD_ENV_ARCH" ); |
952 | |
953 | /// The family of the operating system. Example value is `unix`. |
954 | /// |
955 | /// Some possible values: |
956 | /// |
957 | /// - unix |
958 | /// - windows |
959 | #[stable (feature = "env" , since = "1.0.0" )] |
960 | pub const FAMILY: &str = os::FAMILY; |
961 | |
962 | /// A string describing the specific operating system in use. |
963 | /// Example value is `linux`. |
964 | /// |
965 | /// Some possible values: |
966 | /// |
967 | /// - linux |
968 | /// - macos |
969 | /// - ios |
970 | /// - freebsd |
971 | /// - dragonfly |
972 | /// - netbsd |
973 | /// - openbsd |
974 | /// - solaris |
975 | /// - android |
976 | /// - windows |
977 | #[stable (feature = "env" , since = "1.0.0" )] |
978 | pub const OS: &str = os::OS; |
979 | |
980 | /// Specifies the filename prefix used for shared libraries on this |
981 | /// platform. Example value is `lib`. |
982 | /// |
983 | /// Some possible values: |
984 | /// |
985 | /// - lib |
986 | /// - `""` (an empty string) |
987 | #[stable (feature = "env" , since = "1.0.0" )] |
988 | pub const DLL_PREFIX: &str = os::DLL_PREFIX; |
989 | |
990 | /// Specifies the filename suffix used for shared libraries on this |
991 | /// platform. Example value is `.so`. |
992 | /// |
993 | /// Some possible values: |
994 | /// |
995 | /// - .so |
996 | /// - .dylib |
997 | /// - .dll |
998 | #[stable (feature = "env" , since = "1.0.0" )] |
999 | pub const DLL_SUFFIX: &str = os::DLL_SUFFIX; |
1000 | |
1001 | /// Specifies the file extension used for shared libraries on this |
1002 | /// platform that goes after the dot. Example value is `so`. |
1003 | /// |
1004 | /// Some possible values: |
1005 | /// |
1006 | /// - so |
1007 | /// - dylib |
1008 | /// - dll |
1009 | #[stable (feature = "env" , since = "1.0.0" )] |
1010 | pub const DLL_EXTENSION: &str = os::DLL_EXTENSION; |
1011 | |
1012 | /// Specifies the filename suffix used for executable binaries on this |
1013 | /// platform. Example value is `.exe`. |
1014 | /// |
1015 | /// Some possible values: |
1016 | /// |
1017 | /// - .exe |
1018 | /// - .nexe |
1019 | /// - .pexe |
1020 | /// - `""` (an empty string) |
1021 | #[stable (feature = "env" , since = "1.0.0" )] |
1022 | pub const EXE_SUFFIX: &str = os::EXE_SUFFIX; |
1023 | |
1024 | /// Specifies the file extension, if any, used for executable binaries |
1025 | /// on this platform. Example value is `exe`. |
1026 | /// |
1027 | /// Some possible values: |
1028 | /// |
1029 | /// - exe |
1030 | /// - `""` (an empty string) |
1031 | #[stable (feature = "env" , since = "1.0.0" )] |
1032 | pub const EXE_EXTENSION: &str = os::EXE_EXTENSION; |
1033 | } |
1034 | |