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

ConfigBuilder::build can now consume config #176

Closed
Closed
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
42 changes: 40 additions & 2 deletions src/config/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@ pub struct Config {
loggers: Vec<Logger>,
}

/// Any structs that impl this trait can be consumed by ConfigBuilder to make
/// build a config
pub trait ConfigBuildable {
/// Unwraps the stuct into structs the builder can build from
fn builder_unwrap(self) -> (Option<ConfigBuilder>, Root);
}

impl Config {
/// Creates a new `ConfigBuilder`.
pub fn builder() -> ConfigBuilder {
Expand Down Expand Up @@ -53,6 +60,18 @@ impl Config {
}
}

impl ConfigBuildable for Config {
fn builder_unwrap(self) -> (Option<ConfigBuilder>, Root) {
(
Some(ConfigBuilder {
appenders: self.appenders,
loggers: self.loggers,
}),
self.root,
)
}
}

/// A builder for `Config`s.
#[derive(Debug, Default)]
pub struct ConfigBuilder {
Expand Down Expand Up @@ -91,6 +110,11 @@ impl ConfigBuilder {
self
}

/// Consumes two `ConfigBuilders` and combines them into one
pub fn combine(self, ConfigBuilder { appenders, loggers }: ConfigBuilder) -> ConfigBuilder {
self.appenders(appenders).loggers(loggers)
}

/// Consumes the `ConfigBuilder`, returning the `Config`.
///
/// Unlike `build`, this method will always return a `Config` by stripping
Expand Down Expand Up @@ -156,8 +180,16 @@ impl ConfigBuilder {
}

/// Consumes the `ConfigBuilder`, returning the `Config`.
pub fn build(self, root: Root) -> Result<Config, ConfigErrors> {
let (config, errors) = self.build_lossy(root);
pub fn build(self, buildable: impl ConfigBuildable) -> Result<Config, ConfigErrors> {
let (config_builder, root) = buildable.builder_unwrap();

let (config, errors) = if let Some(config_builder) = config_builder {
self.combine(config_builder)
} else {
self
}
.build_lossy(root);

if errors.is_empty() {
Ok(config)
} else {
Expand Down Expand Up @@ -195,6 +227,12 @@ impl Root {
}
}

impl ConfigBuildable for Root {
fn builder_unwrap(self) -> (Option<ConfigBuilder>, Root) {
(None, self)
}
}

/// A builder for `Root`s.
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub struct RootBuilder {
Expand Down