From 3c7376035cf4f8a2e9386bb6aab970d7c1704975 Mon Sep 17 00:00:00 2001 From: Lukas Kalbertodt Date: Sun, 25 Jul 2021 10:56:46 +0200 Subject: [PATCH] Add `Config::from_file` --- src/lib.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 5f999a1..f808cae 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,5 @@ +use std::path::PathBuf; + use serde::Deserialize; #[doc(hidden)] @@ -68,6 +70,27 @@ pub trait Config: Sized { fn builder() -> Builder { Builder::new() } + + /// Load the configuration from a single file. + /// + /// If you rather want to load from multiple sources, use + /// [`Config::builder`]. Infers the file format from the file extension. + /// Returns an error in these cases: + /// + /// - The path does not have a known file extension. + /// - Loading the file fails. + /// - The file does not specify all required configuration values. + /// + /// TODO: Example + fn from_file(path: impl Into) -> Result { + let default_values = Self::Partial::default_values(); + let mut file = File::new(path)?; + if !default_values.is_complete() { + file = file.required(); + } + + Self::from_partial(file.load::()?.with_fallback(default_values)) + } } /// A potentially partial configuration object that can be directly deserialized