dotenv/
lib.rs

1mod dotenv;
2mod errors;
3mod parse;
4
5pub use crate::dotenv::Dotenv;
6pub use crate::errors::Error;
7pub type Result<T> = std::result::Result<T, Error>;
8
9use std::env;
10use std::ffi;
11use std::fs;
12use std::io;
13use std::io::Read;
14use std::path::Path;
15use std::path::PathBuf;
16use std::sync::Once;
17
18static LOAD: Once = Once::new();
19
20/// Get the value for an environment variable.
21///
22/// The value is `Ok(s)` if the environment variable is present and valid unicode.
23///
24/// Note: this function gets values from any visible environment variable key,
25/// regardless of whether a *.env* file was loaded.
26///
27/// # Examples:
28///
29/// ```no_run
30/// let value = dotenv::var("HOME").unwrap();
31/// println!("{}", value);  // prints `/home/foo`
32/// ```
33pub fn var<K: AsRef<ffi::OsStr>>(key: K) -> Result<String> {
34    LOAD.call_once(|| {
35        load().ok();
36    });
37
38    env::var(key).map_err(Error::from)
39}
40
41/// Return an iterator of `(key, value)` pairs for all environment variables of the current process.
42/// The returned iterator contains a snapshot of the process's environment variables at the time of invocation. Modifications to environment variables afterwards will not be reflected.
43///
44/// # Examples:
45///
46/// ```no_run
47/// use std::io;
48///
49/// let result: Vec<(String, String)> = dotenv::vars().collect();
50/// ```
51pub fn vars() -> env::Vars {
52    LOAD.call_once(|| {
53        load().ok();
54    });
55
56    env::vars()
57}
58
59fn find<P: AsRef<Path>>(filename: P) -> Result<PathBuf> {
60    let filename = filename.as_ref();
61    env::current_dir()?
62        .ancestors()
63        .map(|dir| dir.join(filename))
64        .find(|path| path.is_file())
65        .ok_or_else(Error::not_found)
66}
67
68/// Load the *.env* file from the current directory or its parents.
69///
70/// Fails if the file is not found.
71pub fn load() -> Result<PathBuf> {
72    let path = find(".env")?;
73    from_path(&path).map(|vars| {
74        vars.load();
75        path
76    })
77}
78
79/// Create [Dotenv] from the specified file.
80///
81/// Fails if the file is not found.
82pub fn from_filename<P: AsRef<Path>>(filename: P) -> Result<Dotenv> {
83    let path = find(filename)?;
84    from_path(path)
85}
86
87/// Create [Dotenv] from the specified path.
88///
89/// Fails if the file is not found.
90pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Dotenv> {
91    let file = fs::File::open(path)?;
92    from_read(file)
93}
94
95/// Create [Dotenv] from [Read](std::io::Read).
96///
97/// This is useful for loading environment variables from from IPC or the network.
98pub fn from_read<R: Read>(read: R) -> Result<Dotenv> {
99    let mut buf = String::new();
100    let mut reader = io::BufReader::new(read);
101    reader.read_to_string(&mut buf)?;
102
103    Ok(Dotenv::new(buf))
104}