Skip to content
Draft
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
24 changes: 24 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 confik/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ default = ["env", "toml"]
env = ["dep:envious"]
json = ["dep:serde_json"]
ron-0_12 = ["dep:ron-0_12"]
serde_ini-0_2 = ["dep:serde_ini-0_2"]
toml = ["dep:toml"]
yaml_serde-0_10 = ["dep:yaml_serde-0_10"]

Expand Down Expand Up @@ -63,6 +64,7 @@ thiserror = "2"
# Source types
envious = { version = "0.2", optional = true }
ron-0_12 = { package = "ron", version = "0.12", optional = true }
serde_ini-0_2 = { package = "serde_ini", version = "0.2", optional = true }
serde_json = { version = "1", optional = true }
toml = { version = "1", optional = true, default-features = false, features = ["parse", "serde"] }
yaml_serde-0_10 = { package = "yaml_serde", version = "0.10", optional = true }
Expand Down
3 changes: 2 additions & 1 deletion confik/src/lib.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,11 +123,12 @@ When the `tracing` feature is enabled, reload errors in the signal handler will
A [`Source`] is any type that can create [`ConfigurationBuilder`]s. This crate implements the following sources:

- [`EnvSource`]: Loads configuration from environment variables using the [`envious`] crate. Requires the `env` feature. (Enabled by default.)
- [`FileSource`]: Loads configuration from a file, detecting `.toml`, `.json`, `.ron`, `.yaml`, or `.yml` files based on the file extension. Requires the matching `toml`, `json`, `ron-0_12`, or `yaml_serde-0_10` feature. (`toml` is enabled by default.)
- [`FileSource`]: Loads configuration from a file, detecting `.toml`, `.json`, `.ron`, `.yaml`, `.yml`, or `.ini` files based on the file extension. Requires the matching `toml`, `json`, `ron-0_12`, `yaml_serde-0_10`, or `serde_ini-0_2` feature. (`toml` is enabled by default.)
- [`TomlSource`]: Loads configuration from a TOML string literal. Requires the `toml` feature. (Enabled by default.)
- [`JsonSource`]: Loads configuration from a JSON string literal. Requires the `json` feature.
- [`RonSource`]: Loads configuration from a RON string literal. Requires the `ron-0_12` feature.
- [`YamlSource`]: Loads configuration from a YAML string literal. Requires the `yaml_serde-0_10` feature.
- [`IniSource`]: Loads configuration from an INI string literal. Requires the `serde_ini-0_2` feature.
- [`OffsetSource`]: Loads configuration from an inner source that is provided to it, but applied to a particular offset of the root configuration builder.

## Secrets
Expand Down
2 changes: 2 additions & 0 deletions confik/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ use self::path::Path;
pub use self::reloading::{ReloadCallback, ReloadableConfig, ReloadingConfig};
#[cfg(feature = "env")]
pub use self::sources::env_source::EnvSource;
#[cfg(feature = "serde_ini-0_2")]
pub use self::sources::ini_source::IniSource;
#[cfg(feature = "json")]
pub use self::sources::json_source::JsonSource;
#[cfg(feature = "ron-0_12")]
Expand Down
38 changes: 38 additions & 0 deletions confik/src/sources/file_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ enum FileErrorKind {
#[error(transparent)]
Json(#[from] serde_json::Error),

#[cfg(feature = "serde_ini-0_2")]
#[error(transparent)]
Ini(#[from] serde_ini_0_2::error::Error),

#[cfg(feature = "ron-0_12")]
#[error(transparent)]
Ron(#[from] ron_0_12::error::SpannedError),
Expand All @@ -57,6 +61,7 @@ impl FileSource {
/// The deserialization method will be determined by the file extension.
///
/// Supported extensions:
/// - `ini`
/// - `toml`
/// - `json`
/// - `ron`
Expand Down Expand Up @@ -100,6 +105,16 @@ impl FileSource {
}
}

Some("ini") => {
cfg_if! {
if #[cfg(feature = "serde_ini-0_2")] {
Ok(serde_ini_0_2::from_str(&contents).map_err(serde_ini_0_2::error::Error::from)?)
} else {
Err(FileErrorKind::MissingFeatureForExtension("ini"))
}
}
}

Some("ron") => {
cfg_if! {
if #[cfg(feature = "ron-0_12")] {
Expand Down Expand Up @@ -207,6 +222,29 @@ mod tests {
dir.close().unwrap();
}

#[cfg(feature = "serde_ini-0_2")]
#[test]
fn ini() {
let dir = tempfile::TempDir::new().unwrap();

let ini_path = dir.path().join("config.ini");

fs::write(&ini_path, "").unwrap();
let source = FileSource::new(&ini_path);
let err = source.deserialize::<Option<SimpleConfig>>().unwrap_err();
assert!(
err.to_string().contains("missing field"),
"unexpected error message: {err}",
);

fs::write(&ini_path, "foo = 42\n").unwrap();
let source = FileSource::new(&ini_path);
let config = source.deserialize::<Option<SimpleConfig>>().unwrap();
assert_eq!(config.unwrap().foo, 42);

dir.close().unwrap();
}

#[cfg(feature = "toml")]
#[test]
fn toml() {
Expand Down
95 changes: 95 additions & 0 deletions confik/src/sources/ini_source.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
use std::{borrow::Cow, error::Error, fmt};

use crate::{ConfigurationBuilder, Source};

/// A [`Source`] containing raw INI data.
#[derive(Clone)]
pub struct IniSource<'a> {
contents: Cow<'a, str>,
allow_secrets: bool,
}

impl<'a> IniSource<'a> {
/// Creates a [`Source`] containing raw INI data.
pub fn new(contents: impl Into<Cow<'a, str>>) -> Self {
Self {
contents: contents.into(),
allow_secrets: false,
}
}

/// Allows this source to contain secrets.
pub fn allow_secrets(mut self) -> Self {
self.allow_secrets = true;
self
}
}

impl<T: ConfigurationBuilder> Source<T> for IniSource<'_> {
fn allows_secrets(&self) -> bool {
self.allow_secrets
}

fn provide(&self) -> Result<T, Box<dyn Error + Sync + Send>> {
Ok(serde_ini_0_2::from_str(&self.contents)?)
}
}

impl fmt::Debug for IniSource<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("IniSource")
.field("allow_secrets", &self.allow_secrets)
.finish_non_exhaustive()
}
}

#[cfg(test)]
mod tests {
use confik_macros::Configuration;

use super::*;

#[derive(Debug, PartialEq, Eq, serde::Deserialize, Configuration)]
struct TestConfig {
value: usize,
}

#[test]
fn provides_ini_data() {
let source = IniSource::new("value = 42\n");

let config =
<IniSource<'_> as Source<<TestConfig as crate::Configuration>::Builder>>::provide(
&source,
)
.unwrap()
.try_build()
.unwrap();

assert_eq!(config, TestConfig { value: 42 });
}

#[test]
fn propagates_parse_errors() {
let source = IniSource::new("value\n");

let err =
match <IniSource<'_> as Source<<TestConfig as crate::Configuration>::Builder>>::provide(
&source,
) {
Ok(_) => panic!("INI parsing should fail"),
Err(err) => err,
};

assert!(!err.to_string().is_empty());
}

#[test]
fn allow_secrets_enables_secret_loading() {
let source = IniSource::new("value = 42\n").allow_secrets();

assert!(<IniSource<'_> as Source<
<TestConfig as crate::Configuration>::Builder,
>>::allows_secrets(&source));
}
}
3 changes: 3 additions & 0 deletions confik/src/sources/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ pub(crate) mod json_source;
#[cfg(feature = "ron-0_12")]
pub(crate) mod ron_source;

#[cfg(feature = "serde_ini-0_2")]
pub(crate) mod ini_source;

#[cfg(feature = "env")]
pub(crate) mod env_source;

Expand Down
21 changes: 21 additions & 0 deletions confik/tests/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,27 @@ mod json {
}
}

#[cfg(feature = "serde_ini-0_2")]
mod ini {
use confik::{ConfigBuilder, IniSource};

use crate::{Target, TargetEnum};

#[test]
fn check_ini() {
assert_eq!(
ConfigBuilder::<Target>::default()
.override_with(IniSource::new("a = 5\nb = Second\n"))
.try_build()
.expect("INI deserialization should succeed"),
Target {
a: 5,
b: TargetEnum::Second,
}
);
}
}

#[cfg(feature = "ron-0_12")]
mod ron {
use confik::{ConfigBuilder, RonSource};
Expand Down
21 changes: 21 additions & 0 deletions confik/tests/secret/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,27 @@ mod json {
}
}

#[cfg(feature = "serde_ini-0_2")]
mod ini {
use assert_matches::assert_matches;
use confik::{ConfigBuilder, Error, IniSource};

use super::NotSecret;

#[test]
fn check_ini_is_not_secret() {
let target = ConfigBuilder::<NotSecret>::default()
.override_with(IniSource::new("[public]\npublic = 1\nsecret = 2\n"))
.try_build()
.expect_err("INI deserialization is not a secret source");

assert_matches!(
&target,
Error::UnexpectedSecret(path, _) if path.to_string().contains("public.secret")
);
}
}

#[cfg(feature = "ron-0_12")]
mod ron {
use assert_matches::assert_matches;
Expand Down
Loading