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))
}