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
20pub 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
41pub 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
68pub fn load() -> Result<PathBuf> {
72 let path = find(".env")?;
73 from_path(&path).map(|vars| {
74 vars.load();
75 path
76 })
77}
78
79pub fn from_filename<P: AsRef<Path>>(filename: P) -> Result<Dotenv> {
83 let path = find(filename)?;
84 from_path(path)
85}
86
87pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Dotenv> {
91 let file = fs::File::open(path)?;
92 from_read(file)
93}
94
95pub 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}