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
128 changes: 128 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/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Unreleased

- Add Corn source support behind new crate feature `corn-0_10` (off-by-default).

## 0.15.11

- Add a new helper `MergingUnsetBuilder` and trait `MergingWithUnset`, for aiding in building of custom `Configuration` implementations. See the docs on `MergingWithUnset` for a worked example.
Expand Down
2 changes: 2 additions & 0 deletions confik/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ default = ["env", "toml"]
# Source types
env = ["dep:envious"]
json = ["dep:serde_json"]
corn-0_10 = ["dep:libcorn-0_10"]
ron-0_12 = ["dep:ron-0_12"]
toml = ["dep:toml"]
yaml_serde-0_10 = ["dep:yaml_serde-0_10"]
Expand Down Expand Up @@ -62,6 +63,7 @@ thiserror = "2"

# Source types
envious = { version = "0.2", optional = true }
libcorn-0_10 = { package = "libcorn", version = "0.10", optional = true }
ron-0_12 = { package = "ron", version = "0.12", optional = true }
serde_json = { version = "1", optional = true }
toml = { version = "1", optional = true, default-features = false, features = ["parse", "serde"] }
Expand Down
3 changes: 2 additions & 1 deletion confik/src/lib.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,9 +131,10 @@ When the `tracing` feature is enabled, reload errors in the signal handler are a
A [`Source`] is anything that can produce a partial [`ConfigurationBuilder`]. `confik` ships with the following source types:

- [`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`, `.corn`, `.ron`, `.yaml`, or `.yml` files based on the file extension. Requires the matching `toml`, `json`, `corn-0_10`, `ron-0_12`, or `yaml_serde-0_10` 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.
- [`CornSource`]: Loads configuration from a Corn string literal. Requires the `corn-0_10` 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.
- [`OffsetSource`]: Loads configuration from an inner source that is provided to it, but applied to a particular offset of the root configuration builder.
Expand Down
2 changes: 2 additions & 0 deletions confik/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ mod third_party;
use self::path::Path;
#[cfg(feature = "reloading")]
pub use self::reloading::{ReloadCallback, ReloadableConfig, ReloadingConfig};
#[cfg(feature = "corn-0_10")]
pub use self::sources::corn_source::CornSource;
#[cfg(feature = "env")]
pub use self::sources::env_source::EnvSource;
#[cfg(feature = "json")]
Expand Down
95 changes: 95 additions & 0 deletions confik/src/sources/corn_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 Corn data.
#[derive(Clone)]
pub struct CornSource<'a> {
contents: Cow<'a, str>,
allow_secrets: bool,
}

impl<'a> CornSource<'a> {
/// Creates a [`Source`] containing raw Corn 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 CornSource<'_> {
fn allows_secrets(&self) -> bool {
self.allow_secrets
}

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

impl fmt::Debug for CornSource<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CornSource")
.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_corn_data() {
let source = CornSource::new("{ value = 42 }");

let config =
<CornSource<'_> 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 = CornSource::new("{ value = ");

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

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

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

assert!(<CornSource<'_> as Source<
<TestConfig as crate::Configuration>::Builder,
>>::allows_secrets(&source));
}
}
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 = "corn-0_10")]
#[error(transparent)]
Corn(#[from] libcorn_0_10::error::Error),

#[cfg(feature = "ron-0_12")]
#[error(transparent)]
Ron(#[from] ron_0_12::error::SpannedError),
Expand All @@ -60,6 +64,7 @@ impl FileSource {
/// - `toml`
/// - `json`
/// - `ron`
/// - `corn`
/// - `yaml`
/// - `yml`
pub fn new(path: impl Into<PathBuf>) -> Self {
Expand Down Expand Up @@ -100,6 +105,16 @@ impl FileSource {
}
}

Some("corn") => {
cfg_if! {
if #[cfg(feature = "corn-0_10")] {
Ok(libcorn_0_10::from_str(&contents)?)
} else {
Err(FileErrorKind::MissingFeatureForExtension("corn"))
}
}
}

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

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

let corn_path = dir.path().join("config.corn");

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

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

dir.close().unwrap();
}

#[cfg(feature = "yaml_serde-0_10")]
#[test]
fn yaml() {
Expand Down
Loading
Loading