Skip to content

fix: Support reading from files that have an UTF-8 Byte Order Mark #670

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

Merged
merged 2 commits into from
Jul 9, 2025
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion src/file/source/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,17 @@ where
.unwrap_or_else(|| filename.clone());

// Read contents from file
let text = fs::read_to_string(filename)?;
let buf = fs::read(filename)?;

// If it exists, skip the UTF-8 BOM byte sequence: EF BB BF
let buf = if buf.len() >= 3 && &buf[0..3] == b"\xef\xbb\xbf" {
&buf[3..]
} else {
&buf
};

let c = String::from_utf8_lossy(buf);
let text = c.into_owned();

Ok(FileSourceResult {
uri: Some(uri.to_string_lossy().into_owned()),
Expand Down
4 changes: 4 additions & 0 deletions tests/testsuite/file-ext-with-bom.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"debug": true,
"production": false
}
12 changes: 12 additions & 0 deletions tests/testsuite/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,18 @@ fn test_file_ext() {
assert_eq!(c.get("production").ok(), Some(false));
}

#[test]
#[cfg(feature = "json")]
fn test_file_ext_with_utf8_bom() {
let c = Config::builder()
.add_source(File::with_name("tests/testsuite/file-ext-with-bom.json"))
.build()
.unwrap();

assert_eq!(c.get("debug").ok(), Some(true));
assert_eq!(c.get("production").ok(), Some(false));
}

#[test]
#[cfg(feature = "json")]
fn test_file_second_ext() {
Expand Down
Loading