1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
mod dotenv;
mod errors;
mod parse;
pub use crate::dotenv::Dotenv;
pub use crate::errors::Error;
pub type Result<T> = std::result::Result<T, Error>;
use std::env;
use std::ffi;
use std::fs;
use std::io;
use std::io::Read;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Once;
static LOAD: Once = Once::new();
pub fn var<K: AsRef<ffi::OsStr>>(key: K) -> Result<String> {
LOAD.call_once(|| {
load().ok();
});
env::var(key).map_err(Error::from)
}
pub fn vars() -> env::Vars {
LOAD.call_once(|| {
load().ok();
});
env::vars()
}
fn find<P: AsRef<Path>>(filename: P) -> Result<PathBuf> {
let filename = filename.as_ref();
env::current_dir()?
.ancestors()
.map(|dir| dir.join(filename))
.find(|path| path.is_file())
.ok_or_else(Error::not_found)
}
pub fn load() -> Result<PathBuf> {
let path = find(".env")?;
from_path(&path).map(|vars| {
vars.load();
path
})
}
pub fn from_filename<P: AsRef<Path>>(filename: P) -> Result<Dotenv> {
let path = find(filename)?;
from_path(path)
}
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Dotenv> {
let file = fs::File::open(path)?;
from_read(file)
}
pub fn from_read<R: Read>(read: R) -> Result<Dotenv> {
let mut buf = String::new();
let mut reader = io::BufReader::new(read);
reader.read_to_string(&mut buf)?;
Ok(Dotenv::new(buf))
}