Skip to content
Open
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
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ yaml = ["yaml-rust2"]
ini = ["rust-ini"]
json5 = ["json5_rs", "dep:serde-untagged"]
corn = ["dep:corn"]
dotenv = ["dep:dotenvy"]
convert-case = ["convert_case"]
preserve_order = ["indexmap", "toml?/preserve_order", "serde_json?/preserve_order", "ron?/indexmap"]
async = ["async-trait"]
Expand All @@ -143,6 +144,7 @@ rust-ini = { version = "0.21.3", optional = true }
ron = { version = "0.8.1", optional = true }
json5_rs = { version = "0.4.1", optional = true, package = "json5" }
corn = { version = "0.10.0", optional = true, package = "libcorn" }
dotenvy = { version = "0.15.7", optional = true }
indexmap = { version = "2.11.4", features = ["serde"], optional = true }
convert_case = { version = "0.6.0", optional = true }
pathdiff = "0.2.3"
Expand Down
31 changes: 31 additions & 0 deletions src/file/format/dotenv.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
use std::error::Error;
use std::io::Cursor;

use dotenvy::from_read_iter;

use crate::map::Map;
use crate::value::{Value, ValueKind};

pub(crate) fn parse(
uri: Option<&String>,
text: &str,
) -> Result<Map<String, Value>, Box<dyn Error + Send + Sync>> {
let mut map: Map<String, Value> = Map::new();
let cursor = Cursor::new(text);

for item in from_read_iter(cursor) {
let (key, mut value) = item?;

let os_env_vars = std::env::vars_os();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should not be doing manual layering, that is what the ConfigBuilder is for.

Copy link
Author

@chickencoding123 chickencoding123 Oct 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dotenvy overrides OS var which is inconsistent with existing FileFormat in this crate. Manual layering is appealing here because file formats sit below ConfigBuilder in the hierarchy. Coupling a ConfigBuilder inside a file format will lead to difficult refactoring in the future.

I think for the purposes of this specific file format, simple env override should suffice?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Manual layering is appealing here because file formats sit below ConfigBuilder in the hierarchy. Coupling a ConfigBuilder inside a file format will lead to difficult refactoring in the future.

Environment and each File are manually added as sources and the user has control over the precedence order. However we support DotEnv, it will be similar, so we don't need to do this here. If we did,. it would belong in Environment which is what is handling the OS vars.

for (os_string_key, os_string_value) in os_env_vars {
let string_key: String = os_string_key.to_string_lossy().into_owned();
if string_key == key {
value = os_string_value.to_string_lossy().into_owned();
}
}

map.insert(key, Value::new(uri, ValueKind::String(value)));
}

Ok(map)
}
17 changes: 17 additions & 0 deletions src/file/format/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ mod json5;
#[cfg(feature = "corn")]
mod corn;

#[cfg(feature = "dotenv")]
mod dotenv;

/// File formats provided by the library.
///
/// Although it is possible to define custom formats using [`Format`] trait it is recommended to use `FileFormat` if possible.
Expand Down Expand Up @@ -57,6 +60,10 @@ pub enum FileFormat {
/// Corn (parsed with `libcorn`)
#[cfg(feature = "corn")]
Corn,

/// Dotenv (parsed with `dotenvy`)
#[cfg(feature = "dotenv")]
Dotenv,
Comment on lines +63 to +66
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this work as another FileFormat / Source? I suspect there is a lot of design overlap with Environment that we'd want to make this functionality on that.

Copy link
Author

@chickencoding123 chickencoding123 Oct 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is another FileFormat. You can see the usage from the tests (added snippet for ref. here). It is similar to existing file formats. Also dotenvy dependency will take care of the overlap, if any. However I ensured OS env take precedence as per existing file formats.

 let s = Config::builder()
        .add_source(config::File::from_str(
            r#"
                FOO=bar
                BAZ=qux
            "#,
            config::FileFormat::Dotenv,
        ))
        .build()
        .unwrap();

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI resolving conversations that aren't ready for it can make PR reviews more difficult on maintainers. You should be pretty confident that you understood the concern and responded to it as the maintainer expected to resolve it. That was not the case here.

Some traits of dotenv are

  • Stringly typed (so is ini)
  • Unstructured

Both of these characteristics are shared with Environment which has a lot of functionality for solving these problems. In fact, this is another form of environment variables! The only difference is it also shares some of the file loading characteristics of file formats.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've raised this (and other questions) at #16 (comment) as I prefer to work out high level designs in Issues rather than PRs.

}

impl FileFormat {
Expand All @@ -76,6 +83,8 @@ impl FileFormat {
FileFormat::Json5,
#[cfg(feature = "corn")]
FileFormat::Corn,
#[cfg(feature = "dotenv")]
FileFormat::Dotenv,
]
}

Expand All @@ -102,13 +111,17 @@ impl FileFormat {
#[cfg(feature = "corn")]
FileFormat::Corn => &["corn"],

#[cfg(feature = "dotenv")]
FileFormat::Dotenv => &["dotenv"],

#[cfg(all(
not(feature = "toml"),
not(feature = "json"),
not(feature = "yaml"),
not(feature = "ini"),
not(feature = "ron"),
not(feature = "json5"),
not(feature = "dotenv"),
))]
_ => unreachable!("No features are enabled, this library won't work without features"),
}
Expand Down Expand Up @@ -141,13 +154,17 @@ impl FileFormat {
#[cfg(feature = "corn")]
FileFormat::Corn => corn::parse(uri, text),

#[cfg(feature = "dotenv")]
FileFormat::Dotenv => dotenv::parse(uri, text),

#[cfg(all(
not(feature = "toml"),
not(feature = "json"),
not(feature = "yaml"),
not(feature = "ini"),
not(feature = "ron"),
not(feature = "json5"),
not(feature = "dotenv"),
))]
_ => unreachable!("No features are enabled, this library won't work without features"),
}
Expand Down
78 changes: 78 additions & 0 deletions tests/testsuite/file_dotenv.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
#![cfg(feature = "dotenv")]

use config::Config;
use std::env;

#[test]
fn basic_dotenv() {
let s = Config::builder()
.add_source(config::File::from_str(
r#"
FOO=bar
BAZ=qux
"#,
config::FileFormat::Dotenv,
))
.build()
.unwrap();

assert_eq!(s.get::<String>("FOO").unwrap(), "bar");
assert_eq!(s.get::<String>("BAZ").unwrap(), "qux");
}

#[test]
fn optional_variables() {
let s = Config::builder()
.add_source(config::File::from_str(
r#"
FOO=bar
BAZ=${FOO}
BAR=${UNDEFINED:-}
"#,
config::FileFormat::Dotenv,
))
.build()
.unwrap();

assert_eq!(s.get::<String>("BAR").unwrap(), "");
}

#[test]
fn multiple_files() {
let s = Config::builder()
.add_source(config::File::from_str(
r#"
FOO=bar
"#,
config::FileFormat::Dotenv,
))
.add_source(config::File::from_str(
r#"
BAZ=qux
"#,
config::FileFormat::Dotenv,
))
.build()
.unwrap();

assert_eq!(s.get::<String>("FOO").unwrap(), "bar");
assert_eq!(s.get::<String>("BAZ").unwrap(), "qux");
}

#[test]
fn environment_overrides() {
env::set_var("FOOBAR", "env_value");

let s = Config::builder()
.add_source(config::File::from_str(
r#"
FOOBAR=file_value
"#,
config::FileFormat::Dotenv,
))
.add_source(config::Environment::with_prefix("env").separator("_"))
.build()
.unwrap();

assert_eq!(s.get::<String>("FOOBAR").unwrap(), "env_value");
}
1 change: 1 addition & 0 deletions tests/testsuite/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ pub mod env;
pub mod errors;
pub mod file;
pub mod file_corn;
pub mod file_dotenv;
pub mod file_ini;
pub mod file_json;
pub mod file_json5;
Expand Down
Loading