Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for UTF-8 BOM encoding #28

Merged
merged 1 commit into from Oct 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 13 additions & 1 deletion dotenv/src/iter.rs
Expand Up @@ -22,7 +22,9 @@ impl<R: Read> Iter<R> {
}

/// Loads all variables found in the `reader` into the environment.
pub fn load(self) -> Result<()> {
pub fn load(mut self) -> Result<()> {
self.remove_bom()?;

for item in self {
let (key, value) = item?;
if env::var(&key).is_err() {
Expand All @@ -32,6 +34,16 @@ impl<R: Read> Iter<R> {

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
if buffer.starts_with(&[0xEF, 0xBB, 0xBF]) {
// remove the BOM from the bufreader
self.lines.buf.consume(3);
}
Ok(())
}
}

struct QuotedLines<B> {
Expand Down
22 changes: 22 additions & 0 deletions dotenv/tests/test-ignore-bom.rs
@@ -0,0 +1,22 @@
mod common;

use crate::common::*;
use dotenvy::*;
use std::{env, error::Error, result::Result};

#[test]
fn test_ignore_bom() -> Result<(), Box<dyn Error>> {
let bom = "\u{feff}";
let dir = tempdir_with_dotenv(&format!("{}TESTKEY=test_val", bom))?;

let mut path = env::current_dir()?;
path.push(".env");

from_path(&path)?;

assert_eq!(env::var("TESTKEY")?, "test_val");

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