config-0.11.0/.cargo_vcs_info.json0000644000000001120000000000000123510ustar { "git": { "sha1": "817b37807572418f48e3d660e3931d265e32ab28" } } config-0.11.0/.editorconfig000064400000000000000000000001620000000000000136010ustar 00000000000000root = true [*] indent_style = space indent_size = 4 insert_final_newline = true trim_trailing_whitespace = true config-0.11.0/.github/workflows/msrv.yml000064400000000000000000000042020000000000000162320ustar 00000000000000on: [push, pull_request] name: MSRV jobs: check: name: Check runs-on: ubuntu-latest strategy: matrix: rust: - stable - beta - nightly steps: - name: Checkout sources uses: actions/checkout@v2 - name: Install toolchain uses: actions-rs/toolchain@v1 with: toolchain: ${{ matrix.rust }} override: true - name: Run cargo check uses: actions-rs/cargo@v1 with: command: check test: name: Test Suite runs-on: ubuntu-latest strategy: matrix: rust: - stable - beta - nightly steps: - name: Checkout sources uses: actions/checkout@v2 - name: Install toolchain uses: actions-rs/toolchain@v1 with: toolchain: ${{ matrix.rust }} override: true - name: Run cargo test uses: actions-rs/cargo@v1 with: command: test fmt: name: Rustfmt runs-on: ubuntu-latest strategy: matrix: rust: - stable - beta - nightly steps: - name: Checkout sources uses: actions/checkout@v2 - name: Install toolchain uses: actions-rs/toolchain@v1 with: toolchain: ${{ matrix.rust }} override: true - name: Install rustfmt run: rustup component add rustfmt - name: Run cargo fmt uses: actions-rs/cargo@v1 with: command: fmt args: --all -- --check clippy: name: Clippy runs-on: ubuntu-latest strategy: matrix: rust: - stable - beta - nightly steps: - name: Checkout sources uses: actions/checkout@v2 - name: Install toolchain uses: actions-rs/toolchain@v1 with: toolchain: ${{ matrix.rust }} override: true - name: Install clippy run: rustup component add clippy - name: Run cargo clippy uses: actions-rs/cargo@v1 with: command: clippy args: -- -D warnings config-0.11.0/.gitignore000064400000000000000000000000220000000000000131070ustar 00000000000000target Cargo.lock config-0.11.0/CHANGELOG.md000064400000000000000000000151050000000000000127400ustar 00000000000000# Change Log All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## 0.11.0 - 2021-03-17 - The `Config` type got a builder-pattern `with_merged()` method [#166]. - A `Config::set_once()` function was added, to set an value that can be overwritten by `Config::merge`ing another configuration [#172] - serde_hjson is, if enabled, pulled in without default features. This is due to a bug in serde_hjson, see [#169] for more information. - Testing is done on github actions [#175] [#166]: https://github.com/mehcode/config-rs/pull/166 [#172]: https://github.com/mehcode/config-rs/pull/172 [#169]: https://github.com/mehcode/config-rs/pull/169 [#175]: https://github.com/mehcode/config-rs/pull/169 ## 0.10.1 - 2019-12-07 - Allow enums as configuration keys [#119] [#119]: https://github.com/mehcode/config-rs/pull/119 ## 0.10.0 - 2019-12-07 - Remove lowercasing of keys (unless the key is coming from an environment variable). - Update nom to 5.x ## 0.9.3 - 2019-05-09 - Support deserializing to a struct with `#[serde(default)]` [#106] [#106]: https://github.com/mehcode/config-rs/pull/106 ## 0.9.2 - 2019-01-03 - Support reading `enum`s from configuration. [#85] - Improvements to error path (attempting to propagate path). [#89] - Fix UB in monomorphic expansion. We weren't re-exporting dependent types. [#91] [#85]: https://github.com/mehcode/config-rs/pull/85 [#89]: https://github.com/mehcode/config-rs/pull/89 [#91]: https://github.com/mehcode/config-rs/issues/91 ## 0.9.1 - 2018-09-25 - Allow Environment variable collection to ignore empty values. [#78] ```rust // Empty env variables will not be collected Environment::with_prefix("APP").ignore_empty(true) ``` [#78]: https://github.com/mehcode/config-rs/pull/78 ## 0.9.0 - 2018-07-02 - **Breaking Change:** Environment does not declare a separator by default. ```rust // 0.8.0 Environment::with_prefix("APP") // 0.9.0 Environment::with_prefix("APP").separator("_") ``` - Add support for INI. [#72] - Add support for newtype structs. [#71] - Fix bug with array set by path. [#69] - Update to nom 4. [#63] [#72]: https://github.com/mehcode/config-rs/pull/72 [#71]: https://github.com/mehcode/config-rs/pull/71 [#69]: https://github.com/mehcode/config-rs/pull/69 [#63]: https://github.com/mehcode/config-rs/pull/63 ## 0.8.0 - 2018-01-26 - Update lazy_static and yaml_rust ## 0.7.1 - 2018-01-26 - Be compatible with nom's verbose_errors feature (#50)[https://github.com/mehcode/config-rs/pull/50] - Add `derive(PartialEq)` for Value (#54)[https://github.com/mehcode/config-rs/pull/54] ## 0.7.0 - 2017-08-05 - Fix conflict with `serde_yaml`. [#39] [#39]: https://github.com/mehcode/config-rs/issues/39 - Implement `Source` for `Config`. - Implement `serde::de::Deserializer` for `Config`. `my_config.deserialize` may now be called as either `Deserialize::deserialize(my_config)` or `my_config.try_into()`. - Remove `ConfigResult`. The builder pattern requires either `.try_into` as the final step _or_ the initial `Config::new()` to be bound to a slot. Errors must also be handled on each call instead of at the end of the chain. ```rust let mut c = Config::new(); c .merge(File::with_name("Settings")).unwrap() .merge(Environment::with_prefix("APP")).unwrap(); ``` ```rust let c = Config::new() .merge(File::with_name("Settings")).unwrap() .merge(Environment::with_prefix("APP")).unwrap() // LLVM should be smart enough to remove the actual clone operation // as you are cloning a temporary that is dropped at the same time .clone(); ``` ```rust let mut s: Settings = Config::new() .merge(File::with_name("Settings")).unwrap() .merge(Environment::with_prefix("APP")).unwrap() .try_into(); ``` ## 0.6.0 – 2017-06-22 - Implement `Source` for `Vec` and `Vec>` ```rust Config::new() .merge(vec![ File::with_name("config/default"), File::with_name(&format!("config/{}", run_mode)), ]) ``` - Implement `From<&Path>` and `From` for `File` - Remove `namespace` option for File - Add builder pattern to condense configuration ```rust Config::new() .merge(File::with_name("Settings")) .merge(Environment::with_prefix("APP")) .unwrap() ``` - Parsing errors even for non required files – [@Anthony25] ( [#33] ) [@Anthony25]: https://github.com/Anthony25 [#33]: https://github.com/mehcode/config-rs/pull/33 ## 0.5.1 – 2017-06-16 - Added config category to Cargo.toml ## 0.5.0 – 2017-06-16 - `config.get` has been changed to take a type parameter and to deserialize into that type using serde. Old behavior (get a value variant) can be used by passing `config::Value` as the type parameter: `my_config.get::("..")`. Some great help here from [@impowski] in [#25]. - Propagate parse and type errors through the deep merge (remembering filename, line, etc.) - Remove directory traversal on `File`. This is likely temporary. I do _want_ this behavior but I can see how it should be optional. See [#35] - Add `File::with_name` to get automatic file format detection instead of manual `FileFormat::*` – [@JordiPolo] - Case normalization [#26] - Remove many possible panics [#8] - `my_config.refresh()` will do a full re-read from the source so live configuration is possible with some work to watch the file [#8]: https://github.com/mehcode/config-rs/issues/8 [#35]: https://github.com/mehcode/config-rs/pull/35 [#26]: https://github.com/mehcode/config-rs/pull/26 [#25]: https://github.com/mehcode/config-rs/pull/25 [@impowski]: https://github.com/impowski [@JordiPolo]: https://github.com/JordiPolo ## 0.4.0 - 2017-02-12 - Remove global ( `config::get` ) API — It's now required to create a local configuration instance with `config::Config::new()` first. If you'd like to have a global configuration instance, use `lazy_static!` as follows: ```rust use std::sync::RwLock; use config::Config; lazy_static! { static ref CONFIG: RwLock = Default::default(); } ``` ## 0.3.0 - 2017-02-08 - YAML from [@tmccombs](https://github.com/tmccombs) - Nested field retrieval - Deep merging of sources (was shallow) - `config::File::from_str` to parse and merge a file from a string - Support for retrieval of maps and slices — `config::get_table` and `config::get_array` ## 0.2.0 - 2017-01-29 Initial release. config-0.11.0/Cargo.toml0000644000000033030000000000000103540ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "config" version = "0.11.0" authors = ["Ryan Leckey "] description = "Layered configuration system for Rust applications." homepage = "https://github.com/mehcode/config-rs" readme = "README.md" keywords = ["config", "configuration", "settings", "env", "environment"] categories = ["config"] license = "MIT/Apache-2.0" repository = "https://github.com/mehcode/config-rs" [dependencies.lazy_static] version = "1.0" [dependencies.nom] version = "5.0.0" [dependencies.rust-ini] version = "0.13" optional = true [dependencies.serde] version = "1.0.8" [dependencies.serde-hjson] version = "0.9" optional = true default-features = false [dependencies.serde_json] version = "1.0.2" optional = true [dependencies.toml] version = "0.5" optional = true [dependencies.yaml-rust] version = "0.4" optional = true [dev-dependencies.chrono] version = "0.4" features = ["serde"] [dev-dependencies.float-cmp] version = "0.6" [dev-dependencies.serde_derive] version = "1.0.8" [features] default = ["toml", "json", "yaml", "hjson", "ini"] hjson = ["serde-hjson"] ini = ["rust-ini"] json = ["serde_json"] yaml = ["yaml-rust"] [badges.maintenance] status = "actively-developed" config-0.11.0/Cargo.toml.orig000064400000000000000000000020530000000000000140140ustar 00000000000000[package] name = "config" version = "0.11.0" description = "Layered configuration system for Rust applications." homepage = "https://github.com/mehcode/config-rs" repository = "https://github.com/mehcode/config-rs" readme = "README.md" keywords = ["config", "configuration", "settings", "env", "environment"] authors = ["Ryan Leckey "] categories = ["config"] license = "MIT/Apache-2.0" [badges] maintenance = { status = "actively-developed" } [features] default = ["toml", "json", "yaml", "hjson", "ini"] json = ["serde_json"] yaml = ["yaml-rust"] hjson = ["serde-hjson"] ini = ["rust-ini"] [dependencies] lazy_static = "1.0" serde = "1.0.8" nom = "5.0.0" toml = { version = "0.5", optional = true } serde_json = { version = "1.0.2", optional = true } yaml-rust = { version = "0.4", optional = true } serde-hjson = { version = "0.9", default-features = false, optional = true } rust-ini = { version = "0.13", optional = true } [dev-dependencies] serde_derive = "1.0.8" float-cmp = "0.6" chrono = { version = "0.4", features = ["serde"] } config-0.11.0/LICENSE-APACHE000064400000000000000000000251160000000000000130560ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2017 Ryan Leckey Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.config-0.11.0/LICENSE-MIT000064400000000000000000000020360000000000000125620ustar 00000000000000Copyright (c) 2017 Ryan Leckey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.config-0.11.0/README.md000064400000000000000000000034050000000000000124060ustar 00000000000000# config-rs ![Rust](https://img.shields.io/badge/rust-stable-brightgreen.svg) [![Build Status](https://travis-ci.org/mehcode/config-rs.svg?branch=master)](https://travis-ci.org/mehcode/config-rs) [![Crates.io](https://img.shields.io/crates/d/config.svg)](https://crates.io/crates/config) [![Docs.rs](https://docs.rs/config/badge.svg)](https://docs.rs/config) > Layered configuration system for Rust applications (with strong support for [12-factor] applications). [12-factor]: https://12factor.net/config - Set defaults - Set explicit values (to programmatically override) - Read from [JSON], [TOML], [YAML], [HJSON], [INI] files - Read from environment - Loosely typed — Configuration values may be read in any supported type, as long as there exists a reasonable conversion - Access nested fields using a formatted path — Uses a subset of JSONPath; currently supports the child ( `redis.port` ) and subscript operators ( `databases[0].name` ) [JSON]: https://github.com/serde-rs/json [TOML]: https://github.com/toml-lang/toml [YAML]: https://github.com/chyh1990/yaml-rust [HJSON]: https://github.com/hjson/hjson-rust [INI]: https://github.com/zonyitoo/rust-ini ## Usage ```toml [dependencies] config = "0.11" ``` - `ini` - Adds support for reading INI files - `json` - Adds support for reading JSON files - `hjson` - Adds support for reading HJSON files - `yaml` - Adds support for reading YAML files - `toml` - Adds support for reading TOML files See the [documentation](https://docs.rs/config) or [examples](https://github.com/mehcode/config-rs/tree/master/examples) for more usage information. ## License config-rs is primarily distributed under the terms of both the MIT license and the Apache License (Version 2.0). See LICENSE-APACHE and LICENSE-MIT for details. config-0.11.0/src/config.rs000064400000000000000000000156110000000000000135330ustar 00000000000000use serde::de::{Deserialize, Deserializer}; use serde::ser::{Serialize, Serializer}; use std::collections::HashMap; use std::fmt::Debug; use std::ops::Deref; use std::str::FromStr; use error::*; use ser::ConfigSerializer; use source::Source; use path; use value::{Table, Value, ValueKind}; #[derive(Clone, Debug)] enum ConfigKind { // A mutable configuration. This is the default. Mutable { defaults: HashMap, overrides: HashMap, sources: Vec>, }, // A frozen configuration. // Configuration can no longer be mutated. Frozen, } impl Default for ConfigKind { fn default() -> Self { ConfigKind::Mutable { defaults: HashMap::new(), overrides: HashMap::new(), sources: Vec::new(), } } } /// A prioritized configuration repository. It maintains a set of /// configuration sources, fetches values to populate those, and provides /// them according to the source's priority. #[derive(Default, Clone, Debug)] pub struct Config { kind: ConfigKind, /// Root of the cached configuration. pub cache: Value, } impl Config { pub fn new() -> Self { Self { kind: ConfigKind::default(), // Config root should be instantiated as an empty table // to avoid deserialization errors. cache: Value::new(None, Table::new()), } } /// Merge in a configuration property source. pub fn merge(&mut self, source: T) -> Result<&mut Config> where T: 'static, T: Source + Send + Sync, { match self.kind { ConfigKind::Mutable { ref mut sources, .. } => { sources.push(Box::new(source)); } ConfigKind::Frozen => { return Err(ConfigError::Frozen); } } self.refresh() } /// Merge in a configuration property source. pub fn with_merged(mut self, source: T) -> Result where T: 'static, T: Source + Send + Sync, { match self.kind { ConfigKind::Mutable { ref mut sources, .. } => { sources.push(Box::new(source)); } ConfigKind::Frozen => { return Err(ConfigError::Frozen); } } self.refresh()?; Ok(self) } /// Refresh the configuration cache with fresh /// data from added sources. /// /// Configuration is automatically refreshed after a mutation /// operation (`set`, `merge`, `set_default`, etc.). pub fn refresh(&mut self) -> Result<&mut Config> { self.cache = match self.kind { // TODO: We need to actually merge in all the stuff ConfigKind::Mutable { ref overrides, ref sources, ref defaults, } => { let mut cache: Value = HashMap::::new().into(); // Add defaults for (key, val) in defaults { key.set(&mut cache, val.clone()); } // Add sources sources.collect_to(&mut cache)?; // Add overrides for (key, val) in overrides { key.set(&mut cache, val.clone()); } cache } ConfigKind::Frozen => { return Err(ConfigError::Frozen); } }; Ok(self) } pub fn set_default(&mut self, key: &str, value: T) -> Result<&mut Config> where T: Into, { match self.kind { ConfigKind::Mutable { ref mut defaults, .. } => { defaults.insert(key.parse()?, value.into()); } ConfigKind::Frozen => return Err(ConfigError::Frozen), }; self.refresh() } pub fn set(&mut self, key: &str, value: T) -> Result<&mut Config> where T: Into, { match self.kind { ConfigKind::Mutable { ref mut overrides, .. } => { overrides.insert(key.parse()?, value.into()); } ConfigKind::Frozen => return Err(ConfigError::Frozen), }; self.refresh() } pub fn set_once(&mut self, key: &str, value: Value) -> Result<()> { let expr: path::Expression = key.parse()?; // Traverse the cache using the path to (possibly) retrieve a value if let Some(ref mut val) = expr.get_mut(&mut self.cache) { **val = value; } else { expr.set(&mut self.cache, value); } Ok(()) } pub fn get<'de, T: Deserialize<'de>>(&self, key: &str) -> Result { // Parse the key into a path expression let expr: path::Expression = key.parse()?; // Traverse the cache using the path to (possibly) retrieve a value let value = expr.get(&self.cache).cloned(); match value { Some(value) => { // Deserialize the received value into the requested type T::deserialize(value).map_err(|e| e.extend_with_key(key)) } None => Err(ConfigError::NotFound(key.into())), } } pub fn get_str(&self, key: &str) -> Result { self.get(key).and_then(Value::into_str) } pub fn get_int(&self, key: &str) -> Result { self.get(key).and_then(Value::into_int) } pub fn get_float(&self, key: &str) -> Result { self.get(key).and_then(Value::into_float) } pub fn get_bool(&self, key: &str) -> Result { self.get(key).and_then(Value::into_bool) } pub fn get_table(&self, key: &str) -> Result> { self.get(key).and_then(Value::into_table) } pub fn get_array(&self, key: &str) -> Result> { self.get(key).and_then(Value::into_array) } /// Attempt to deserialize the entire configuration into the requested type. pub fn try_into<'de, T: Deserialize<'de>>(self) -> Result { T::deserialize(self) } /// Attempt to serialize the entire configuration from the given type. pub fn try_from(from: &T) -> Result { let mut serializer = ConfigSerializer::default(); from.serialize(&mut serializer)?; Ok(serializer.output) } #[deprecated(since = "0.7.0", note = "please use 'try_into' instead")] pub fn deserialize<'de, T: Deserialize<'de>>(self) -> Result { self.try_into() } } impl Source for Config { fn clone_into_box(&self) -> Box { Box::new((*self).clone()) } fn collect(&self) -> Result> { self.cache.clone().into_table() } } config-0.11.0/src/de.rs000064400000000000000000000335420000000000000126610ustar 00000000000000use config::Config; use error::*; use serde::de; use std::collections::{HashMap, VecDeque}; use std::iter::Enumerate; use value::{Table, Value, ValueKind}; impl<'de> de::Deserializer<'de> for Value { type Error = ConfigError; #[inline] fn deserialize_any(self, visitor: V) -> Result where V: de::Visitor<'de>, { // Deserialize based on the underlying type match self.kind { ValueKind::Nil => visitor.visit_unit(), ValueKind::Integer(i) => visitor.visit_i64(i), ValueKind::Boolean(b) => visitor.visit_bool(b), ValueKind::Float(f) => visitor.visit_f64(f), ValueKind::String(s) => visitor.visit_string(s), ValueKind::Array(values) => visitor.visit_seq(SeqAccess::new(values)), ValueKind::Table(map) => visitor.visit_map(MapAccess::new(map)), } } #[inline] fn deserialize_bool>(self, visitor: V) -> Result { visitor.visit_bool(self.into_bool()?) } #[inline] fn deserialize_i8>(self, visitor: V) -> Result { // FIXME: This should *fail* if the value does not fit in the requets integer type visitor.visit_i8(self.into_int()? as i8) } #[inline] fn deserialize_i16>(self, visitor: V) -> Result { // FIXME: This should *fail* if the value does not fit in the requets integer type visitor.visit_i16(self.into_int()? as i16) } #[inline] fn deserialize_i32>(self, visitor: V) -> Result { // FIXME: This should *fail* if the value does not fit in the requets integer type visitor.visit_i32(self.into_int()? as i32) } #[inline] fn deserialize_i64>(self, visitor: V) -> Result { visitor.visit_i64(self.into_int()?) } #[inline] fn deserialize_u8>(self, visitor: V) -> Result { // FIXME: This should *fail* if the value does not fit in the requets integer type visitor.visit_u8(self.into_int()? as u8) } #[inline] fn deserialize_u16>(self, visitor: V) -> Result { // FIXME: This should *fail* if the value does not fit in the requets integer type visitor.visit_u16(self.into_int()? as u16) } #[inline] fn deserialize_u32>(self, visitor: V) -> Result { // FIXME: This should *fail* if the value does not fit in the requets integer type visitor.visit_u32(self.into_int()? as u32) } #[inline] fn deserialize_u64>(self, visitor: V) -> Result { // FIXME: This should *fail* if the value does not fit in the requets integer type visitor.visit_u64(self.into_int()? as u64) } #[inline] fn deserialize_f32>(self, visitor: V) -> Result { visitor.visit_f32(self.into_float()? as f32) } #[inline] fn deserialize_f64>(self, visitor: V) -> Result { visitor.visit_f64(self.into_float()?) } #[inline] fn deserialize_str>(self, visitor: V) -> Result { visitor.visit_string(self.into_str()?) } #[inline] fn deserialize_string>(self, visitor: V) -> Result { visitor.visit_string(self.into_str()?) } #[inline] fn deserialize_option(self, visitor: V) -> Result where V: de::Visitor<'de>, { // Match an explicit nil as None and everything else as Some match self.kind { ValueKind::Nil => visitor.visit_none(), _ => visitor.visit_some(self), } } fn deserialize_newtype_struct(self, _name: &'static str, visitor: V) -> Result where V: de::Visitor<'de>, { visitor.visit_newtype_struct(self) } fn deserialize_enum( self, name: &'static str, variants: &'static [&'static str], visitor: V, ) -> Result where V: de::Visitor<'de>, { visitor.visit_enum(EnumAccess { value: self, name, variants, }) } forward_to_deserialize_any! { char seq bytes byte_buf map struct unit identifier ignored_any unit_struct tuple_struct tuple } } struct StrDeserializer<'a>(&'a str); impl<'a> StrDeserializer<'a> { fn new(key: &'a str) -> Self { StrDeserializer(key) } } impl<'de, 'a> de::Deserializer<'de> for StrDeserializer<'a> { type Error = ConfigError; #[inline] fn deserialize_any>(self, visitor: V) -> Result { visitor.visit_str(self.0) } forward_to_deserialize_any! { bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string seq bytes byte_buf map struct unit enum newtype_struct identifier ignored_any unit_struct tuple_struct tuple option } } struct SeqAccess { elements: Enumerate<::std::vec::IntoIter>, } impl SeqAccess { fn new(elements: Vec) -> Self { SeqAccess { elements: elements.into_iter().enumerate(), } } } impl<'de> de::SeqAccess<'de> for SeqAccess { type Error = ConfigError; fn next_element_seed(&mut self, seed: T) -> Result> where T: de::DeserializeSeed<'de>, { match self.elements.next() { Some((idx, value)) => seed .deserialize(value) .map(Some) .map_err(|e| e.prepend_index(idx)), None => Ok(None), } } fn size_hint(&self) -> Option { match self.elements.size_hint() { (lower, Some(upper)) if lower == upper => Some(upper), _ => None, } } } struct MapAccess { elements: VecDeque<(String, Value)>, } impl MapAccess { fn new(table: HashMap) -> Self { MapAccess { elements: table.into_iter().collect(), } } } impl<'de> de::MapAccess<'de> for MapAccess { type Error = ConfigError; fn next_key_seed(&mut self, seed: K) -> Result> where K: de::DeserializeSeed<'de>, { if let Some(&(ref key_s, _)) = self.elements.front() { let key_de = Value::new(None, key_s as &str); let key = de::DeserializeSeed::deserialize(seed, key_de)?; Ok(Some(key)) } else { Ok(None) } } fn next_value_seed(&mut self, seed: V) -> Result where V: de::DeserializeSeed<'de>, { let (key, value) = self.elements.pop_front().unwrap(); de::DeserializeSeed::deserialize(seed, value).map_err(|e| e.prepend_key(key)) } } struct EnumAccess { value: Value, name: &'static str, variants: &'static [&'static str], } impl EnumAccess { fn variant_deserializer(&self, name: &str) -> Result { self.variants .iter() .find(|&&s| s == name) .map(|&s| StrDeserializer(s)) .ok_or_else(|| self.no_constructor_error(name)) } fn table_deserializer(&self, table: &Table) -> Result { if table.len() == 1 { self.variant_deserializer(table.iter().next().unwrap().0) } else { Err(self.structural_error()) } } fn no_constructor_error(&self, supposed_variant: &str) -> ConfigError { ConfigError::Message(format!( "enum {} does not have variant constructor {}", self.name, supposed_variant )) } fn structural_error(&self) -> ConfigError { ConfigError::Message(format!( "value of enum {} should be represented by either string or table with exactly one key", self.name )) } } impl<'de> de::EnumAccess<'de> for EnumAccess { type Error = ConfigError; type Variant = Self; fn variant_seed(self, seed: V) -> Result<(V::Value, Self::Variant)> where V: de::DeserializeSeed<'de>, { let value = { let deserializer = match self.value.kind { ValueKind::String(ref s) => self.variant_deserializer(s), ValueKind::Table(ref t) => self.table_deserializer(&t), _ => Err(self.structural_error()), }?; seed.deserialize(deserializer)? }; Ok((value, self)) } } impl<'de> de::VariantAccess<'de> for EnumAccess { type Error = ConfigError; fn unit_variant(self) -> Result<()> { Ok(()) } fn newtype_variant_seed(self, seed: T) -> Result where T: de::DeserializeSeed<'de>, { match self.value.kind { ValueKind::Table(t) => seed.deserialize(t.into_iter().next().unwrap().1), _ => unreachable!(), } } fn tuple_variant(self, _len: usize, visitor: V) -> Result where V: de::Visitor<'de>, { match self.value.kind { ValueKind::Table(t) => { de::Deserializer::deserialize_seq(t.into_iter().next().unwrap().1, visitor) } _ => unreachable!(), } } fn struct_variant(self, _fields: &'static [&'static str], visitor: V) -> Result where V: de::Visitor<'de>, { match self.value.kind { ValueKind::Table(t) => { de::Deserializer::deserialize_map(t.into_iter().next().unwrap().1, visitor) } _ => unreachable!(), } } } impl<'de> de::Deserializer<'de> for Config { type Error = ConfigError; #[inline] fn deserialize_any(self, visitor: V) -> Result where V: de::Visitor<'de>, { // Deserialize based on the underlying type match self.cache.kind { ValueKind::Nil => visitor.visit_unit(), ValueKind::Integer(i) => visitor.visit_i64(i), ValueKind::Boolean(b) => visitor.visit_bool(b), ValueKind::Float(f) => visitor.visit_f64(f), ValueKind::String(s) => visitor.visit_string(s), ValueKind::Array(values) => visitor.visit_seq(SeqAccess::new(values)), ValueKind::Table(map) => visitor.visit_map(MapAccess::new(map)), } } #[inline] fn deserialize_bool>(self, visitor: V) -> Result { visitor.visit_bool(self.cache.into_bool()?) } #[inline] fn deserialize_i8>(self, visitor: V) -> Result { // FIXME: This should *fail* if the value does not fit in the requets integer type visitor.visit_i8(self.cache.into_int()? as i8) } #[inline] fn deserialize_i16>(self, visitor: V) -> Result { // FIXME: This should *fail* if the value does not fit in the requets integer type visitor.visit_i16(self.cache.into_int()? as i16) } #[inline] fn deserialize_i32>(self, visitor: V) -> Result { // FIXME: This should *fail* if the value does not fit in the requets integer type visitor.visit_i32(self.cache.into_int()? as i32) } #[inline] fn deserialize_i64>(self, visitor: V) -> Result { visitor.visit_i64(self.cache.into_int()?) } #[inline] fn deserialize_u8>(self, visitor: V) -> Result { // FIXME: This should *fail* if the value does not fit in the requets integer type visitor.visit_u8(self.cache.into_int()? as u8) } #[inline] fn deserialize_u16>(self, visitor: V) -> Result { // FIXME: This should *fail* if the value does not fit in the requets integer type visitor.visit_u16(self.cache.into_int()? as u16) } #[inline] fn deserialize_u32>(self, visitor: V) -> Result { // FIXME: This should *fail* if the value does not fit in the requets integer type visitor.visit_u32(self.cache.into_int()? as u32) } #[inline] fn deserialize_u64>(self, visitor: V) -> Result { // FIXME: This should *fail* if the value does not fit in the requets integer type visitor.visit_u64(self.cache.into_int()? as u64) } #[inline] fn deserialize_f32>(self, visitor: V) -> Result { visitor.visit_f32(self.cache.into_float()? as f32) } #[inline] fn deserialize_f64>(self, visitor: V) -> Result { visitor.visit_f64(self.cache.into_float()?) } #[inline] fn deserialize_str>(self, visitor: V) -> Result { visitor.visit_string(self.cache.into_str()?) } #[inline] fn deserialize_string>(self, visitor: V) -> Result { visitor.visit_string(self.cache.into_str()?) } #[inline] fn deserialize_option(self, visitor: V) -> Result where V: de::Visitor<'de>, { // Match an explicit nil as None and everything else as Some match self.cache.kind { ValueKind::Nil => visitor.visit_none(), _ => visitor.visit_some(self), } } fn deserialize_enum( self, name: &'static str, variants: &'static [&'static str], visitor: V, ) -> Result where V: de::Visitor<'de>, { visitor.visit_enum(EnumAccess { value: self.cache, name, variants, }) } forward_to_deserialize_any! { char seq bytes byte_buf map struct unit newtype_struct identifier ignored_any unit_struct tuple_struct tuple } } config-0.11.0/src/env.rs000064400000000000000000000063520000000000000130600ustar 00000000000000use error::*; use source::Source; use std::collections::HashMap; use std::env; use value::{Value, ValueKind}; #[derive(Clone, Debug)] pub struct Environment { /// Optional prefix that will limit access to the environment to only keys that /// begin with the defined prefix. /// /// A prefix with a separator of `_` is tested to be present on each key before its considered /// to be part of the source environment. /// /// For example, the key `CONFIG_DEBUG` would become `DEBUG` with a prefix of `config`. prefix: Option, /// Optional character sequence that separates each key segment in an environment key pattern. /// Consider a nested configuration such as `redis.password`, a separator of `_` would allow /// an environment key of `REDIS_PASSWORD` to match. separator: Option, /// Ignore empty env values (treat as unset). ignore_empty: bool, } impl Environment { pub fn new() -> Self { Environment::default() } pub fn with_prefix(s: &str) -> Self { Environment { prefix: Some(s.into()), ..Environment::default() } } pub fn prefix(mut self, s: &str) -> Self { self.prefix = Some(s.into()); self } pub fn separator(mut self, s: &str) -> Self { self.separator = Some(s.into()); self } pub fn ignore_empty(mut self, ignore: bool) -> Self { self.ignore_empty = ignore; self } } impl Default for Environment { fn default() -> Environment { Environment { prefix: None, separator: None, ignore_empty: false, } } } impl Source for Environment { fn clone_into_box(&self) -> Box { Box::new((*self).clone()) } fn collect(&self) -> Result> { let mut m = HashMap::new(); let uri: String = "the environment".into(); let separator = match self.separator { Some(ref separator) => separator, _ => "", }; // Define a prefix pattern to test and exclude from keys let prefix_pattern = self.prefix.as_ref().map(|prefix| prefix.clone() + "_"); for (key, value) in env::vars() { // Treat empty environment variables as unset if self.ignore_empty && value.is_empty() { continue; } let mut key = key.to_string(); // Check for prefix if let Some(ref prefix_pattern) = prefix_pattern { if key .to_lowercase() .starts_with(&prefix_pattern.to_lowercase()) { // Remove this prefix from the key key = key[prefix_pattern.len()..].to_string(); } else { // Skip this key continue; } } // If separator is given replace with `.` if !separator.is_empty() { key = key.replace(separator, "."); } m.insert( key.to_lowercase(), Value::new(Some(&uri), ValueKind::String(value)), ); } Ok(m) } } config-0.11.0/src/error.rs000064400000000000000000000141230000000000000134140ustar 00000000000000use nom; use serde::de; use serde::ser; use std::borrow::Cow; use std::error::Error; use std::fmt; use std::result; #[derive(Debug)] pub enum Unexpected { Bool(bool), Integer(i64), Float(f64), Str(String), Unit, Seq, Map, } impl fmt::Display for Unexpected { fn fmt(&self, f: &mut fmt::Formatter) -> result::Result<(), fmt::Error> { match *self { Unexpected::Bool(b) => write!(f, "boolean `{}`", b), Unexpected::Integer(i) => write!(f, "integer `{}`", i), Unexpected::Float(v) => write!(f, "floating point `{}`", v), Unexpected::Str(ref s) => write!(f, "string {:?}", s), Unexpected::Unit => write!(f, "unit value"), Unexpected::Seq => write!(f, "sequence"), Unexpected::Map => write!(f, "map"), } } } /// Represents all possible errors that can occur when working with /// configuration. pub enum ConfigError { /// Configuration is frozen and no further mutations can be made. Frozen, /// Configuration property was not found NotFound(String), /// Configuration path could not be parsed. PathParse(nom::error::ErrorKind), /// Configuration could not be parsed from file. FileParse { /// The URI used to access the file (if not loaded from a string). /// Example: `/path/to/config.json` uri: Option, /// The captured error from attempting to parse the file in its desired format. /// This is the actual error object from the library used for the parsing. cause: Box, }, /// Value could not be converted into the requested type. Type { /// The URI that references the source that the value came from. /// Example: `/path/to/config.json` or `Environment` or `etcd://localhost` // TODO: Why is this called Origin but FileParse has a uri field? origin: Option, /// What we found when parsing the value unexpected: Unexpected, /// What was expected when parsing the value expected: &'static str, /// The key in the configuration hash of this value (if available where the /// error is generated). key: Option, }, /// Custom message Message(String), /// Unadorned error from a foreign origin. Foreign(Box), } impl ConfigError { // FIXME: pub(crate) #[doc(hidden)] pub fn invalid_type( origin: Option, unexpected: Unexpected, expected: &'static str, ) -> Self { ConfigError::Type { origin, unexpected, expected, key: None, } } // FIXME: pub(crate) #[doc(hidden)] pub fn extend_with_key(self, key: &str) -> Self { match self { ConfigError::Type { origin, unexpected, expected, .. } => ConfigError::Type { origin, unexpected, expected, key: Some(key.into()), }, _ => self, } } fn prepend(self, segment: String, add_dot: bool) -> Self { let concat = |key: Option| { let key = key.unwrap_or_else(String::new); let dot = if add_dot && key.as_bytes().get(0).unwrap_or(&b'[') != &b'[' { "." } else { "" }; format!("{}{}{}", segment, dot, key) }; match self { ConfigError::Type { origin, unexpected, expected, key, } => ConfigError::Type { origin, unexpected, expected, key: Some(concat(key)), }, ConfigError::NotFound(key) => ConfigError::NotFound(concat(Some(key))), _ => self, } } pub(crate) fn prepend_key(self, key: String) -> Self { self.prepend(key, true) } pub(crate) fn prepend_index(self, idx: usize) -> Self { self.prepend(format!("[{}]", idx), false) } } /// Alias for a `Result` with the error type set to `ConfigError`. pub type Result = result::Result; // Forward Debug to Display for readable panic! messages impl fmt::Debug for ConfigError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", *self) } } impl fmt::Display for ConfigError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ConfigError::Frozen => write!(f, "configuration is frozen"), ConfigError::PathParse(ref kind) => write!(f, "{}", kind.description()), ConfigError::Message(ref s) => write!(f, "{}", s), ConfigError::Foreign(ref cause) => write!(f, "{}", cause), ConfigError::NotFound(ref key) => { write!(f, "configuration property {:?} not found", key) } ConfigError::Type { ref origin, ref unexpected, expected, ref key, } => { write!(f, "invalid type: {}, expected {}", unexpected, expected)?; if let Some(ref key) = *key { write!(f, " for key `{}`", key)?; } if let Some(ref origin) = *origin { write!(f, " in {}", origin)?; } Ok(()) } ConfigError::FileParse { ref cause, ref uri } => { write!(f, "{}", cause)?; if let Some(ref uri) = *uri { write!(f, " in {}", uri)?; } Ok(()) } } } } impl Error for ConfigError {} impl de::Error for ConfigError { fn custom(msg: T) -> Self { ConfigError::Message(msg.to_string()) } } impl ser::Error for ConfigError { fn custom(msg: T) -> Self { ConfigError::Message(msg.to_string()) } } config-0.11.0/src/file/format/hjson.rs000064400000000000000000000032550000000000000156170ustar 00000000000000use serde_hjson; use source::Source; use std::collections::HashMap; use std::error::Error; use value::{Value, ValueKind}; pub fn parse( uri: Option<&String>, text: &str, ) -> Result, Box> { // Parse a JSON object value from the text // TODO: Have a proper error fire if the root of a file is ever not a Table let value = from_hjson_value(uri, &serde_hjson::from_str(text)?); match value.kind { ValueKind::Table(map) => Ok(map), _ => Ok(HashMap::new()), } } fn from_hjson_value(uri: Option<&String>, value: &serde_hjson::Value) -> Value { match *value { serde_hjson::Value::String(ref value) => Value::new(uri, ValueKind::String(value.clone())), serde_hjson::Value::I64(value) => Value::new(uri, ValueKind::Integer(value)), serde_hjson::Value::U64(value) => Value::new(uri, ValueKind::Integer(value as i64)), serde_hjson::Value::F64(value) => Value::new(uri, ValueKind::Float(value)), serde_hjson::Value::Bool(value) => Value::new(uri, ValueKind::Boolean(value)), serde_hjson::Value::Object(ref table) => { let mut m = HashMap::new(); for (key, value) in table { m.insert(key.clone(), from_hjson_value(uri, value)); } Value::new(uri, ValueKind::Table(m)) } serde_hjson::Value::Array(ref array) => { let mut l = Vec::new(); for value in array { l.push(from_hjson_value(uri, value)); } Value::new(uri, ValueKind::Array(l)) } serde_hjson::Value::Null => Value::new(uri, ValueKind::Nil), } } config-0.11.0/src/file/format/ini.rs000064400000000000000000000017160000000000000152550ustar 00000000000000use ini::Ini; use source::Source; use std::collections::HashMap; use std::error::Error; use value::{Value, ValueKind}; pub fn parse( uri: Option<&String>, text: &str, ) -> Result, Box> { let mut map: HashMap = HashMap::new(); let i = Ini::load_from_str(text)?; for (sec, prop) in i.iter() { match *sec { Some(ref sec) => { let mut sec_map: HashMap = HashMap::new(); for (k, v) in prop.iter() { sec_map.insert(k.clone(), Value::new(uri, ValueKind::String(v.clone()))); } map.insert(sec.clone(), Value::new(uri, ValueKind::Table(sec_map))); } None => { for (k, v) in prop.iter() { map.insert(k.clone(), Value::new(uri, ValueKind::String(v.clone()))); } } } } Ok(map) } config-0.11.0/src/file/format/json.rs000064400000000000000000000033660000000000000154520ustar 00000000000000use serde_json; use source::Source; use std::collections::HashMap; use std::error::Error; use value::{Value, ValueKind}; pub fn parse( uri: Option<&String>, text: &str, ) -> Result, Box> { // Parse a JSON object value from the text // TODO: Have a proper error fire if the root of a file is ever not a Table let value = from_json_value(uri, &serde_json::from_str(text)?); match value.kind { ValueKind::Table(map) => Ok(map), _ => Ok(HashMap::new()), } } fn from_json_value(uri: Option<&String>, value: &serde_json::Value) -> Value { match *value { serde_json::Value::String(ref value) => Value::new(uri, ValueKind::String(value.clone())), serde_json::Value::Number(ref value) => { if let Some(value) = value.as_i64() { Value::new(uri, ValueKind::Integer(value)) } else if let Some(value) = value.as_f64() { Value::new(uri, ValueKind::Float(value)) } else { unreachable!(); } } serde_json::Value::Bool(value) => Value::new(uri, ValueKind::Boolean(value)), serde_json::Value::Object(ref table) => { let mut m = HashMap::new(); for (key, value) in table { m.insert(key.clone(), from_json_value(uri, value)); } Value::new(uri, ValueKind::Table(m)) } serde_json::Value::Array(ref array) => { let mut l = Vec::new(); for value in array { l.push(from_json_value(uri, value)); } Value::new(uri, ValueKind::Array(l)) } serde_json::Value::Null => Value::new(uri, ValueKind::Nil), } } config-0.11.0/src/file/format/mod.rs000064400000000000000000000051730000000000000152560ustar 00000000000000// If no features are used, there is an "unused mut" warning in `ALL_EXTENSIONS` // BUG: ? For some reason this doesn't do anything if I try and function scope this #![allow(unused_mut)] use source::Source; use std::collections::HashMap; use std::error::Error; use value::Value; #[cfg(feature = "toml")] mod toml; #[cfg(feature = "json")] mod json; #[cfg(feature = "yaml")] mod yaml; #[cfg(feature = "hjson")] mod hjson; #[cfg(feature = "ini")] mod ini; #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] pub enum FileFormat { /// TOML (parsed with toml) #[cfg(feature = "toml")] Toml, /// JSON (parsed with serde_json) #[cfg(feature = "json")] Json, /// YAML (parsed with yaml_rust) #[cfg(feature = "yaml")] Yaml, /// HJSON (parsed with serde_hjson) #[cfg(feature = "hjson")] Hjson, /// INI (parsed with rust_ini) #[cfg(feature = "ini")] Ini, } lazy_static! { #[doc(hidden)] // #[allow(unused_mut)] ? pub static ref ALL_EXTENSIONS: HashMap> = { let mut formats: HashMap> = HashMap::new(); #[cfg(feature = "toml")] formats.insert(FileFormat::Toml, vec!["toml"]); #[cfg(feature = "json")] formats.insert(FileFormat::Json, vec!["json"]); #[cfg(feature = "yaml")] formats.insert(FileFormat::Yaml, vec!["yaml", "yml"]); #[cfg(feature = "hjson")] formats.insert(FileFormat::Hjson, vec!["hjson"]); #[cfg(feature = "ini")] formats.insert(FileFormat::Ini, vec!["ini"]); formats }; } impl FileFormat { // TODO: pub(crate) #[doc(hidden)] pub fn extensions(self) -> &'static Vec<&'static str> { // It should not be possible for this to fail // A FileFormat would need to be declared without being added to the // ALL_EXTENSIONS map. ALL_EXTENSIONS.get(&self).unwrap() } // TODO: pub(crate) #[doc(hidden)] #[allow(unused_variables)] pub fn parse( self, uri: Option<&String>, text: &str, ) -> Result, Box> { match self { #[cfg(feature = "toml")] FileFormat::Toml => toml::parse(uri, text), #[cfg(feature = "json")] FileFormat::Json => json::parse(uri, text), #[cfg(feature = "yaml")] FileFormat::Yaml => yaml::parse(uri, text), #[cfg(feature = "hjson")] FileFormat::Hjson => hjson::parse(uri, text), #[cfg(feature = "ini")] FileFormat::Ini => ini::parse(uri, text), } } } config-0.11.0/src/file/format/toml.rs000064400000000000000000000027030000000000000154460ustar 00000000000000use source::Source; use std::collections::{BTreeMap, HashMap}; use std::error::Error; use toml; use value::{Value, ValueKind}; pub fn parse( uri: Option<&String>, text: &str, ) -> Result, Box> { // Parse a TOML value from the provided text // TODO: Have a proper error fire if the root of a file is ever not a Table let value = from_toml_value(uri, &toml::from_str(text)?); match value.kind { ValueKind::Table(map) => Ok(map), _ => Ok(HashMap::new()), } } fn from_toml_value(uri: Option<&String>, value: &toml::Value) -> Value { match *value { toml::Value::String(ref value) => Value::new(uri, value.to_string()), toml::Value::Float(value) => Value::new(uri, value), toml::Value::Integer(value) => Value::new(uri, value), toml::Value::Boolean(value) => Value::new(uri, value), toml::Value::Table(ref table) => { let mut m = HashMap::new(); for (key, value) in table { m.insert(key.clone(), from_toml_value(uri, value)); } Value::new(uri, m) } toml::Value::Array(ref array) => { let mut l = Vec::new(); for value in array { l.push(from_toml_value(uri, value)); } Value::new(uri, l) } toml::Value::Datetime(ref datetime) => Value::new(uri, datetime.to_string()), } } config-0.11.0/src/file/format/yaml.rs000064400000000000000000000054200000000000000154340ustar 00000000000000use source::Source; use std::collections::HashMap; use std::error::Error; use std::fmt; use std::mem; use value::{Value, ValueKind}; use yaml_rust as yaml; pub fn parse( uri: Option<&String>, text: &str, ) -> Result, Box> { // Parse a YAML object from file let mut docs = yaml::YamlLoader::load_from_str(text)?; let root = match docs.len() { 0 => yaml::Yaml::Hash(yaml::yaml::Hash::new()), 1 => mem::replace(&mut docs[0], yaml::Yaml::Null), n => { return Err(Box::new(MultipleDocumentsError(n))); } }; // TODO: Have a proper error fire if the root of a file is ever not a Table let value = from_yaml_value(uri, &root); match value.kind { ValueKind::Table(map) => Ok(map), _ => Ok(HashMap::new()), } } fn from_yaml_value(uri: Option<&String>, value: &yaml::Yaml) -> Value { match *value { yaml::Yaml::String(ref value) => Value::new(uri, ValueKind::String(value.clone())), yaml::Yaml::Real(ref value) => { // TODO: Figure out in what cases this can panic? Value::new(uri, ValueKind::Float(value.parse::().unwrap())) } yaml::Yaml::Integer(value) => Value::new(uri, ValueKind::Integer(value)), yaml::Yaml::Boolean(value) => Value::new(uri, ValueKind::Boolean(value)), yaml::Yaml::Hash(ref table) => { let mut m = HashMap::new(); for (key, value) in table { if let Some(k) = key.as_str() { m.insert(k.to_owned(), from_yaml_value(uri, value)); } // TODO: should we do anything for non-string keys? } Value::new(uri, ValueKind::Table(m)) } yaml::Yaml::Array(ref array) => { let mut l = Vec::new(); for value in array { l.push(from_yaml_value(uri, value)); } Value::new(uri, ValueKind::Array(l)) } // 1. Yaml NULL // 2. BadValue – It shouldn't be possible to hit BadValue as this only happens when // using the index trait badly or on a type error but we send back nil. // 3. Alias – No idea what to do with this and there is a note in the lib that its // not fully supported yet anyway _ => Value::new(uri, ValueKind::Nil), } } #[derive(Debug, Copy, Clone)] struct MultipleDocumentsError(usize); impl fmt::Display for MultipleDocumentsError { fn fmt(&self, format: &mut fmt::Formatter) -> fmt::Result { write!(format, "Got {} YAML documents, expected 1", self.0) } } impl Error for MultipleDocumentsError { fn description(&self) -> &str { "More than one YAML document provided" } } config-0.11.0/src/file/mod.rs000064400000000000000000000057550000000000000137740ustar 00000000000000mod format; pub mod source; use error::*; use source::Source; use std::collections::HashMap; use std::path::{Path, PathBuf}; use value::Value; pub use self::format::FileFormat; use self::source::FileSource; pub use self::source::file::FileSourceFile; pub use self::source::string::FileSourceString; #[derive(Clone, Debug)] pub struct File where T: FileSource, { source: T, /// Format of file (which dictates what driver to use). format: Option, /// A required File will error if it cannot be found required: bool, } impl File { pub fn from_str(s: &str, format: FileFormat) -> Self { File { format: Some(format), required: true, source: s.into(), } } } impl File { pub fn new(name: &str, format: FileFormat) -> Self { File { format: Some(format), required: true, source: source::file::FileSourceFile::new(name.into()), } } /// Given the basename of a file, will attempt to locate a file by setting its /// extension to a registered format. pub fn with_name(name: &str) -> Self { File { format: None, required: true, source: source::file::FileSourceFile::new(name.into()), } } } impl<'a> From<&'a Path> for File { fn from(path: &'a Path) -> Self { File { format: None, required: true, source: source::file::FileSourceFile::new(path.to_path_buf()), } } } impl From for File { fn from(path: PathBuf) -> Self { File { format: None, required: true, source: source::file::FileSourceFile::new(path), } } } impl File { pub fn format(mut self, format: FileFormat) -> Self { self.format = Some(format); self } pub fn required(mut self, required: bool) -> Self { self.required = required; self } } impl Source for File where T: 'static, T: Sync + Send, { fn clone_into_box(&self) -> Box { Box::new((*self).clone()) } fn collect(&self) -> Result> { // Coerce the file contents to a string let (uri, contents, format) = match self .source .resolve(self.format) .map_err(|err| ConfigError::Foreign(err)) { Ok((uri, contents, format)) => (uri, contents, format), Err(error) => { if !self.required { return Ok(HashMap::new()); } return Err(error); } }; // Parse the string using the given format format .parse(uri.as_ref(), &contents) .map_err(|cause| ConfigError::FileParse { uri, cause }) } } config-0.11.0/src/file/source/file.rs000064400000000000000000000116540000000000000154270ustar 00000000000000use std::error::Error; use std::result; use std::str::FromStr; use file::format::ALL_EXTENSIONS; use std::env; use std::fs; use std::io::{self, Read}; use std::iter::Iterator; use std::path::{Path, PathBuf}; use super::{FileFormat, FileSource}; use source::Source; /// Describes a file sourced from a file #[derive(Clone, Debug)] pub struct FileSourceFile { /// Path of configuration file name: PathBuf, } impl FileSourceFile { pub fn new(name: PathBuf) -> FileSourceFile { FileSourceFile { name } } fn find_file( &self, format_hint: Option, ) -> Result<(PathBuf, FileFormat), Box> { // First check for an _exact_ match let mut filename = env::current_dir()?.as_path().join(self.name.clone()); if filename.is_file() { return match format_hint { Some(format) => Ok((filename, format)), None => { for (format, extensions) in ALL_EXTENSIONS.iter() { if extensions.contains( &filename .extension() .unwrap_or_default() .to_string_lossy() .as_ref(), ) { return Ok((filename, *format)); } } Err(Box::new(io::Error::new( io::ErrorKind::NotFound, format!( "configuration file \"{}\" is not of a registered file format", filename.to_string_lossy() ), ))) } }; } match format_hint { Some(format) => { for ext in format.extensions() { filename.set_extension(ext); if filename.is_file() { return Ok((filename, format)); } } } None => { for (format, extensions) in ALL_EXTENSIONS.iter() { for ext in format.extensions() { filename.set_extension(ext); if filename.is_file() { return Ok((filename, *format)); } } } } } Err(Box::new(io::Error::new( io::ErrorKind::NotFound, format!( "configuration file \"{}\" not found", self.name.to_string_lossy() ), ))) } } impl FileSource for FileSourceFile { fn resolve( &self, format_hint: Option, ) -> Result<(Option, String, FileFormat), Box> { // Find file let (filename, format) = self.find_file(format_hint)?; // Attempt to use a relative path for the URI let base = env::current_dir()?; let uri = match path_relative_from(&filename, &base) { Some(value) => value, None => filename.clone(), }; // Read contents from file let mut file = fs::File::open(filename)?; let mut text = String::new(); file.read_to_string(&mut text)?; Ok((Some(uri.to_string_lossy().into_owned()), text, format)) } } // TODO: This should probably be a crate // https://github.com/rust-lang/rust/blob/master/src/librustc_trans/back/rpath.rs#L128 fn path_relative_from(path: &Path, base: &Path) -> Option { use std::path::Component; if path.is_absolute() != base.is_absolute() { if path.is_absolute() { Some(PathBuf::from(path)) } else { None } } else { let mut ita = path.components(); let mut itb = base.components(); let mut comps: Vec = vec![]; loop { match (ita.next(), itb.next()) { (None, None) => break, (Some(a), None) => { comps.push(a); comps.extend(ita.by_ref()); break; } (None, _) => comps.push(Component::ParentDir), (Some(a), Some(b)) if comps.is_empty() && a == b => (), (Some(a), Some(b)) if b == Component::CurDir => comps.push(a), (Some(_), Some(b)) if b == Component::ParentDir => return None, (Some(a), Some(_)) => { comps.push(Component::ParentDir); for _ in itb { comps.push(Component::ParentDir); } comps.push(a); comps.extend(ita.by_ref()); break; } } } Some(comps.iter().map(|c| c.as_os_str()).collect()) } } config-0.11.0/src/file/source/mod.rs000064400000000000000000000005450000000000000152640ustar 00000000000000pub mod file; pub mod string; use std::error::Error; use std::fmt::Debug; use super::FileFormat; use source::Source; /// Describes where the file is sourced pub trait FileSource: Debug + Clone { fn resolve( &self, format_hint: Option, ) -> Result<(Option, String, FileFormat), Box>; } config-0.11.0/src/file/source/string.rs000064400000000000000000000012710000000000000160100ustar 00000000000000use std::error::Error; use std::result; use std::str::FromStr; use super::{FileFormat, FileSource}; use source::Source; /// Describes a file sourced from a string #[derive(Clone, Debug)] pub struct FileSourceString(String); impl<'a> From<&'a str> for FileSourceString { fn from(s: &'a str) -> Self { FileSourceString(s.into()) } } impl FileSource for FileSourceString { fn resolve( &self, format_hint: Option, ) -> Result<(Option, String, FileFormat), Box> { Ok(( None, self.0.clone(), format_hint.expect("from_str requires a set file format"), )) } } config-0.11.0/src/lib.rs000064400000000000000000000031470000000000000130350ustar 00000000000000//! Config organizes hierarchical or layered configurations for Rust applications. //! //! Config lets you set a set of default parameters and then extend them via merging in //! configuration from a variety of sources: //! //! - Environment variables //! - Another Config instance //! - Remote configuration: etcd, Consul //! - Files: JSON, YAML, TOML, HJSON //! - Manual, programmatic override (via a `.set` method on the Config instance) //! //! Additionally, Config supports: //! //! - Live watching and re-reading of configuration files //! - Deep access into the merged configuration via a path syntax //! - Deserialization via `serde` of the configuration or any subset defined via a path //! //! See the [examples](https://github.com/mehcode/config-rs/tree/master/examples) for //! general usage information. #![allow(dead_code)] #![allow(unused_imports)] #![allow(unused_variables)] #![allow(unknown_lints)] // #![warn(missing_docs)] #[macro_use] extern crate serde; #[cfg(test)] #[macro_use] extern crate serde_derive; #[macro_use] extern crate nom; #[macro_use] extern crate lazy_static; #[cfg(feature = "toml")] extern crate toml; #[cfg(feature = "json")] extern crate serde_json; #[cfg(feature = "yaml")] extern crate yaml_rust; #[cfg(feature = "hjson")] extern crate serde_hjson; #[cfg(feature = "ini")] extern crate ini; mod config; mod de; mod env; mod error; mod file; mod path; mod ser; mod source; mod value; pub use config::Config; pub use env::Environment; pub use error::ConfigError; pub use file::{File, FileFormat, FileSourceFile, FileSourceString}; pub use source::Source; pub use value::Value; config-0.11.0/src/path/mod.rs000064400000000000000000000204210000000000000137740ustar 00000000000000use error::*; use nom::error::ErrorKind; use std::collections::HashMap; use std::str::FromStr; use value::{Value, ValueKind}; mod parser; #[derive(Debug, Eq, PartialEq, Clone, Hash)] pub enum Expression { Identifier(String), Child(Box, String), Subscript(Box, isize), } impl FromStr for Expression { type Err = ConfigError; fn from_str(s: &str) -> Result { parser::from_str(s).map_err(ConfigError::PathParse) } } fn sindex_to_uindex(index: isize, len: usize) -> usize { if index >= 0 { index as usize } else { len - (index.abs() as usize) } } impl Expression { pub fn get(self, root: &Value) -> Option<&Value> { match self { Expression::Identifier(id) => { match root.kind { // `x` access on a table is equivalent to: map[x] ValueKind::Table(ref map) => map.get(&id), // all other variants return None _ => None, } } Expression::Child(expr, key) => { match expr.get(root) { Some(value) => { match value.kind { // Access on a table is identical to Identifier, it just forwards ValueKind::Table(ref map) => map.get(&key), // all other variants return None _ => None, } } _ => None, } } Expression::Subscript(expr, index) => match expr.get(root) { Some(value) => match value.kind { ValueKind::Array(ref array) => { let index = sindex_to_uindex(index, array.len()); if index >= array.len() { None } else { Some(&array[index]) } } _ => None, }, _ => None, }, } } pub fn get_mut<'a>(&self, root: &'a mut Value) -> Option<&'a mut Value> { match *self { Expression::Identifier(ref id) => match root.kind { ValueKind::Table(ref mut map) => map.get_mut(id), _ => None, }, Expression::Child(ref expr, ref key) => match expr.get_mut(root) { Some(value) => match value.kind { ValueKind::Table(ref mut map) => map.get_mut(key), _ => None, }, _ => None, }, Expression::Subscript(ref expr, index) => match expr.get_mut(root) { Some(value) => match value.kind { ValueKind::Array(ref mut array) => { let index = sindex_to_uindex(index, array.len()); if index >= array.len() { None } else { Some(&mut array[index]) } } _ => None, }, _ => None, }, } } pub fn get_mut_forcibly<'a>(&self, root: &'a mut Value) -> Option<&'a mut Value> { match *self { Expression::Identifier(ref id) => match root.kind { ValueKind::Table(ref mut map) => Some( map.entry(id.clone()) .or_insert_with(|| Value::new(None, ValueKind::Nil)), ), _ => None, }, Expression::Child(ref expr, ref key) => match expr.get_mut_forcibly(root) { Some(value) => match value.kind { ValueKind::Table(ref mut map) => Some( map.entry(key.clone()) .or_insert_with(|| Value::new(None, ValueKind::Nil)), ), _ => { *value = HashMap::::new().into(); if let ValueKind::Table(ref mut map) = value.kind { Some( map.entry(key.clone()) .or_insert_with(|| Value::new(None, ValueKind::Nil)), ) } else { unreachable!(); } } }, _ => None, }, Expression::Subscript(ref expr, index) => match expr.get_mut_forcibly(root) { Some(value) => { match value.kind { ValueKind::Array(_) => (), _ => *value = Vec::::new().into(), } match value.kind { ValueKind::Array(ref mut array) => { let index = sindex_to_uindex(index, array.len()); if index >= array.len() { array .resize((index + 1) as usize, Value::new(None, ValueKind::Nil)); } Some(&mut array[index]) } _ => None, } } _ => None, }, } } pub fn set(&self, root: &mut Value, value: Value) { match *self { Expression::Identifier(ref id) => { // Ensure that root is a table match root.kind { ValueKind::Table(_) => {} _ => { *root = HashMap::::new().into(); } } match value.kind { ValueKind::Table(ref incoming_map) => { // Pull out another table let mut target = if let ValueKind::Table(ref mut map) = root.kind { map.entry(id.clone()) .or_insert_with(|| HashMap::::new().into()) } else { unreachable!(); }; // Continue the deep merge for (key, val) in incoming_map { Expression::Identifier(key.clone()).set(&mut target, val.clone()); } } _ => { if let ValueKind::Table(ref mut map) = root.kind { // Just do a simple set map.insert(id.clone(), value); } } } } Expression::Child(ref expr, ref key) => { if let Some(parent) = expr.get_mut_forcibly(root) { match parent.kind { ValueKind::Table(_) => { Expression::Identifier(key.clone()).set(parent, value); } _ => { // Didn't find a table. Oh well. Make a table and do this anyway *parent = HashMap::::new().into(); Expression::Identifier(key.clone()).set(parent, value); } } } } Expression::Subscript(ref expr, index) => { if let Some(parent) = expr.get_mut_forcibly(root) { match parent.kind { ValueKind::Array(_) => (), _ => *parent = Vec::::new().into(), } if let ValueKind::Array(ref mut array) = parent.kind { let uindex = sindex_to_uindex(index, array.len()); if uindex >= array.len() { array.resize((uindex + 1) as usize, Value::new(None, ValueKind::Nil)); } array[uindex] = value; } } } } } } config-0.11.0/src/path/parser.rs000064400000000000000000000066140000000000000145210ustar 00000000000000use super::Expression; use nom::{ branch::alt, bytes::complete::{is_a, tag}, character::complete::{char, digit1, space0}, combinator::{map, map_res, opt, recognize}, error::ErrorKind, sequence::{delimited, pair, preceded}, Err, IResult, }; use std::str::{from_utf8, FromStr}; fn raw_ident(i: &str) -> IResult<&str, String> { map( is_a( "abcdefghijklmnopqrstuvwxyz \ ABCDEFGHIJKLMNOPQRSTUVWXYZ \ 0123456789 \ _-", ), |s: &str| s.to_string(), )(i) } fn integer(i: &str) -> IResult<&str, isize> { map_res( delimited(space0, recognize(pair(opt(tag("-")), digit1)), space0), FromStr::from_str, )(i) } fn ident(i: &str) -> IResult<&str, Expression> { map(raw_ident, Expression::Identifier)(i) } fn postfix<'a>(expr: Expression) -> impl Fn(&'a str) -> IResult<&'a str, Expression> { let e2 = expr.clone(); let child = map(preceded(tag("."), raw_ident), move |id| { Expression::Child(Box::new(expr.clone()), id) }); let subscript = map(delimited(char('['), integer, char(']')), move |num| { Expression::Subscript(Box::new(e2.clone()), num) }); alt((child, subscript)) } pub fn from_str(input: &str) -> Result { match ident(input) { Ok((mut rem, mut expr)) => { while !rem.is_empty() { match postfix(expr)(rem) { Ok((rem_, expr_)) => { rem = rem_; expr = expr_; } // Forward Incomplete and Error result => { return result.map(|(_, o)| o).map_err(to_error_kind); } } } Ok(expr) } // Forward Incomplete and Error result => result.map(|(_, o)| o).map_err(to_error_kind), } } pub fn to_error_kind(e: Err<(&str, ErrorKind)>) -> ErrorKind { match e { Err::Incomplete(_) => ErrorKind::Complete, Err::Failure((_, e)) | Err::Error((_, e)) => e, } } #[cfg(test)] mod test { use super::Expression::*; use super::*; #[test] fn test_id() { let parsed: Expression = from_str("abcd").unwrap(); assert_eq!(parsed, Identifier("abcd".into())); } #[test] fn test_id_dash() { let parsed: Expression = from_str("abcd-efgh").unwrap(); assert_eq!(parsed, Identifier("abcd-efgh".into())); } #[test] fn test_child() { let parsed: Expression = from_str("abcd.efgh").unwrap(); let expected = Child(Box::new(Identifier("abcd".into())), "efgh".into()); assert_eq!(parsed, expected); let parsed: Expression = from_str("abcd.efgh.ijkl").unwrap(); let expected = Child( Box::new(Child(Box::new(Identifier("abcd".into())), "efgh".into())), "ijkl".into(), ); assert_eq!(parsed, expected); } #[test] fn test_subscript() { let parsed: Expression = from_str("abcd[12]").unwrap(); let expected = Subscript(Box::new(Identifier("abcd".into())), 12); assert_eq!(parsed, expected); } #[test] fn test_subscript_neg() { let parsed: Expression = from_str("abcd[-1]").unwrap(); let expected = Subscript(Box::new(Identifier("abcd".into())), -1); assert_eq!(parsed, expected); } } config-0.11.0/src/ser.rs000064400000000000000000000416170000000000000130640ustar 00000000000000use serde::ser; use std::fmt::Display; use std::mem; use error::*; use value::{Value, ValueKind}; use Config; #[derive(Default, Debug)] pub struct ConfigSerializer { keys: Vec<(String, Option)>, pub output: Config, } impl ConfigSerializer { fn serialize_primitive(&mut self, value: T) -> Result<()> where T: Into + Display, { let key = match self.last_key_index_pair() { Some((key, Some(index))) => format!("{}[{}]", key, index), Some((key, None)) => key.to_string(), None => { return Err(ConfigError::Message(format!( "key is not found for value {}", value ))) } }; self.output.set(&key, value.into())?; Ok(()) } fn last_key_index_pair(&self) -> Option<(&str, Option)> { let len = self.keys.len(); if len > 0 { self.keys .get(len - 1) .map(|&(ref key, opt)| (key.as_str(), opt)) } else { None } } fn inc_last_key_index(&mut self) -> Result<()> { let len = self.keys.len(); if len > 0 { self.keys .get_mut(len - 1) .map(|pair| pair.1 = pair.1.map(|i| i + 1).or(Some(0))) .ok_or_else(|| { ConfigError::Message(format!("last key is not found in {} keys", len)) }) } else { Err(ConfigError::Message("keys is empty".to_string())) } } fn make_full_key(&self, key: &str) -> String { let len = self.keys.len(); if len > 0 { if let Some(&(ref prev_key, index)) = self.keys.get(len - 1) { return if let Some(index) = index { format!("{}[{}].{}", prev_key, index, key) } else { format!("{}.{}", prev_key, key) }; } } key.to_string() } fn push_key(&mut self, key: &str) { let full_key = self.make_full_key(key); self.keys.push((full_key, None)); } fn pop_key(&mut self) -> Option<(String, Option)> { self.keys.pop() } } impl<'a> ser::Serializer for &'a mut ConfigSerializer { type Ok = (); type Error = ConfigError; type SerializeSeq = Self; type SerializeTuple = Self; type SerializeTupleStruct = Self; type SerializeTupleVariant = Self; type SerializeMap = Self; type SerializeStruct = Self; type SerializeStructVariant = Self; fn serialize_bool(self, v: bool) -> Result { self.serialize_primitive(v) } fn serialize_i8(self, v: i8) -> Result { self.serialize_i64(v as i64) } fn serialize_i16(self, v: i16) -> Result { self.serialize_i64(v as i64) } fn serialize_i32(self, v: i32) -> Result { self.serialize_i64(v as i64) } fn serialize_i64(self, v: i64) -> Result { self.serialize_primitive(v) } fn serialize_u8(self, v: u8) -> Result { self.serialize_u64(v as u64) } fn serialize_u16(self, v: u16) -> Result { self.serialize_u64(v as u64) } fn serialize_u32(self, v: u32) -> Result { self.serialize_u64(v as u64) } fn serialize_u64(self, v: u64) -> Result { if v > (i64::max_value() as u64) { Err(ConfigError::Message(format!( "value {} is greater than the max {}", v, i64::max_value() ))) } else { self.serialize_i64(v as i64) } } fn serialize_f32(self, v: f32) -> Result { self.serialize_f64(v as f64) } fn serialize_f64(self, v: f64) -> Result { self.serialize_primitive(v) } fn serialize_char(self, v: char) -> Result { self.serialize_primitive(v.to_string()) } fn serialize_str(self, v: &str) -> Result { self.serialize_primitive(v.to_string()) } fn serialize_bytes(self, v: &[u8]) -> Result { use serde::ser::SerializeSeq; let mut seq = self.serialize_seq(Some(v.len()))?; for byte in v { seq.serialize_element(byte)?; } seq.end() } fn serialize_none(self) -> Result { self.serialize_unit() } fn serialize_some(self, value: &T) -> Result where T: ?Sized + ser::Serialize, { value.serialize(self) } fn serialize_unit(self) -> Result { self.serialize_primitive(Value::from(ValueKind::Nil)) } fn serialize_unit_struct(self, _name: &'static str) -> Result { self.serialize_unit() } fn serialize_unit_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, ) -> Result { self.serialize_str(&variant) } fn serialize_newtype_struct(self, _name: &'static str, value: &T) -> Result where T: ?Sized + ser::Serialize, { value.serialize(self) } fn serialize_newtype_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, value: &T, ) -> Result where T: ?Sized + ser::Serialize, { self.push_key(&variant); value.serialize(&mut *self)?; self.pop_key(); Ok(()) } fn serialize_seq(self, _len: Option) -> Result { Ok(self) } fn serialize_tuple(self, len: usize) -> Result { self.serialize_seq(Some(len)) } fn serialize_tuple_struct( self, _name: &'static str, len: usize, ) -> Result { self.serialize_seq(Some(len)) } fn serialize_tuple_variant( self, name: &'static str, _variant_index: u32, variant: &'static str, _len: usize, ) -> Result { self.push_key(&variant); Ok(self) } fn serialize_map(self, _len: Option) -> Result { Ok(self) } fn serialize_struct(self, _name: &'static str, len: usize) -> Result { self.serialize_map(Some(len)) } fn serialize_struct_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, len: usize, ) -> Result { self.push_key(&variant); Ok(self) } } impl<'a> ser::SerializeSeq for &'a mut ConfigSerializer { type Ok = (); type Error = ConfigError; fn serialize_element(&mut self, value: &T) -> Result<()> where T: ?Sized + ser::Serialize, { self.inc_last_key_index()?; value.serialize(&mut **self)?; Ok(()) } fn end(self) -> Result { Ok(()) } } impl<'a> ser::SerializeTuple for &'a mut ConfigSerializer { type Ok = (); type Error = ConfigError; fn serialize_element(&mut self, value: &T) -> Result<()> where T: ?Sized + ser::Serialize, { self.inc_last_key_index()?; value.serialize(&mut **self)?; Ok(()) } fn end(self) -> Result { Ok(()) } } impl<'a> ser::SerializeTupleStruct for &'a mut ConfigSerializer { type Ok = (); type Error = ConfigError; fn serialize_field(&mut self, value: &T) -> Result<()> where T: ?Sized + ser::Serialize, { self.inc_last_key_index()?; value.serialize(&mut **self)?; Ok(()) } fn end(self) -> Result { Ok(()) } } impl<'a> ser::SerializeTupleVariant for &'a mut ConfigSerializer { type Ok = (); type Error = ConfigError; fn serialize_field(&mut self, value: &T) -> Result<()> where T: ?Sized + ser::Serialize, { self.inc_last_key_index()?; value.serialize(&mut **self)?; Ok(()) } fn end(self) -> Result { self.pop_key(); Ok(()) } } impl<'a> ser::SerializeMap for &'a mut ConfigSerializer { type Ok = (); type Error = ConfigError; fn serialize_key(&mut self, key: &T) -> Result<()> where T: ?Sized + ser::Serialize, { let key_serializer = StringKeySerializer; let key = key.serialize(key_serializer)?; self.push_key(&key); Ok(()) } fn serialize_value(&mut self, value: &T) -> Result<()> where T: ?Sized + ser::Serialize, { value.serialize(&mut **self)?; self.pop_key(); Ok(()) } fn end(self) -> Result { Ok(()) } } impl<'a> ser::SerializeStruct for &'a mut ConfigSerializer { type Ok = (); type Error = ConfigError; fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<()> where T: ?Sized + ser::Serialize, { self.push_key(key); value.serialize(&mut **self)?; self.pop_key(); Ok(()) } fn end(self) -> Result { Ok(()) } } impl<'a> ser::SerializeStructVariant for &'a mut ConfigSerializer { type Ok = (); type Error = ConfigError; fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<()> where T: ?Sized + ser::Serialize, { self.push_key(key); value.serialize(&mut **self)?; self.pop_key(); Ok(()) } fn end(self) -> Result { self.pop_key(); Ok(()) } } pub struct StringKeySerializer; impl ser::Serializer for StringKeySerializer { type Ok = String; type Error = ConfigError; type SerializeSeq = Self; type SerializeTuple = Self; type SerializeTupleStruct = Self; type SerializeTupleVariant = Self; type SerializeMap = Self; type SerializeStruct = Self; type SerializeStructVariant = Self; fn serialize_bool(self, v: bool) -> Result { Ok(v.to_string()) } fn serialize_i8(self, v: i8) -> Result { Ok(v.to_string()) } fn serialize_i16(self, v: i16) -> Result { Ok(v.to_string()) } fn serialize_i32(self, v: i32) -> Result { Ok(v.to_string()) } fn serialize_i64(self, v: i64) -> Result { Ok(v.to_string()) } fn serialize_u8(self, v: u8) -> Result { Ok(v.to_string()) } fn serialize_u16(self, v: u16) -> Result { Ok(v.to_string()) } fn serialize_u32(self, v: u32) -> Result { Ok(v.to_string()) } fn serialize_u64(self, v: u64) -> Result { Ok(v.to_string()) } fn serialize_f32(self, v: f32) -> Result { Ok(v.to_string()) } fn serialize_f64(self, v: f64) -> Result { Ok(v.to_string()) } fn serialize_char(self, v: char) -> Result { Ok(v.to_string()) } fn serialize_str(self, v: &str) -> Result { Ok(v.to_string()) } fn serialize_bytes(self, v: &[u8]) -> Result { Ok(String::from_utf8_lossy(v).to_string()) } fn serialize_none(self) -> Result { self.serialize_unit() } fn serialize_some(self, value: &T) -> Result where T: ?Sized + ser::Serialize, { value.serialize(self) } fn serialize_unit(self) -> Result { Ok(String::new()) } fn serialize_unit_struct(self, _name: &str) -> Result { self.serialize_unit() } fn serialize_unit_variant( self, _name: &str, _variant_index: u32, variant: &str, ) -> Result { Ok(variant.to_string()) } fn serialize_newtype_struct(self, _name: &str, value: &T) -> Result where T: ?Sized + ser::Serialize, { value.serialize(self) } fn serialize_newtype_variant( self, _name: &str, _variant_index: u32, _variant: &str, value: &T, ) -> Result where T: ?Sized + ser::Serialize, { value.serialize(self) } fn serialize_seq(self, _len: Option) -> Result { Err(ConfigError::Message( "seq can't serialize to string key".to_string(), )) } fn serialize_tuple(self, _len: usize) -> Result { Err(ConfigError::Message( "tuple can't serialize to string key".to_string(), )) } fn serialize_tuple_struct(self, name: &str, _len: usize) -> Result { Err(ConfigError::Message(format!( "tuple struct {} can't serialize to string key", name ))) } fn serialize_tuple_variant( self, name: &str, _variant_index: u32, variant: &str, _len: usize, ) -> Result { Err(ConfigError::Message(format!( "tuple variant {}::{} can't serialize to string key", name, variant ))) } fn serialize_map(self, _len: Option) -> Result { Err(ConfigError::Message( "map can't serialize to string key".to_string(), )) } fn serialize_struct(self, name: &str, _len: usize) -> Result { Err(ConfigError::Message(format!( "struct {} can't serialize to string key", name ))) } fn serialize_struct_variant( self, name: &str, _variant_index: u32, variant: &str, _len: usize, ) -> Result { Err(ConfigError::Message(format!( "struct variant {}::{} can't serialize to string key", name, variant ))) } } impl ser::SerializeSeq for StringKeySerializer { type Ok = String; type Error = ConfigError; fn serialize_element(&mut self, value: &T) -> Result<()> where T: ?Sized + ser::Serialize, { unreachable!() } fn end(self) -> Result { unreachable!() } } impl ser::SerializeTuple for StringKeySerializer { type Ok = String; type Error = ConfigError; fn serialize_element(&mut self, value: &T) -> Result<()> where T: ?Sized + ser::Serialize, { unreachable!() } fn end(self) -> Result { unreachable!() } } impl ser::SerializeTupleStruct for StringKeySerializer { type Ok = String; type Error = ConfigError; fn serialize_field(&mut self, value: &T) -> Result<()> where T: ?Sized + ser::Serialize, { unreachable!() } fn end(self) -> Result { unreachable!() } } impl ser::SerializeTupleVariant for StringKeySerializer { type Ok = String; type Error = ConfigError; fn serialize_field(&mut self, value: &T) -> Result<()> where T: ?Sized + ser::Serialize, { unreachable!() } fn end(self) -> Result { unreachable!() } } impl ser::SerializeMap for StringKeySerializer { type Ok = String; type Error = ConfigError; fn serialize_key(&mut self, key: &T) -> Result<()> where T: ?Sized + ser::Serialize, { unreachable!() } fn serialize_value(&mut self, value: &T) -> Result<()> where T: ?Sized + ser::Serialize, { unreachable!() } fn end(self) -> Result { unreachable!() } } impl ser::SerializeStruct for StringKeySerializer { type Ok = String; type Error = ConfigError; fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<()> where T: ?Sized + ser::Serialize, { unreachable!() } fn end(self) -> Result { unreachable!() } } impl ser::SerializeStructVariant for StringKeySerializer { type Ok = String; type Error = ConfigError; fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<()> where T: ?Sized + ser::Serialize, { unreachable!() } fn end(self) -> Result { unreachable!() } } #[cfg(test)] mod test { use super::*; use serde::Serialize; #[test] fn test_struct() { #[derive(Debug, Serialize, Deserialize, PartialEq)] struct Test { int: u32, seq: Vec, } let test = Test { int: 1, seq: vec!["a".to_string(), "b".to_string()], }; let config = Config::try_from(&test).unwrap(); let actual: Test = config.try_into().unwrap(); assert_eq!(test, actual); } } config-0.11.0/src/source.rs000064400000000000000000000042660000000000000135720ustar 00000000000000use error::*; use path; use std::collections::HashMap; use std::fmt::Debug; use std::str::FromStr; use value::{Value, ValueKind}; /// Describes a generic _source_ of configuration properties. pub trait Source: Debug { fn clone_into_box(&self) -> Box; /// Collect all configuration properties available from this source and return /// a HashMap. fn collect(&self) -> Result>; fn collect_to(&self, cache: &mut Value) -> Result<()> { let props = match self.collect() { Ok(props) => props, Err(error) => { return Err(error); } }; for (key, val) in &props { match path::Expression::from_str(key) { // Set using the path Ok(expr) => expr.set(cache, val.clone()), // Set diretly anyway _ => path::Expression::Identifier(key.clone()).set(cache, val.clone()), } } Ok(()) } } impl Clone for Box { fn clone(&self) -> Box { self.clone_into_box() } } impl Source for Vec> { fn clone_into_box(&self) -> Box { Box::new((*self).clone()) } fn collect(&self) -> Result> { let mut cache: Value = HashMap::::new().into(); for source in self { source.collect_to(&mut cache)?; } if let ValueKind::Table(table) = cache.kind { Ok(table) } else { unreachable!(); } } } impl Source for Vec where T: Source + Sync + Send, T: Clone, T: 'static, { fn clone_into_box(&self) -> Box { Box::new((*self).clone()) } fn collect(&self) -> Result> { let mut cache: Value = HashMap::::new().into(); for source in self { source.collect_to(&mut cache)?; } if let ValueKind::Table(table) = cache.kind { Ok(table) } else { unreachable!(); } } } config-0.11.0/src/value.rs000064400000000000000000000373360000000000000134120ustar 00000000000000use error::*; use serde::de::{Deserialize, Deserializer, Visitor}; use std::collections::HashMap; use std::fmt; use std::fmt::Display; /// Underlying kind of the configuration value. #[derive(Debug, Clone, PartialEq)] pub enum ValueKind { Nil, Boolean(bool), Integer(i64), Float(f64), String(String), Table(Table), Array(Array), } pub type Array = Vec; pub type Table = HashMap; impl Default for ValueKind { fn default() -> Self { ValueKind::Nil } } impl From> for ValueKind where T: Into, { fn from(value: Option) -> Self { match value { Some(value) => value.into(), None => ValueKind::Nil, } } } impl From for ValueKind { fn from(value: String) -> Self { ValueKind::String(value) } } impl<'a> From<&'a str> for ValueKind { fn from(value: &'a str) -> Self { ValueKind::String(value.into()) } } impl From for ValueKind { fn from(value: i64) -> Self { ValueKind::Integer(value) } } impl From for ValueKind { fn from(value: f64) -> Self { ValueKind::Float(value) } } impl From for ValueKind { fn from(value: bool) -> Self { ValueKind::Boolean(value) } } impl From> for ValueKind where T: Into, { fn from(values: HashMap) -> Self { let mut r = HashMap::new(); for (k, v) in values { r.insert(k.clone(), v.into()); } ValueKind::Table(r) } } impl From> for ValueKind where T: Into, { fn from(values: Vec) -> Self { let mut l = Vec::new(); for v in values { l.push(v.into()); } ValueKind::Array(l) } } impl Display for ValueKind { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ValueKind::String(ref value) => write!(f, "{}", value), ValueKind::Boolean(value) => write!(f, "{}", value), ValueKind::Integer(value) => write!(f, "{}", value), ValueKind::Float(value) => write!(f, "{}", value), ValueKind::Nil => write!(f, "nil"), // TODO: Figure out a nice Display for these ValueKind::Table(ref table) => write!(f, "{:?}", table), ValueKind::Array(ref array) => write!(f, "{:?}", array), } } } /// A configuration value. #[derive(Default, Debug, Clone, PartialEq)] pub struct Value { /// A description of the original location of the value. /// /// A Value originating from a File might contain: /// ```text /// Settings.toml /// ``` /// /// A Value originating from the environment would contain: /// ```text /// the envrionment /// ``` /// /// A Value originating from a remote source might contain: /// ```text /// etcd+http://127.0.0.1:2379 /// ``` origin: Option, /// Underlying kind of the configuration value. pub kind: ValueKind, } impl Value { /// Create a new value instance that will remember its source uri. pub fn new(origin: Option<&String>, kind: V) -> Self where V: Into, { Value { origin: origin.cloned(), kind: kind.into(), } } /// Attempt to deserialize this value into the requested type. pub fn try_into<'de, T: Deserialize<'de>>(self) -> Result { T::deserialize(self) } /// Returns `self` as a bool, if possible. // FIXME: Should this not be `try_into_*` ? pub fn into_bool(self) -> Result { match self.kind { ValueKind::Boolean(value) => Ok(value), ValueKind::Integer(value) => Ok(value != 0), ValueKind::Float(value) => Ok(value != 0.0), ValueKind::String(ref value) => { match value.to_lowercase().as_ref() { "1" | "true" | "on" | "yes" => Ok(true), "0" | "false" | "off" | "no" => Ok(false), // Unexpected string value s => Err(ConfigError::invalid_type( self.origin.clone(), Unexpected::Str(s.into()), "a boolean", )), } } // Unexpected type ValueKind::Nil => Err(ConfigError::invalid_type( self.origin, Unexpected::Unit, "a boolean", )), ValueKind::Table(_) => Err(ConfigError::invalid_type( self.origin, Unexpected::Map, "a boolean", )), ValueKind::Array(_) => Err(ConfigError::invalid_type( self.origin, Unexpected::Seq, "a boolean", )), } } /// Returns `self` into an i64, if possible. // FIXME: Should this not be `try_into_*` ? pub fn into_int(self) -> Result { match self.kind { ValueKind::Integer(value) => Ok(value), ValueKind::String(ref s) => { match s.to_lowercase().as_ref() { "true" | "on" | "yes" => Ok(1), "false" | "off" | "no" => Ok(0), _ => { s.parse().map_err(|_| { // Unexpected string ConfigError::invalid_type( self.origin.clone(), Unexpected::Str(s.clone()), "an integer", ) }) } } } ValueKind::Boolean(value) => Ok(if value { 1 } else { 0 }), ValueKind::Float(value) => Ok(value.round() as i64), // Unexpected type ValueKind::Nil => Err(ConfigError::invalid_type( self.origin, Unexpected::Unit, "an integer", )), ValueKind::Table(_) => Err(ConfigError::invalid_type( self.origin, Unexpected::Map, "an integer", )), ValueKind::Array(_) => Err(ConfigError::invalid_type( self.origin, Unexpected::Seq, "an integer", )), } } /// Returns `self` into a f64, if possible. // FIXME: Should this not be `try_into_*` ? pub fn into_float(self) -> Result { match self.kind { ValueKind::Float(value) => Ok(value), ValueKind::String(ref s) => { match s.to_lowercase().as_ref() { "true" | "on" | "yes" => Ok(1.0), "false" | "off" | "no" => Ok(0.0), _ => { s.parse().map_err(|_| { // Unexpected string ConfigError::invalid_type( self.origin.clone(), Unexpected::Str(s.clone()), "a floating point", ) }) } } } ValueKind::Integer(value) => Ok(value as f64), ValueKind::Boolean(value) => Ok(if value { 1.0 } else { 0.0 }), // Unexpected type ValueKind::Nil => Err(ConfigError::invalid_type( self.origin, Unexpected::Unit, "a floating point", )), ValueKind::Table(_) => Err(ConfigError::invalid_type( self.origin, Unexpected::Map, "a floating point", )), ValueKind::Array(_) => Err(ConfigError::invalid_type( self.origin, Unexpected::Seq, "a floating point", )), } } /// Returns `self` into a str, if possible. // FIXME: Should this not be `try_into_*` ? pub fn into_str(self) -> Result { match self.kind { ValueKind::String(value) => Ok(value), ValueKind::Boolean(value) => Ok(value.to_string()), ValueKind::Integer(value) => Ok(value.to_string()), ValueKind::Float(value) => Ok(value.to_string()), // Cannot convert ValueKind::Nil => Err(ConfigError::invalid_type( self.origin, Unexpected::Unit, "a string", )), ValueKind::Table(_) => Err(ConfigError::invalid_type( self.origin, Unexpected::Map, "a string", )), ValueKind::Array(_) => Err(ConfigError::invalid_type( self.origin, Unexpected::Seq, "a string", )), } } /// Returns `self` into an array, if possible // FIXME: Should this not be `try_into_*` ? pub fn into_array(self) -> Result> { match self.kind { ValueKind::Array(value) => Ok(value), // Cannot convert ValueKind::Float(value) => Err(ConfigError::invalid_type( self.origin, Unexpected::Float(value), "an array", )), ValueKind::String(value) => Err(ConfigError::invalid_type( self.origin, Unexpected::Str(value), "an array", )), ValueKind::Integer(value) => Err(ConfigError::invalid_type( self.origin, Unexpected::Integer(value), "an array", )), ValueKind::Boolean(value) => Err(ConfigError::invalid_type( self.origin, Unexpected::Bool(value), "an array", )), ValueKind::Nil => Err(ConfigError::invalid_type( self.origin, Unexpected::Unit, "an array", )), ValueKind::Table(_) => Err(ConfigError::invalid_type( self.origin, Unexpected::Map, "an array", )), } } /// If the `Value` is a Table, returns the associated Map. // FIXME: Should this not be `try_into_*` ? pub fn into_table(self) -> Result> { match self.kind { ValueKind::Table(value) => Ok(value), // Cannot convert ValueKind::Float(value) => Err(ConfigError::invalid_type( self.origin, Unexpected::Float(value), "a map", )), ValueKind::String(value) => Err(ConfigError::invalid_type( self.origin, Unexpected::Str(value), "a map", )), ValueKind::Integer(value) => Err(ConfigError::invalid_type( self.origin, Unexpected::Integer(value), "a map", )), ValueKind::Boolean(value) => Err(ConfigError::invalid_type( self.origin, Unexpected::Bool(value), "a map", )), ValueKind::Nil => Err(ConfigError::invalid_type( self.origin, Unexpected::Unit, "a map", )), ValueKind::Array(_) => Err(ConfigError::invalid_type( self.origin, Unexpected::Seq, "a map", )), } } } impl<'de> Deserialize<'de> for Value { #[inline] fn deserialize(deserializer: D) -> ::std::result::Result where D: Deserializer<'de>, { struct ValueVisitor; impl<'de> Visitor<'de> for ValueVisitor { type Value = Value; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("any valid configuration value") } #[inline] fn visit_bool(self, value: bool) -> ::std::result::Result { Ok(value.into()) } #[inline] fn visit_i8(self, value: i8) -> ::std::result::Result { Ok((value as i64).into()) } #[inline] fn visit_i16(self, value: i16) -> ::std::result::Result { Ok((value as i64).into()) } #[inline] fn visit_i32(self, value: i32) -> ::std::result::Result { Ok((value as i64).into()) } #[inline] fn visit_i64(self, value: i64) -> ::std::result::Result { Ok(value.into()) } #[inline] fn visit_u8(self, value: u8) -> ::std::result::Result { Ok((value as i64).into()) } #[inline] fn visit_u16(self, value: u16) -> ::std::result::Result { Ok((value as i64).into()) } #[inline] fn visit_u32(self, value: u32) -> ::std::result::Result { Ok((value as i64).into()) } #[inline] fn visit_u64(self, value: u64) -> ::std::result::Result { // FIXME: This is bad Ok((value as i64).into()) } #[inline] fn visit_f64(self, value: f64) -> ::std::result::Result { Ok(value.into()) } #[inline] fn visit_str(self, value: &str) -> ::std::result::Result where E: ::serde::de::Error, { self.visit_string(String::from(value)) } #[inline] fn visit_string(self, value: String) -> ::std::result::Result { Ok(value.into()) } #[inline] fn visit_none(self) -> ::std::result::Result { Ok(Value::new(None, ValueKind::Nil)) } #[inline] fn visit_some(self, deserializer: D) -> ::std::result::Result where D: Deserializer<'de>, { Deserialize::deserialize(deserializer) } #[inline] fn visit_unit(self) -> ::std::result::Result { Ok(Value::new(None, ValueKind::Nil)) } #[inline] fn visit_seq(self, mut visitor: V) -> ::std::result::Result where V: ::serde::de::SeqAccess<'de>, { let mut vec = Array::new(); while let Some(elem) = visitor.next_element()? { vec.push(elem); } Ok(vec.into()) } fn visit_map(self, mut visitor: V) -> ::std::result::Result where V: ::serde::de::MapAccess<'de>, { let mut values = Table::new(); while let Some((key, value)) = visitor.next_entry()? { values.insert(key, value); } Ok(values.into()) } } deserializer.deserialize_any(ValueVisitor) } } impl From for Value where T: Into, { fn from(value: T) -> Self { Value { origin: None, kind: value.into(), } } } impl Display for Value { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.kind) } } config-0.11.0/tests/Settings-invalid.hjson000064400000000000000000000000300000000000000165470ustar 00000000000000{ ok: true, error } config-0.11.0/tests/Settings-invalid.ini000064400000000000000000000000210000000000000162050ustar 00000000000000ok : true, error config-0.11.0/tests/Settings-invalid.json000064400000000000000000000000340000000000000164030ustar 00000000000000{ "ok": true, "error" } config-0.11.0/tests/Settings-invalid.toml000064400000000000000000000000260000000000000164060ustar 00000000000000ok = true error = tru config-0.11.0/tests/Settings-invalid.yaml000064400000000000000000000000250000000000000163740ustar 00000000000000ok: true error false config-0.11.0/tests/Settings-production.toml000064400000000000000000000001350000000000000171470ustar 00000000000000debug = false production = true [place] rating = 4.9 [place.creator] name = "Somebody New" config-0.11.0/tests/Settings.hjson000064400000000000000000000004110000000000000151260ustar 00000000000000{ debug: true production: false arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] place: { name: Torre di Pisa longitude: 43.7224985 latitude: 10.3970522 favorite: false reviews: 3866 rating: 4.5 creator: { name: John Smith } } } config-0.11.0/tests/Settings.ini000064400000000000000000000002400000000000000145640ustar 00000000000000debug = true production = false [place] name = Torre di Pisa longitude = 43.7224985 latitude = 10.3970522 favorite = false reviews = 3866 rating = 4.5 config-0.11.0/tests/Settings.json000064400000000000000000000004560000000000000147670ustar 00000000000000{ "debug": true, "production": false, "arr": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], "place": { "name": "Torre di Pisa", "longitude": 43.7224985, "latitude": 10.3970522, "favorite": false, "reviews": 3866, "rating": 4.5, "creator": { "name": "John Smith" } } } config-0.11.0/tests/Settings.toml000064400000000000000000000012060000000000000147630ustar 00000000000000debug = true debug_s = "true" production = false production_s = "false" code = 53 # errors boolean_s_parse = "fals" arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] quarks = ["up", "down", "strange", "charm", "bottom", "top"] [diodes] green = "off" [diodes.red] brightness = 100 [diodes.blue] blinking = [300, 700] [diodes.white.pattern] name = "christmas" inifinite = true [[items]] name = "1" [[items]] name = "2" [place] number = 1 name = "Torre di Pisa" longitude = 43.7224985 latitude = 10.3970522 favorite = false reviews = 3866 rating = 4.5 [place.creator] name = "John Smith" [proton] up = 2 down = 1 [divisors] 1 = 1 2 = 2 4 = 3 5 = 2 config-0.11.0/tests/Settings.yaml000064400000000000000000000003370000000000000147560ustar 00000000000000debug: true production: false arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] place: name: Torre di Pisa longitude: 43.7224985 latitude: 10.3970522 favorite: false reviews: 3866 rating: 4.5 creator: name: John Smith config-0.11.0/tests/datetime.rs000064400000000000000000000050660000000000000144400ustar 00000000000000#![cfg(all( feature = "toml", feature = "json", feature = "hjson", feature = "yaml", feature = "ini", ))] extern crate chrono; extern crate config; use chrono::{DateTime, TimeZone, Utc}; use config::*; fn make() -> Config { Config::default() .merge(File::from_str( r#" { "json_datetime": "2017-05-10T02:14:53Z" } "#, FileFormat::Json, )) .unwrap() .merge(File::from_str( r#" yaml_datetime: 2017-06-12T10:58:30Z "#, FileFormat::Yaml, )) .unwrap() .merge(File::from_str( r#" toml_datetime = 2017-05-11T14:55:15Z "#, FileFormat::Toml, )) .unwrap() .merge(File::from_str( r#" { "hjson_datetime": "2017-05-10T02:14:53Z" } "#, FileFormat::Hjson, )) .unwrap() .merge(File::from_str( r#" ini_datetime = 2017-05-10T02:14:53Z "#, FileFormat::Ini, )) .unwrap() .clone() } #[test] fn test_datetime_string() { let s = make(); // JSON let date: String = s.get("json_datetime").unwrap(); assert_eq!(&date, "2017-05-10T02:14:53Z"); // TOML let date: String = s.get("toml_datetime").unwrap(); assert_eq!(&date, "2017-05-11T14:55:15Z"); // YAML let date: String = s.get("yaml_datetime").unwrap(); assert_eq!(&date, "2017-06-12T10:58:30Z"); // HJSON let date: String = s.get("hjson_datetime").unwrap(); assert_eq!(&date, "2017-05-10T02:14:53Z"); // INI let date: String = s.get("ini_datetime").unwrap(); assert_eq!(&date, "2017-05-10T02:14:53Z"); } #[test] fn test_datetime() { let s = make(); // JSON let date: DateTime = s.get("json_datetime").unwrap(); assert_eq!(date, Utc.ymd(2017, 5, 10).and_hms(2, 14, 53)); // TOML let date: DateTime = s.get("toml_datetime").unwrap(); assert_eq!(date, Utc.ymd(2017, 5, 11).and_hms(14, 55, 15)); // YAML let date: DateTime = s.get("yaml_datetime").unwrap(); assert_eq!(date, Utc.ymd(2017, 6, 12).and_hms(10, 58, 30)); // HJSON let date: DateTime = s.get("hjson_datetime").unwrap(); assert_eq!(date, Utc.ymd(2017, 5, 10).and_hms(2, 14, 53)); // INI let date: DateTime = s.get("ini_datetime").unwrap(); assert_eq!(date, Utc.ymd(2017, 5, 10).and_hms(2, 14, 53)); } config-0.11.0/tests/defaults.rs000064400000000000000000000013160000000000000144450ustar 00000000000000extern crate config; #[macro_use] extern crate serde_derive; use config::*; #[derive(Debug, Serialize, Deserialize)] #[serde(default)] pub struct Settings { pub db_host: String, } impl Default for Settings { fn default() -> Self { Settings { db_host: String::from("default"), } } } #[test] fn set_defaults() { let c = Config::new(); let s: Settings = c.try_into().expect("Deserialization failed"); assert_eq!(s.db_host, "default"); } #[test] fn try_from_defaults() { let c = Config::try_from(&Settings::default()).expect("Serialization failed"); let s: Settings = c.try_into().expect("Deserialization failed"); assert_eq!(s.db_host, "default"); } config-0.11.0/tests/empty.rs000064400000000000000000000005710000000000000137760ustar 00000000000000extern crate config; #[macro_use] extern crate serde_derive; use config::*; #[derive(Debug, Serialize, Deserialize)] struct Settings { #[serde(skip)] foo: isize, #[serde(skip)] bar: u8, } #[test] fn empty_deserializes() { let s: Settings = Config::new().try_into().expect("Deserialization failed"); assert_eq!(s.foo, 0); assert_eq!(s.bar, 0); } config-0.11.0/tests/env.rs000064400000000000000000000030740000000000000134310ustar 00000000000000extern crate config; use config::*; use std::env; #[test] fn test_default() { env::set_var("A_B_C", "abc"); let environment = Environment::new(); assert!(environment.collect().unwrap().contains_key("a_b_c")); env::remove_var("A_B_C"); } #[test] fn test_prefix_is_removed_from_key() { env::set_var("B_A_C", "abc"); let environment = Environment::with_prefix("B"); assert!(environment.collect().unwrap().contains_key("a_c")); env::remove_var("B_A_C"); } #[test] fn test_prefix_with_variant_forms_of_spelling() { env::set_var("a_A_C", "abc"); let environment = Environment::with_prefix("a"); assert!(environment.collect().unwrap().contains_key("a_c")); env::remove_var("a_A_C"); env::set_var("aB_A_C", "abc"); let environment = Environment::with_prefix("aB"); assert!(environment.collect().unwrap().contains_key("a_c")); env::remove_var("aB_A_C"); env::set_var("Ab_A_C", "abc"); let environment = Environment::with_prefix("ab"); assert!(environment.collect().unwrap().contains_key("a_c")); env::remove_var("Ab_A_C"); } #[test] fn test_separator_behavior() { env::set_var("C_B_A", "abc"); let environment = Environment::with_prefix("C").separator("_"); assert!(environment.collect().unwrap().contains_key("b.a")); env::remove_var("C_B_A"); } #[test] fn test_empty_value_is_ignored() { env::set_var("C_A_B", ""); let environment = Environment::new().ignore_empty(true); assert!(!environment.collect().unwrap().contains_key("c_a_b")); env::remove_var("C_A_B"); } config-0.11.0/tests/errors.rs000064400000000000000000000061720000000000000141570ustar 00000000000000#![cfg(feature = "toml")] extern crate config; #[macro_use] extern crate serde_derive; use config::*; use std::path::PathBuf; fn make() -> Config { let mut c = Config::default(); c.merge(File::new("tests/Settings", FileFormat::Toml)) .unwrap(); c } #[test] fn test_error_parse() { let mut c = Config::default(); let res = c.merge(File::new("tests/Settings-invalid", FileFormat::Toml)); let path: PathBuf = ["tests", "Settings-invalid.toml"].iter().collect(); assert!(res.is_err()); assert_eq!( res.unwrap_err().to_string(), format!( "invalid TOML value, did you mean to use a quoted string? at line 2 column 9 in {}", path.display() ) ); } #[test] fn test_error_type() { let c = make(); let res = c.get::("boolean_s_parse"); let path: PathBuf = ["tests", "Settings.toml"].iter().collect(); assert!(res.is_err()); assert_eq!( res.unwrap_err().to_string(), format!( "invalid type: string \"fals\", expected a boolean for key `boolean_s_parse` in {}", path.display() ) ); } #[test] fn test_error_type_detached() { let c = make(); let value = c.get::("boolean_s_parse").unwrap(); let res = value.try_into::(); assert!(res.is_err()); assert_eq!( res.unwrap_err().to_string(), "invalid type: string \"fals\", expected a boolean".to_string() ); } #[test] fn test_error_enum_de() { #[derive(Debug, Deserialize, PartialEq)] enum Diode { Off, Brightness(i32), Blinking(i32, i32), Pattern { name: String, inifinite: bool }, } let on_v: Value = "on".into(); let on_d = on_v.try_into::(); assert_eq!( on_d.unwrap_err().to_string(), "enum Diode does not have variant constructor on".to_string() ); let array_v: Value = vec![100, 100].into(); let array_d = array_v.try_into::(); assert_eq!( array_d.unwrap_err().to_string(), "value of enum Diode should be represented by either string or table with exactly one key" ); let confused_v: Value = [ ("Brightness".to_string(), 100.into()), ("Blinking".to_string(), vec![300, 700].into()), ] .iter() .cloned() .collect::>() .into(); let confused_d = confused_v.try_into::(); assert_eq!( confused_d.unwrap_err().to_string(), "value of enum Diode should be represented by either string or table with exactly one key" ); } #[test] fn error_with_path() { #[derive(Debug, Deserialize)] struct Inner { test: i32, } #[derive(Debug, Deserialize)] struct Outer { inner: Inner, } const CFG: &str = r#" inner: test: ABC "#; let mut cfg = Config::new(); cfg.merge(File::from_str(CFG, FileFormat::Yaml)).unwrap(); let e = cfg.try_into::().unwrap_err(); if let ConfigError::Type { key: Some(path), .. } = e { assert_eq!(path, "inner.test"); } else { panic!("Wrong error {:?}", e); } } config-0.11.0/tests/file.rs000064400000000000000000000025110000000000000135530ustar 00000000000000#![cfg(feature = "yaml")] extern crate config; use config::*; #[test] fn test_file_not_required() { let mut c = Config::default(); let res = c.merge(File::new("tests/NoSettings", FileFormat::Yaml).required(false)); assert!(res.is_ok()); } #[test] fn test_file_required_not_found() { let mut c = Config::default(); let res = c.merge(File::new("tests/NoSettings", FileFormat::Yaml)); assert!(res.is_err()); assert_eq!( res.unwrap_err().to_string(), "configuration file \"tests/NoSettings\" not found".to_string() ); } #[test] fn test_file_auto() { let mut c = Config::default(); c.merge(File::with_name("tests/Settings-production")) .unwrap(); assert_eq!(c.get("debug").ok(), Some(false)); assert_eq!(c.get("production").ok(), Some(true)); } #[test] fn test_file_auto_not_found() { let mut c = Config::default(); let res = c.merge(File::with_name("tests/NoSettings")); assert!(res.is_err()); assert_eq!( res.unwrap_err().to_string(), "configuration file \"tests/NoSettings\" not found".to_string() ); } #[test] fn test_file_ext() { let mut c = Config::default(); c.merge(File::with_name("tests/Settings.json")).unwrap(); assert_eq!(c.get("debug").ok(), Some(true)); assert_eq!(c.get("production").ok(), Some(false)); } config-0.11.0/tests/file_hjson.rs000064400000000000000000000040460000000000000147610ustar 00000000000000#![cfg(feature = "hjson")] extern crate config; extern crate float_cmp; extern crate serde; #[macro_use] extern crate serde_derive; use config::*; use float_cmp::ApproxEqUlps; use std::collections::HashMap; use std::path::PathBuf; #[derive(Debug, Deserialize)] struct Place { name: String, longitude: f64, latitude: f64, favorite: bool, telephone: Option, reviews: u64, creator: HashMap, rating: Option, } #[derive(Debug, Deserialize)] struct Settings { debug: f64, production: Option, place: Place, #[serde(rename = "arr")] elements: Vec, } fn make() -> Config { let mut c = Config::default(); c.merge(File::new("tests/Settings", FileFormat::Hjson)) .unwrap(); c } #[test] fn test_file() { let c = make(); // Deserialize the entire file as single struct let s: Settings = c.try_into().unwrap(); assert!(s.debug.approx_eq_ulps(&1.0, 2)); assert_eq!(s.production, Some("false".to_string())); assert_eq!(s.place.name, "Torre di Pisa"); assert!(s.place.longitude.approx_eq_ulps(&43.7224985, 2)); assert!(s.place.latitude.approx_eq_ulps(&10.3970522, 2)); assert_eq!(s.place.favorite, false); assert_eq!(s.place.reviews, 3866); assert_eq!(s.place.rating, Some(4.5)); assert_eq!(s.place.telephone, None); assert_eq!(s.elements.len(), 10); assert_eq!(s.elements[3], "4".to_string()); assert_eq!( s.place.creator["name"].clone().into_str().unwrap(), "John Smith".to_string() ); } #[test] fn test_error_parse() { let mut c = Config::default(); let res = c.merge(File::new("tests/Settings-invalid", FileFormat::Hjson)); let path: PathBuf = ["tests", "Settings-invalid.hjson"].iter().collect(); assert!(res.is_err()); assert_eq!( res.unwrap_err().to_string(), format!("Found a punctuator where a key name was expected (check your syntax or use quotes if the key name includes {{}}[],: or whitespace) at line 4 column 1 in {}", path.display()) ); } config-0.11.0/tests/file_ini.rs000064400000000000000000000027160000000000000144210ustar 00000000000000#![cfg(feature = "ini")] extern crate config; extern crate float_cmp; extern crate serde; #[macro_use] extern crate serde_derive; use config::*; use std::path::PathBuf; #[derive(Debug, Deserialize, PartialEq)] struct Place { name: String, longitude: f64, latitude: f64, favorite: bool, reviews: u64, rating: Option, } #[derive(Debug, Deserialize, PartialEq)] struct Settings { debug: f64, place: Place, } fn make() -> Config { let mut c = Config::default(); c.merge(File::new("tests/Settings", FileFormat::Ini)) .unwrap(); c } #[test] fn test_file() { let c = make(); let s: Settings = c.try_into().unwrap(); assert_eq!( s, Settings { debug: 1.0, place: Place { name: String::from("Torre di Pisa"), longitude: 43.7224985, latitude: 10.3970522, favorite: false, reviews: 3866, rating: Some(4.5), }, } ); } #[test] fn test_error_parse() { let mut c = Config::default(); let res = c.merge(File::new("tests/Settings-invalid", FileFormat::Ini)); let path: PathBuf = ["tests", "Settings-invalid.ini"].iter().collect(); assert!(res.is_err()); assert_eq!( res.unwrap_err().to_string(), format!( r#"2:0 Expecting "[Some('='), Some(':')]" but found EOF. in {}"#, path.display() ) ); } config-0.11.0/tests/file_json.rs000064400000000000000000000037540000000000000146160ustar 00000000000000#![cfg(feature = "json")] extern crate config; extern crate float_cmp; extern crate serde; #[macro_use] extern crate serde_derive; use config::*; use float_cmp::ApproxEqUlps; use std::collections::HashMap; use std::path::PathBuf; #[derive(Debug, Deserialize)] struct Place { name: String, longitude: f64, latitude: f64, favorite: bool, telephone: Option, reviews: u64, creator: HashMap, rating: Option, } #[derive(Debug, Deserialize)] struct Settings { debug: f64, production: Option, place: Place, #[serde(rename = "arr")] elements: Vec, } fn make() -> Config { let mut c = Config::default(); c.merge(File::new("tests/Settings", FileFormat::Json)) .unwrap(); c } #[test] fn test_file() { let c = make(); // Deserialize the entire file as single struct let s: Settings = c.try_into().unwrap(); assert!(s.debug.approx_eq_ulps(&1.0, 2)); assert_eq!(s.production, Some("false".to_string())); assert_eq!(s.place.name, "Torre di Pisa"); assert!(s.place.longitude.approx_eq_ulps(&43.7224985, 2)); assert!(s.place.latitude.approx_eq_ulps(&10.3970522, 2)); assert_eq!(s.place.favorite, false); assert_eq!(s.place.reviews, 3866); assert_eq!(s.place.rating, Some(4.5)); assert_eq!(s.place.telephone, None); assert_eq!(s.elements.len(), 10); assert_eq!(s.elements[3], "4".to_string()); assert_eq!( s.place.creator["name"].clone().into_str().unwrap(), "John Smith".to_string() ); } #[test] fn test_error_parse() { let mut c = Config::default(); let res = c.merge(File::new("tests/Settings-invalid", FileFormat::Json)); let path_with_extension: PathBuf = ["tests", "Settings-invalid.json"].iter().collect(); assert!(res.is_err()); assert_eq!( res.unwrap_err().to_string(), format!( "expected `:` at line 4 column 1 in {}", path_with_extension.display() ) ); } config-0.11.0/tests/file_toml.rs000064400000000000000000000044370000000000000146170ustar 00000000000000#![cfg(feature = "toml")] extern crate config; extern crate float_cmp; extern crate serde; #[macro_use] extern crate serde_derive; use config::*; use float_cmp::ApproxEqUlps; use std::collections::HashMap; use std::path::PathBuf; #[derive(Debug, Deserialize)] struct Place { number: PlaceNumber, name: String, longitude: f64, latitude: f64, favorite: bool, telephone: Option, reviews: u64, creator: HashMap, rating: Option, } #[derive(Debug, Deserialize, PartialEq)] struct PlaceNumber(u8); #[derive(Debug, Deserialize, PartialEq)] struct AsciiCode(i8); #[derive(Debug, Deserialize)] struct Settings { debug: f64, production: Option, code: AsciiCode, place: Place, #[serde(rename = "arr")] elements: Vec, } fn make() -> Config { let mut c = Config::default(); c.merge(File::new("tests/Settings", FileFormat::Toml)) .unwrap(); c } #[test] fn test_file() { let c = make(); // Deserialize the entire file as single struct let s: Settings = c.try_into().unwrap(); assert!(s.debug.approx_eq_ulps(&1.0, 2)); assert_eq!(s.production, Some("false".to_string())); assert_eq!(s.code, AsciiCode(53)); assert_eq!(s.place.number, PlaceNumber(1)); assert_eq!(s.place.name, "Torre di Pisa"); assert!(s.place.longitude.approx_eq_ulps(&43.7224985, 2)); assert!(s.place.latitude.approx_eq_ulps(&10.3970522, 2)); assert_eq!(s.place.favorite, false); assert_eq!(s.place.reviews, 3866); assert_eq!(s.place.rating, Some(4.5)); assert_eq!(s.place.telephone, None); assert_eq!(s.elements.len(), 10); assert_eq!(s.elements[3], "4".to_string()); assert_eq!( s.place.creator["name"].clone().into_str().unwrap(), "John Smith".to_string() ); } #[test] fn test_error_parse() { let mut c = Config::default(); let res = c.merge(File::new("tests/Settings-invalid", FileFormat::Toml)); let path_with_extension: PathBuf = ["tests", "Settings-invalid.toml"].iter().collect(); assert!(res.is_err()); assert_eq!( res.unwrap_err().to_string(), format!( "invalid TOML value, did you mean to use a quoted string? at line 2 column 9 in {}", path_with_extension.display() ) ); } config-0.11.0/tests/file_yaml.rs000064400000000000000000000040430000000000000145770ustar 00000000000000#![cfg(feature = "yaml")] extern crate config; extern crate float_cmp; extern crate serde; #[macro_use] extern crate serde_derive; use config::*; use float_cmp::ApproxEqUlps; use std::collections::HashMap; use std::path::PathBuf; #[derive(Debug, Deserialize)] struct Place { name: String, longitude: f64, latitude: f64, favorite: bool, telephone: Option, reviews: u64, creator: HashMap, rating: Option, } #[derive(Debug, Deserialize)] struct Settings { debug: f64, production: Option, place: Place, #[serde(rename = "arr")] elements: Vec, } fn make() -> Config { let mut c = Config::default(); c.merge(File::new("tests/Settings", FileFormat::Yaml)) .unwrap(); c } #[test] fn test_file() { let c = make(); // Deserialize the entire file as single struct let s: Settings = c.try_into().unwrap(); assert!(s.debug.approx_eq_ulps(&1.0, 2)); assert_eq!(s.production, Some("false".to_string())); assert_eq!(s.place.name, "Torre di Pisa"); assert!(s.place.longitude.approx_eq_ulps(&43.7224985, 2)); assert!(s.place.latitude.approx_eq_ulps(&10.3970522, 2)); assert_eq!(s.place.favorite, false); assert_eq!(s.place.reviews, 3866); assert_eq!(s.place.rating, Some(4.5)); assert_eq!(s.place.telephone, None); assert_eq!(s.elements.len(), 10); assert_eq!(s.elements[3], "4".to_string()); assert_eq!( s.place.creator["name"].clone().into_str().unwrap(), "John Smith".to_string() ); } #[test] fn test_error_parse() { let mut c = Config::default(); let res = c.merge(File::new("tests/Settings-invalid", FileFormat::Yaml)); let path_with_extension: PathBuf = ["tests", "Settings-invalid.yaml"].iter().collect(); assert!(res.is_err()); assert_eq!( res.unwrap_err().to_string(), format!( "while parsing a block mapping, did not find expected key at \ line 2 column 1 in {}", path_with_extension.display() ) ); } config-0.11.0/tests/get.rs000064400000000000000000000150660000000000000134240ustar 00000000000000#![cfg(feature = "toml")] extern crate config; extern crate float_cmp; extern crate serde; #[macro_use] extern crate serde_derive; use config::*; use float_cmp::ApproxEqUlps; use std::collections::{HashMap, HashSet}; #[derive(Debug, Deserialize)] struct Place { name: String, longitude: f64, latitude: f64, favorite: bool, telephone: Option, reviews: u64, rating: Option, } #[derive(Debug, Deserialize)] struct Settings { debug: f64, production: Option, place: Place, } fn make() -> Config { let mut c = Config::default(); c.merge(File::new("tests/Settings", FileFormat::Toml)) .unwrap(); c } #[test] fn test_not_found() { let c = make(); let res = c.get::("not_found"); assert!(res.is_err()); assert_eq!( res.unwrap_err().to_string(), "configuration property \"not_found\" not found".to_string() ); } #[test] fn test_scalar() { let c = make(); assert_eq!(c.get("debug").ok(), Some(true)); assert_eq!(c.get("production").ok(), Some(false)); } #[test] fn test_scalar_type_loose() { let c = make(); assert_eq!(c.get("debug").ok(), Some(true)); assert_eq!(c.get("debug").ok(), Some("true".to_string())); assert_eq!(c.get("debug").ok(), Some(1)); assert_eq!(c.get("debug").ok(), Some(1.0)); assert_eq!(c.get("debug_s").ok(), Some(true)); assert_eq!(c.get("debug_s").ok(), Some("true".to_string())); assert_eq!(c.get("debug_s").ok(), Some(1)); assert_eq!(c.get("debug_s").ok(), Some(1.0)); assert_eq!(c.get("production").ok(), Some(false)); assert_eq!(c.get("production").ok(), Some("false".to_string())); assert_eq!(c.get("production").ok(), Some(0)); assert_eq!(c.get("production").ok(), Some(0.0)); assert_eq!(c.get("production_s").ok(), Some(false)); assert_eq!(c.get("production_s").ok(), Some("false".to_string())); assert_eq!(c.get("production_s").ok(), Some(0)); assert_eq!(c.get("production_s").ok(), Some(0.0)); } #[test] fn test_get_scalar_path() { let c = make(); assert_eq!(c.get("place.favorite").ok(), Some(false)); assert_eq!( c.get("place.creator.name").ok(), Some("John Smith".to_string()) ); } #[test] fn test_get_scalar_path_subscript() { let c = make(); assert_eq!(c.get("arr[2]").ok(), Some(3)); assert_eq!(c.get("items[0].name").ok(), Some("1".to_string())); assert_eq!(c.get("items[1].name").ok(), Some("2".to_string())); assert_eq!(c.get("items[-1].name").ok(), Some("2".to_string())); assert_eq!(c.get("items[-2].name").ok(), Some("1".to_string())); } #[test] fn test_map() { let c = make(); let m: HashMap = c.get("place").unwrap(); assert_eq!(m.len(), 8); assert_eq!( m["name"].clone().into_str().unwrap(), "Torre di Pisa".to_string() ); assert_eq!(m["reviews"].clone().into_int().unwrap(), 3866); } #[test] fn test_map_str() { let c = make(); let m: HashMap = c.get("place.creator").unwrap(); assert_eq!(m.len(), 1); assert_eq!(m["name"], "John Smith".to_string()); } #[test] fn test_map_struct() { #[derive(Debug, Deserialize)] struct Settings { place: HashMap, } let c = make(); let s: Settings = c.try_into().unwrap(); assert_eq!(s.place.len(), 8); assert_eq!( s.place["name"].clone().into_str().unwrap(), "Torre di Pisa".to_string() ); assert_eq!(s.place["reviews"].clone().into_int().unwrap(), 3866); } #[test] fn test_file_struct() { let c = make(); // Deserialize the entire file as single struct let s: Settings = c.try_into().unwrap(); assert!(s.debug.approx_eq_ulps(&1.0, 2)); assert_eq!(s.production, Some("false".to_string())); assert_eq!(s.place.name, "Torre di Pisa"); assert!(s.place.longitude.approx_eq_ulps(&43.7224985, 2)); assert!(s.place.latitude.approx_eq_ulps(&10.3970522, 2)); assert_eq!(s.place.favorite, false); assert_eq!(s.place.reviews, 3866); assert_eq!(s.place.rating, Some(4.5)); assert_eq!(s.place.telephone, None); } #[test] fn test_scalar_struct() { let c = make(); // Deserialize a scalar struct that has lots of different // data types let p: Place = c.get("place").unwrap(); assert_eq!(p.name, "Torre di Pisa"); assert!(p.longitude.approx_eq_ulps(&43.7224985, 2)); assert!(p.latitude.approx_eq_ulps(&10.3970522, 2)); assert_eq!(p.favorite, false); assert_eq!(p.reviews, 3866); assert_eq!(p.rating, Some(4.5)); assert_eq!(p.telephone, None); } #[test] fn test_array_scalar() { let c = make(); let arr: Vec = c.get("arr").unwrap(); assert_eq!(arr.len(), 10); assert_eq!(arr[3], 4); } #[test] fn test_struct_array() { #[derive(Debug, Deserialize)] struct Settings { #[serde(rename = "arr")] elements: Vec, } let c = make(); let s: Settings = c.try_into().unwrap(); assert_eq!(s.elements.len(), 10); assert_eq!(s.elements[3], "4".to_string()); } #[test] fn test_enum() { #[derive(Debug, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] enum Diode { Off, Brightness(i32), Blinking(i32, i32), Pattern { name: String, inifinite: bool }, } #[derive(Debug, Deserialize)] struct Settings { diodes: HashMap, } let c = make(); let s: Settings = c.try_into().unwrap(); assert_eq!(s.diodes["green"], Diode::Off); assert_eq!(s.diodes["red"], Diode::Brightness(100)); assert_eq!(s.diodes["blue"], Diode::Blinking(300, 700)); assert_eq!( s.diodes["white"], Diode::Pattern { name: "christmas".into(), inifinite: true, } ); } #[test] fn test_enum_key() { #[derive(Debug, Deserialize, PartialEq, Eq, Hash)] #[serde(rename_all = "lowercase")] enum Quark { Up, Down, Strange, Charm, Bottom, Top, } #[derive(Debug, Deserialize)] struct Settings { proton: HashMap, // Just to make sure that set keys work too. quarks: HashSet, } let c = make(); let s: Settings = c.try_into().unwrap(); assert_eq!(s.proton[&Quark::Up], 2); assert_eq!(s.quarks.len(), 6); } #[test] fn test_int_key() { #[derive(Debug, Deserialize, PartialEq)] struct Settings { divisors: HashMap, } let c = make(); let s: Settings = c.try_into().unwrap(); assert_eq!(s.divisors[&4], 3); assert_eq!(s.divisors.len(), 4); } config-0.11.0/tests/merge.rs000064400000000000000000000021000000000000000137250ustar 00000000000000#![cfg(feature = "toml")] extern crate config; use config::*; fn make() -> Config { let mut c = Config::default(); c.merge(File::new("tests/Settings", FileFormat::Toml)) .unwrap(); c.merge(File::new("tests/Settings-production", FileFormat::Toml)) .unwrap(); c } #[test] fn test_merge() { let c = make(); assert_eq!(c.get("debug").ok(), Some(false)); assert_eq!(c.get("production").ok(), Some(true)); assert_eq!( c.get("place.creator.name").ok(), Some("Somebody New".to_string()) ); assert_eq!(c.get("place.rating").ok(), Some(4.9)); } #[test] fn test_merge_whole_config() { let mut c1 = Config::default(); let mut c2 = Config::default(); c1.set("x", 10).unwrap(); c2.set("y", 25).unwrap(); assert_eq!(c1.get("x").ok(), Some(10)); assert_eq!(c2.get::<()>("x").ok(), None); assert_eq!(c2.get("y").ok(), Some(25)); assert_eq!(c1.get::<()>("y").ok(), None); c1.merge(c2).unwrap(); assert_eq!(c1.get("x").ok(), Some(10)); assert_eq!(c1.get("y").ok(), Some(25)); } config-0.11.0/tests/set.rs000064400000000000000000000044700000000000000134350ustar 00000000000000extern crate config; use config::*; #[test] fn test_set_scalar() { let mut c = Config::default(); c.set("value", true).unwrap(); assert_eq!(c.get("value").ok(), Some(true)); } #[cfg(feature = "toml")] #[test] fn test_set_scalar_default() { let mut c = Config::default(); c.merge(File::new("tests/Settings", FileFormat::Toml)) .unwrap(); c.set_default("debug", false).unwrap(); c.set_default("staging", false).unwrap(); assert_eq!(c.get("debug").ok(), Some(true)); assert_eq!(c.get("staging").ok(), Some(false)); } #[cfg(feature = "toml")] #[test] fn test_set_scalar_path() { let mut c = Config::default(); c.set("first.second.third", true).unwrap(); assert_eq!(c.get("first.second.third").ok(), Some(true)); c.merge(File::new("tests/Settings", FileFormat::Toml)) .unwrap(); c.set_default("place.favorite", true).unwrap(); c.set_default("place.blocked", true).unwrap(); assert_eq!(c.get("place.favorite").ok(), Some(false)); assert_eq!(c.get("place.blocked").ok(), Some(true)); } #[cfg(feature = "toml")] #[test] fn test_set_arr_path() { let mut c = Config::default(); c.set("items[0].name", "Ivan").unwrap(); assert_eq!(c.get("items[0].name").ok(), Some("Ivan".to_string())); c.set("data[0].things[1].name", "foo").unwrap(); c.set("data[0].things[1].value", 42).unwrap(); c.set("data[1]", 0).unwrap(); assert_eq!( c.get("data[0].things[1].name").ok(), Some("foo".to_string()) ); assert_eq!(c.get("data[0].things[1].value").ok(), Some(42)); assert_eq!(c.get("data[1]").ok(), Some(0)); c.merge(File::new("tests/Settings", FileFormat::Toml)) .unwrap(); c.set("items[0].name", "John").unwrap(); assert_eq!(c.get("items[0].name").ok(), Some("John".to_string())); c.set("items[2]", "George").unwrap(); assert_eq!(c.get("items[2]").ok(), Some("George".to_string())); } #[cfg(feature = "toml")] #[test] fn test_set_capital() { let mut c = Config::default(); c.set_default("this", false).unwrap(); c.set("ThAt", true).unwrap(); c.merge(File::from_str("{\"logLevel\": 5}", FileFormat::Json)) .unwrap(); assert_eq!(c.get("this").ok(), Some(false)); assert_eq!(c.get("ThAt").ok(), Some(true)); assert_eq!(c.get("logLevel").ok(), Some(5)); }