Skip to content

Commit

Permalink
allow to override existing env vars (#41)
Browse files Browse the repository at this point in the history
  • Loading branch information
tshepang committed Nov 22, 2022
1 parent 42fa001 commit d1f8a15
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
12 changes: 12 additions & 0 deletions dotenv/src/iter.rs
Expand Up @@ -35,6 +35,18 @@ impl<R: Read> Iter<R> {
Ok(())
}

/// A version of [load] that overrides older variables in case of duplicates.
pub fn overload(mut self) -> Result<()> {
self.remove_bom()?;

for item in self {
let (key, value) = item?;
env::set_var(key, value);
}

Ok(())
}

fn remove_bom(&mut self) -> Result<()> {
let buffer = self.lines.buf.fill_buf().map_err(Error::Io)?;
// https://www.compart.com/en/unicode/U+FEFF
Expand Down
13 changes: 13 additions & 0 deletions dotenv/src/lib.rs
Expand Up @@ -181,6 +181,19 @@ pub fn dotenv() -> Result<PathBuf> {
Ok(path)
}

/// A version of [dotenv] that overrides existing env vars
///
/// # Examples
/// ```
/// use dotenvy::overload;
/// overload().ok();
/// ```
pub fn overload() -> Result<PathBuf> {
let (path, iter) = Finder::new().find()?;
iter.overload()?;
Ok(path)
}

/// Returns an iterator over environment variables.
///
/// # Examples
Expand Down
23 changes: 23 additions & 0 deletions dotenv/tests/test-overload.rs
@@ -0,0 +1,23 @@
mod common;

use std::{env, error::Error, result::Result};

use dotenvy::*;

use crate::common::*;

#[test]
fn test_overload() -> Result<(), Box<dyn Error>> {
let dir = tempdir_with_dotenv(
"
var=old
var=new
",
)?;
overload()?;
assert_eq!(var("var")?, "new");

env::set_current_dir(dir.path().parent().unwrap())?;
dir.close()?;
Ok(())
}

0 comments on commit d1f8a15

Please sign in to comment.