├── .github ├── dependabot.yml └── workflows │ ├── audit.yml │ ├── ci.yml │ └── fixup-merge-block.yml ├── .gitignore ├── Cargo.toml ├── LICENSE ├── LICENSE-Apache-2.0 ├── LICENSE-MIT ├── LICENSE-X11 ├── README.md ├── audit.toml ├── examples └── simple.rs └── src ├── lib.rs └── utils.rs /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "cargo" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "monthly" 12 | -------------------------------------------------------------------------------- /.github/workflows/audit.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | pull_request: 4 | types: [opened, reopened] 5 | schedule: 6 | - cron: '00 15 * * 1' 7 | 8 | name: Audit 9 | 10 | jobs: 11 | check: 12 | name: audit 13 | runs-on: ubuntu-latest 14 | steps: 15 | - name: Checkout sources 16 | uses: actions/checkout@v4 17 | 18 | - name: Install toolchain 19 | uses: dtolnay/rust-toolchain@master 20 | with: 21 | toolchain: stable 22 | 23 | - name: Setup Cache 24 | uses: actions/cache@v4 25 | with: 26 | path: | 27 | ~/.cargo/bin/ 28 | ~/.cargo/registry/index/ 29 | ~/.cargo/registry/cache/ 30 | ~/.cargo/git/db/ 31 | ~/.cargo/.crates.toml 32 | ~/.cargo/.crates2.json 33 | target/ 34 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}-audit 35 | 36 | - name: Install Cargo Audit 37 | run: cargo install cargo-audit --locked 38 | shell: bash 39 | 40 | - name: Run Audit 41 | run: cargo audit 42 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | 3 | name: CI 4 | 5 | jobs: 6 | check: 7 | name: Check 8 | runs-on: ${{ matrix.os }} 9 | strategy: 10 | matrix: 11 | rust: 12 | - stable 13 | - beta 14 | - nightly 15 | os: 16 | - ubuntu-latest 17 | - macOS-latest 18 | - windows-latest 19 | steps: 20 | - name: Checkout sources 21 | uses: actions/checkout@v4 22 | 23 | - name: Install Rust 24 | uses: dtolnay/rust-toolchain@master 25 | with: 26 | toolchain: ${{ matrix.rust }} 27 | 28 | - name: Setup Cache 29 | uses: actions/cache@v4 30 | with: 31 | path: | 32 | ~/.cargo/bin/ 33 | ~/.cargo/registry/index/ 34 | ~/.cargo/registry/cache/ 35 | ~/.cargo/git/db/ 36 | target/ 37 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}-${{ matrix.rust }} 38 | 39 | - name: Run cargo check 40 | run: cargo check 41 | shell: bash 42 | 43 | test: 44 | needs: [check] 45 | name: Test Suite 46 | runs-on: ${{ matrix.os }} 47 | strategy: 48 | matrix: 49 | rust: 50 | - stable 51 | - beta 52 | - nightly 53 | os: 54 | - ubuntu-latest 55 | - macOS-latest 56 | - windows-latest 57 | steps: 58 | - name: Checkout sources 59 | uses: actions/checkout@v4 60 | 61 | - name: Install Rust 62 | uses: dtolnay/rust-toolchain@master 63 | with: 64 | toolchain: ${{ matrix.rust }} 65 | 66 | - name: Setup Cache 67 | uses: actions/cache@v4 68 | with: 69 | path: | 70 | ~/.cargo/bin/ 71 | ~/.cargo/registry/index/ 72 | ~/.cargo/registry/cache/ 73 | ~/.cargo/git/db/ 74 | target/ 75 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}-${{ matrix.rust }} 76 | 77 | - name: Run cargo test 78 | run: cargo test 79 | shell: bash 80 | 81 | clippy: 82 | needs: [check] 83 | name: Clippy 84 | runs-on: ubuntu-latest 85 | strategy: 86 | matrix: 87 | rust: 88 | - stable 89 | - beta 90 | - nightly 91 | steps: 92 | - name: Checkout sources 93 | uses: actions/checkout@v4 94 | 95 | - name: Install Rust 96 | uses: dtolnay/rust-toolchain@master 97 | with: 98 | toolchain: ${{ matrix.rust }} 99 | components: clippy 100 | 101 | - name: Setup Cache 102 | uses: actions/cache@v4 103 | with: 104 | path: | 105 | ~/.cargo/bin/ 106 | ~/.cargo/registry/index/ 107 | ~/.cargo/registry/cache/ 108 | ~/.cargo/git/db/ 109 | target/ 110 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}-${{ matrix.rust }} 111 | 112 | - name: Run cargo clippy 113 | run: cargo clippy -- -D warnings 114 | shell: bash 115 | -------------------------------------------------------------------------------- /.github/workflows/fixup-merge-block.yml: -------------------------------------------------------------------------------- 1 | on: [pull_request] 2 | 3 | name: Git Checks 4 | 5 | jobs: 6 | block-fixup: 7 | runs-on: ubuntu-latest 8 | 9 | steps: 10 | - uses: actions/checkout@v2.0.0 11 | - name: Block Fixup Commit Merge 12 | uses: 13rac1/block-fixup-merge-action@v2.0.0 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | 12 | /target 13 | **/*.rs.bk 14 | Cargo.lock 15 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "confy" 3 | version = "1.0.0" 4 | authors = ["Katharina Fey "] 5 | description = "Boilerplate-free configuration management" 6 | license = "MIT/X11 OR Apache-2.0" 7 | documentation = "https://docs.rs/confy" 8 | repository = "https://github.com/rust-cli/confy" 9 | readme = "README.md" 10 | edition = "2024" 11 | 12 | [dependencies] 13 | ron = { version = "0.10.1", optional = true } 14 | directories = "6" 15 | serde = "^1.0" 16 | serde_yaml = { version = "0.9", optional = true } 17 | thiserror = "2.0" 18 | basic-toml = { version = "0.1.10", optional = true } 19 | toml = { version = "0.8", optional = true } 20 | 21 | [features] 22 | default = ["toml_conf"] 23 | toml_conf = ["toml"] 24 | basic_toml_conf = ["basic-toml"] 25 | yaml_conf = ["serde_yaml"] 26 | ron_conf = ["ron"] 27 | 28 | [[example]] 29 | name = "simple" 30 | 31 | [dev-dependencies] 32 | serde_derive = "^1.0" 33 | tempfile = "3.16.0" 34 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT OR X11 OR Apache-2.0+ 2 | -------------------------------------------------------------------------------- /LICENSE-Apache-2.0: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2024 Rust CLI Working Group 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | 204 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2024 Rust CLI Working Group 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /LICENSE-X11: -------------------------------------------------------------------------------- 1 | Copyright (C) 2024 Rust CLI Working Group 2 | 3 | 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: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | 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 X CONSORTIUM 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. 8 | 9 | Except as contained in this notice, the name of Rust CLI Working Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Rust CLI Working Group. 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # confy 2 | 3 | [![crates.io](https://img.shields.io/crates/v/confy)](https://crates.io/crates/confy) 4 | [![docs.rs](https://img.shields.io/docsrs/confy)](https://docs.rs/confy/) 5 | [![Discord](https://img.shields.io/badge/chat-Discord-informational)](https://discord.gg/dwq4Zme) 6 | 7 | Zero-boilerplate configuration management. 8 | 9 | Focus on storing the right data, instead of worrying about how or where to store it. 10 | 11 | ```rust 12 | use serde_derive::{Serialize, Deserialize}; 13 | 14 | #[derive(Default, Debug, Serialize, Deserialize)] 15 | struct MyConfig { 16 | version: u8, 17 | api_key: String, 18 | } 19 | 20 | fn main() -> Result<(), Box> { 21 | let cfg: MyConfig = confy::load("my-app-name", None)?; 22 | dbg!(cfg); 23 | Ok(()) 24 | } 25 | ``` 26 | 27 | ## Confy's feature flags 28 | 29 | `confy` can be used with either `TOML`, `YAML`, or `RON` files. 30 | `TOML` is the default language used with `confy` but any of the other languages can be used by enabling them with feature flags as shown below. 31 | 32 | Note: you can only use __one__ of these features at a time, so in order to use either of the optional features you have to disable default features. 33 | 34 | ### Using YAML 35 | 36 | To use `YAML` files with `confy` you have to make sure you have enabled the `yaml_conf` feature and disabled both `toml_conf` and `ron_conf`. 37 | 38 | Enable the feature in `Cargo.toml`: 39 | 40 | ```toml 41 | [dependencies.confy] 42 | features = ["yaml_conf"] 43 | default-features = false 44 | ``` 45 | 46 | ### Using RON 47 | 48 | For using `RON` files with `confy` you have to make sure you have enabled the `ron_conf` feature and disabled both `toml_conf` and `yaml_conf`. 49 | 50 | Enable the feature in `Cargo.toml`: 51 | 52 | ```toml 53 | [dependencies.confy] 54 | features = ["ron_conf"] 55 | default-features = false 56 | ``` 57 | 58 | ## Changing Error Messages 59 | 60 | Information about adding context to error messages can be found at [Providing Context](https://rust-cli.github.io/book/tutorial/errors.html#providing-context) 61 | 62 | ## Config File Location 63 | 64 | `confy` uses [ProjectDirs](https://github.com/dirs-dev/directories-rs?tab=readme-ov-file#projectdirs) to store your configuration files, the common locations for those are in the `config_dir` section, below are the common OS paths: 65 | 66 | | Linux | macOS | Windows | 67 | | --- | --- | --- | 68 | | `$XDG_CONFIG_HOME`/`` or `$HOME`/.config/`` | `$HOME`/Library/Application Support/`` | `{FOLDERID_RoamingAppData}`/``/config | 69 | 70 | Where the `` will be `rs.$MY_APP_NAME`. 71 | 72 | ## Breaking changes 73 | 74 | ### Version 0.6.0 75 | 76 | In this version we bumped several dependencies which have had changes with some of the default (de)serialization process: 77 | 78 | * `serde_yaml` v0.8 -> v0.9: [v0.9 release notes](https://github.com/dtolnay/serde-yaml/releases/tag/0.9.0). There were several breaking changes to `v0.9.0` and are listed in this release tag. Especially cases where previously numbers were parsed and now return `String`. See the release notes for more details. 79 | * `toml` v0.5 -> v0.8: [v0.8 CHANGELOG](https://github.com/toml-rs/toml/blob/main/crates/toml/CHANGELOG.md#compatibility-1). Breaking change to how tuple variants work in `toml`, from the notes: "Serialization and deserialization of tuple variants has changed from being an array to being a table with the key being the variant name and the value being the array". 80 | 81 | ### Version 0.5.0 82 | 83 | * The base functions `load` and `store` have been added an optional parameter in the event multiples configurations are needed, or ones with different filename. 84 | * The default configuration file is now named "default-config" instead of using the application's name. Put the second argument of `load` and `store` to be the same of the first one to keep the previous configuration file. 85 | * It is now possible to save the configuration as `toml` or as `YAML`. The configuration's file name's extension depends on the format used. 86 | 87 | ### Version 0.4.0 88 | 89 | Starting with version 0.4.0 the configuration file are stored in the expected place for your system. See the [`directories`] crates for more information. 90 | Before version 0.4.0, the configuration file was written in the current directory. 91 | 92 | [`directories`]: https://crates.io/crates/directories 93 | 94 | ## License 95 | 96 | This work is triple-licensed under MIT, MIT/X11, or the Apache 2.0 (or any later version). 97 | You may choose any one of these three licenses if you use this work. 98 | 99 | `SPDX-License-Identifier: MIT OR X11 OR Apache-2.0+` 100 | -------------------------------------------------------------------------------- /audit.toml: -------------------------------------------------------------------------------- 1 | [advisories] 2 | ignore = [] 3 | informational_warnings = ["unmaintained"] # warn for categories of informational advisories 4 | severity_threshold = "low" # CVSS severity ("none", "low", "medium", "high", "critical") 5 | 6 | [output] 7 | deny = ["unmaintained"] # exit on error if unmaintained dependencies are found 8 | format = "terminal" # "terminal" (human readable report) or "json" 9 | quiet = false # Only print information on error 10 | show_tree = true # Show inverse dependency trees along with advisories (default: true) -------------------------------------------------------------------------------- /examples/simple.rs: -------------------------------------------------------------------------------- 1 | //! The most simplest examples of how to use confy 2 | 3 | extern crate confy; 4 | 5 | #[macro_use] 6 | extern crate serde_derive; 7 | 8 | use std::io::Read; 9 | 10 | #[derive(Debug, Serialize, Deserialize)] 11 | struct ConfyConfig { 12 | name: String, 13 | comfy: bool, 14 | foo: i64, 15 | } 16 | 17 | impl Default for ConfyConfig { 18 | fn default() -> Self { 19 | ConfyConfig { 20 | name: "Unknown".to_string(), 21 | comfy: true, 22 | foo: 42, 23 | } 24 | } 25 | } 26 | 27 | fn main() -> Result<(), confy::ConfyError> { 28 | let cfg: ConfyConfig = confy::load("confy_simple_app", None)?; 29 | let file = confy::get_configuration_file_path("confy_simple_app", None)?; 30 | println!("The configuration file path is: {:#?}", file); 31 | println!("The configuration is:"); 32 | println!("{:#?}", cfg); 33 | println!("The wrote toml file content is:"); 34 | let mut content = String::new(); 35 | std::fs::File::open(&file) 36 | .expect("Failed to open toml configuration file.") 37 | .read_to_string(&mut content) 38 | .expect("Failed to read toml configuration file."); 39 | println!("{}", content); 40 | let cfg = ConfyConfig { 41 | name: "Test".to_string(), 42 | ..cfg 43 | }; 44 | confy::store("confy_simple_app",None, &cfg)?; 45 | println!("The updated toml file content is:"); 46 | let mut content = String::new(); 47 | std::fs::File::open(&file) 48 | .expect("Failed to open toml configuration file.") 49 | .read_to_string(&mut content) 50 | .expect("Failed to read toml configuration file."); 51 | println!("{}", content); 52 | let _cfg = ConfyConfig { 53 | name: "Test".to_string(), 54 | ..cfg 55 | }; 56 | std::fs::remove_dir_all(file.parent().unwrap()) 57 | .expect("Failed to remove directory"); 58 | Ok(()) 59 | } 60 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Zero-boilerplate configuration management 2 | //! 3 | //! ## Why? 4 | //! 5 | //! There are a lot of different requirements when 6 | //! selecting, loading and writing a config, 7 | //! depending on the operating system and other 8 | //! environment factors. 9 | //! 10 | //! In many applications this burden is left to you, 11 | //! the developer of an application, to figure out 12 | //! where to place the configuration files. 13 | //! 14 | //! This is where `confy` comes in. 15 | //! 16 | //! ## Idea 17 | //! 18 | //! `confy` takes care of figuring out operating system 19 | //! specific and environment paths before reading and 20 | //! writing a configuration. 21 | //! 22 | //! It gives you easy access to a configuration file 23 | //! which is mirrored into a Rust `struct` via [serde]. 24 | //! This way you only need to worry about the layout of 25 | //! your configuration, not where and how to store it. 26 | //! 27 | //! [serde]: https://docs.rs/serde 28 | //! 29 | //! `confy` uses the [`Default`] trait in Rust to automatically 30 | //! create a new configuration, if none is available to read 31 | //! from yet. 32 | //! This means that you can simply assume your application 33 | //! to have a configuration, which will be created with 34 | //! default values of your choosing, without requiring 35 | //! any special logic to handle creation. 36 | //! 37 | //! [`Default`]: https://doc.rust-lang.org/std/default/trait.Default.html 38 | //! 39 | //! ```rust,no_run 40 | //! use serde_derive::{Serialize, Deserialize}; 41 | //! 42 | //! #[derive(Serialize, Deserialize)] 43 | //! struct MyConfig { 44 | //! version: u8, 45 | //! api_key: String, 46 | //! } 47 | //! 48 | //! /// `MyConfig` implements `Default` 49 | //! impl ::std::default::Default for MyConfig { 50 | //! fn default() -> Self { Self { version: 0, api_key: "".into() } } 51 | //! } 52 | //! 53 | //! fn main() -> Result<(), confy::ConfyError> { 54 | //! let cfg: MyConfig = confy::load("my-app-name", None)?; 55 | //! Ok(()) 56 | //! } 57 | //! ``` 58 | //! 59 | //! Serde is a required dependency, and can be added with either the `serde_derive` crate or `serde` crate with feature derive as shown below 60 | //!```toml,no_run 61 | //![dependencies] 62 | //!serde = { version = "1.0.152", features = ["derive"] } # <- Only one serde version needed (serde or serde_derive) 63 | //!serde_derive = "1.0.152" # <- Only one serde version needed (serde or serde_derive) 64 | //!confy = "^0.6" 65 | //!``` 66 | //! Updating the configuration is then done via the [`store`] function. 67 | //! 68 | //! [`store`]: fn.store.html 69 | //! 70 | //! ## Features 71 | //! 72 | //! Exactly **one** of the features has to be enabled from the following table. 73 | //! 74 | //! ### Tip 75 | //! to add this crate to your project with the default, toml config do the following: `cargo add confy`, otherwise do something like: `cargo add confy --no-default-features --features yaml_conf`, for more info, see [cargo docs on features] 76 | //! 77 | //! [cargo docs on features]: https://docs.rust-lang.org/cargo/reference/resolver.html#features 78 | //! 79 | //! feature | file format | description 80 | //! ------- | ----------- | ----------- 81 | //! **default**: `toml_conf` | [toml] | considered a reasonable default, uses the standard-compliant [`toml` crate] 82 | //! `yaml_conf` | [yaml] | uses the [`serde_yaml` crate] 83 | //! `ron_conf` | [ron] | Rusty Object Notation, uses the [`ron` crate] 84 | //! `basic_toml_conf` | [toml] | alternative to the default `toml_conf`, instead of using the [`toml` crate], the [`basic_toml` crate] is used, in order to cut down on the number of dependencies, speed up compilation and shrink binary size. **_DISCLAIMER_**: this crate is **not** standard compliant, **nor** maintained, otherwise should work fine in most situations. 85 | //! 86 | //! [toml]: https://toml.io 87 | //! [`toml` crate]: https://docs.rs/toml 88 | //! [yaml]: https://yaml.org 89 | //! [`serde_yaml` crate]: https://docs.rs/serde_yaml 90 | //! [ron]: https://docs.rs/ron 91 | //! [`ron` crate]: https://docs.rs/ron 92 | //! [`basic_toml` crate]: https://docs.rs/basic_toml 93 | 94 | mod utils; 95 | use utils::*; 96 | 97 | use directories::ProjectDirs; 98 | use serde::{de::DeserializeOwned, Serialize}; 99 | use std::fs::{self, File, OpenOptions, Permissions}; 100 | use std::io::{ErrorKind::NotFound, Write}; 101 | use std::path::{Path, PathBuf}; 102 | use thiserror::Error; 103 | 104 | #[cfg(feature = "toml_conf")] 105 | use toml::{ 106 | de::Error as TomlDeErr, from_str as toml_from_str, ser::Error as TomlSerErr, 107 | to_string_pretty as toml_to_string_pretty, 108 | }; 109 | 110 | #[cfg(feature = "basic_toml_conf")] 111 | use basic_toml::{ 112 | from_str as toml_from_str, to_string as toml_to_string_pretty, Error as TomlDeErr, 113 | Error as TomlSerErr, 114 | }; 115 | 116 | #[cfg(not(any( 117 | feature = "toml_conf", 118 | feature = "basic_toml_conf", 119 | feature = "yaml_conf", 120 | feature = "ron_conf" 121 | )))] 122 | compile_error!( 123 | "Exactly one config language feature must be enabled to use \ 124 | confy. Please enable one of either the `toml_conf`, `yaml_conf`, \ 125 | , `ron_conf` or `toml_basic_conf` features." 126 | ); 127 | 128 | #[cfg(any( 129 | all(feature = "toml_conf", feature = "basic_toml_conf"), 130 | all( 131 | any(feature = "toml_conf", feature = "basic_toml_conf"), 132 | feature = "yaml_conf" 133 | ), 134 | all( 135 | any(feature = "toml_conf", feature = "basic_toml_conf"), 136 | feature = "ron_conf" 137 | ), 138 | all(feature = "ron_conf", feature = "yaml_conf"), 139 | ))] 140 | compile_error!( 141 | "Exactly one config language feature must be enabled to compile \ 142 | confy. Please disable one of either the `toml_conf`, `basic_toml_conf`, `yaml_conf`, or `ron_conf` features. \ 143 | NOTE: `toml_conf` is a default feature, so disabling it might mean switching off \ 144 | default features for confy in your Cargo.toml" 145 | ); 146 | 147 | #[cfg(any(feature = "toml_conf", feature = "basic_toml_conf"))] 148 | const EXTENSION: &str = "toml"; 149 | 150 | #[cfg(feature = "yaml_conf")] 151 | const EXTENSION: &str = "yml"; 152 | 153 | #[cfg(feature = "ron_conf")] 154 | const EXTENSION: &str = "ron"; 155 | 156 | /// The errors the confy crate can encounter. 157 | #[derive(Debug, Error)] 158 | pub enum ConfyError { 159 | #[cfg(any(feature = "toml_conf", feature = "basic_toml_conf"))] 160 | #[error("Bad TOML data")] 161 | BadTomlData(#[source] TomlDeErr), 162 | 163 | #[cfg(feature = "yaml_conf")] 164 | #[error("Bad YAML data")] 165 | BadYamlData(#[source] serde_yaml::Error), 166 | 167 | #[cfg(feature = "ron_conf")] 168 | #[error("Bad RON data")] 169 | BadRonData(#[source] ron::error::SpannedError), 170 | 171 | #[error("Failed to create directory")] 172 | DirectoryCreationFailed(#[source] std::io::Error), 173 | 174 | #[error("Failed to load configuration file")] 175 | GeneralLoadError(#[source] std::io::Error), 176 | 177 | #[error("Bad configuration directory: {0}")] 178 | BadConfigDirectory(String), 179 | 180 | #[cfg(any(feature = "toml_conf", feature = "basic_toml_conf"))] 181 | #[error("Failed to serialize configuration data into TOML")] 182 | SerializeTomlError(#[source] TomlSerErr), 183 | 184 | #[cfg(feature = "yaml_conf")] 185 | #[error("Failed to serialize configuration data into YAML")] 186 | SerializeYamlError(#[source] serde_yaml::Error), 187 | 188 | #[cfg(feature = "ron_conf")] 189 | #[error("Failed to serialize configuration data into RON")] 190 | SerializeRonError(#[source] ron::error::Error), 191 | 192 | #[error("Failed to write configuration file")] 193 | WriteConfigurationFileError(#[source] std::io::Error), 194 | 195 | #[error("Failed to read configuration file")] 196 | ReadConfigurationFileError(#[source] std::io::Error), 197 | 198 | #[error("Failed to open configuration file")] 199 | OpenConfigurationFileError(#[source] std::io::Error), 200 | 201 | #[error("Failed to set configuration file permissions")] 202 | SetPermissionsFileError(#[source] std::io::Error), 203 | } 204 | 205 | /// Load an application configuration from disk 206 | /// 207 | /// A new configuration file is created with default values if none 208 | /// exists. 209 | /// 210 | /// Errors that are returned from this function are I/O related, 211 | /// for example if the writing of the new configuration fails 212 | /// or `confy` encounters an operating system or environment 213 | /// that it does not support. 214 | /// 215 | /// **Note:** The type of configuration needs to be declared in some way 216 | /// that is inferable by the compiler. Also note that your 217 | /// configuration needs to implement `Default`. 218 | /// 219 | /// ```rust,no_run 220 | /// # use confy::ConfyError; 221 | /// # use serde_derive::{Serialize, Deserialize}; 222 | /// # fn main() -> Result<(), ConfyError> { 223 | /// #[derive(Default, Serialize, Deserialize)] 224 | /// struct MyConfig {} 225 | /// 226 | /// let cfg: MyConfig = confy::load("my-app-name", None)?; 227 | /// # Ok(()) 228 | /// # } 229 | /// ``` 230 | pub fn load<'a, T: Serialize + DeserializeOwned + Default>( 231 | app_name: &str, 232 | config_name: impl Into>, 233 | ) -> Result { 234 | get_configuration_file_path(app_name, config_name).and_then(load_path) 235 | } 236 | 237 | /// Load an application configuration from a specified path. 238 | /// 239 | /// A new configuration file is created with default values if none 240 | /// exists. 241 | /// 242 | /// This is an alternate version of [`load`] that allows the specification of 243 | /// an arbitrary path instead of a system one. For more information on errors 244 | /// and behavior, see [`load`]'s documentation. 245 | /// 246 | /// [`load`]: fn.load.html 247 | pub fn load_path( 248 | path: impl AsRef, 249 | ) -> Result { 250 | match File::open(&path) { 251 | Ok(mut cfg) => { 252 | let cfg_string = cfg 253 | .get_string() 254 | .map_err(ConfyError::ReadConfigurationFileError)?; 255 | 256 | #[cfg(any(feature = "toml_conf", feature = "basic_toml_conf"))] 257 | { 258 | let cfg_data = toml_from_str(&cfg_string); 259 | cfg_data.map_err(ConfyError::BadTomlData) 260 | } 261 | #[cfg(feature = "yaml_conf")] 262 | { 263 | let cfg_data = serde_yaml::from_str(&cfg_string); 264 | cfg_data.map_err(ConfyError::BadYamlData) 265 | } 266 | #[cfg(feature = "ron_conf")] 267 | { 268 | let cfg_data = ron::from_str(&cfg_string); 269 | cfg_data.map_err(ConfyError::BadRonData) 270 | } 271 | } 272 | Err(ref e) if e.kind() == NotFound => { 273 | if let Some(parent) = path.as_ref().parent() { 274 | fs::create_dir_all(parent).map_err(ConfyError::DirectoryCreationFailed)?; 275 | } 276 | let cfg = T::default(); 277 | store_path(path, &cfg)?; 278 | Ok(cfg) 279 | } 280 | Err(e) => Err(ConfyError::GeneralLoadError(e)), 281 | } 282 | } 283 | 284 | /// Load an application configuration from a specified path. 285 | /// 286 | /// A new configuration file is created with `op`'s result if none 287 | /// exists or file content is incorrect. 288 | /// 289 | /// This is an alternate version of [`load`] that allows the specification of 290 | /// an arbitrary path instead of a system one. For more information on errors 291 | /// and behavior, see [`load`]'s documentation. 292 | /// 293 | /// [`load`]: fn.load.html 294 | pub fn load_or_else(path: impl AsRef, op: F) -> Result 295 | where 296 | T: DeserializeOwned + Serialize, 297 | F: FnOnce() -> T, 298 | { 299 | let path_ref = path.as_ref(); 300 | let load_value = || { 301 | let cfg = op(); 302 | if let Some(parent) = path.as_ref().parent() { 303 | fs::create_dir_all(parent).map_err(ConfyError::DirectoryCreationFailed)?; 304 | } 305 | store_path(path_ref, &cfg)?; 306 | Ok(cfg) 307 | }; 308 | 309 | match File::open(path_ref) { 310 | Ok(mut cfg) => { 311 | let mut load_from_file = || { 312 | let cfg_string = cfg 313 | .get_string() 314 | .map_err(ConfyError::ReadConfigurationFileError)?; 315 | 316 | #[cfg(any(feature = "toml_conf", feature = "basic_toml_conf"))] 317 | { 318 | let cfg_data = toml_from_str(&cfg_string); 319 | cfg_data.map_err(ConfyError::BadTomlData) 320 | } 321 | #[cfg(feature = "yaml_conf")] 322 | { 323 | let cfg_data = serde_yaml::from_str(&cfg_string); 324 | cfg_data.map_err(ConfyError::BadYamlData) 325 | } 326 | #[cfg(feature = "ron_conf")] 327 | { 328 | let cfg_data = ron::from_str(&cfg_string); 329 | cfg_data.map_err(ConfyError::BadRonData) 330 | } 331 | }; 332 | load_from_file().or_else(|_| load_value()) 333 | } 334 | Err(ref e) if e.kind() == NotFound => load_value(), 335 | Err(e) => Err(ConfyError::GeneralLoadError(e)), 336 | } 337 | } 338 | 339 | /// Save changes made to a configuration object 340 | /// 341 | /// This function will update a configuration, 342 | /// with the provided values, and create a new one, 343 | /// if none exists. 344 | /// 345 | /// You can also use this function to create a new configuration 346 | /// with different initial values than which are provided 347 | /// by your `Default` trait implementation, or if your 348 | /// configuration structure _can't_ implement `Default`. 349 | /// 350 | /// ```rust,no_run 351 | /// # use serde_derive::{Serialize, Deserialize}; 352 | /// # use confy::ConfyError; 353 | /// # fn main() -> Result<(), ConfyError> { 354 | /// #[derive(Serialize, Deserialize)] 355 | /// struct MyConf {} 356 | /// 357 | /// let my_cfg = MyConf {}; 358 | /// confy::store("my-app-name", None, my_cfg)?; 359 | /// # Ok(()) 360 | /// # } 361 | /// ``` 362 | /// 363 | /// Errors returned are I/O errors related to not being 364 | /// able to write the configuration file or if `confy` 365 | /// encounters an operating system or environment it does 366 | /// not support. 367 | pub fn store<'a, T: Serialize>( 368 | app_name: &str, 369 | config_name: impl Into>, 370 | cfg: T, 371 | ) -> Result<(), ConfyError> { 372 | let path = get_configuration_file_path(app_name, config_name)?; 373 | store_path(path, cfg) 374 | } 375 | 376 | /// Save changes made to a configuration object at a specified path 377 | /// 378 | /// This is an alternate version of [`store`] that allows the specification of 379 | /// file permissions that must be set. For more information on errors and 380 | /// behavior, see [`store`]'s documentation. 381 | /// 382 | /// [`store`]: fn.store.html 383 | pub fn store_perms<'a, T: Serialize>( 384 | app_name: &str, 385 | config_name: impl Into>, 386 | cfg: T, 387 | perms: Permissions, 388 | ) -> Result<(), ConfyError> { 389 | let path = get_configuration_file_path(app_name, config_name)?; 390 | store_path_perms(path, cfg, perms) 391 | } 392 | 393 | /// Save changes made to a configuration object at a specified path 394 | /// 395 | /// This is an alternate version of [`store`] that allows the specification of 396 | /// an arbitrary path instead of a system one. For more information on errors 397 | /// and behavior, see [`store`]'s documentation. 398 | /// 399 | /// [`store`]: fn.store.html 400 | pub fn store_path(path: impl AsRef, cfg: T) -> Result<(), ConfyError> { 401 | do_store(path.as_ref(), cfg, None) 402 | } 403 | 404 | /// Save changes made to a configuration object at a specified path 405 | /// 406 | /// This is an alternate version of [`store_path`] that allows the 407 | /// specification of file permissions that must be set. For more information on 408 | /// errors and behavior, see [`store`]'s documentation. 409 | /// 410 | /// [`store_path`]: fn.store_path.html 411 | pub fn store_path_perms( 412 | path: impl AsRef, 413 | cfg: T, 414 | perms: Permissions, 415 | ) -> Result<(), ConfyError> { 416 | do_store(path.as_ref(), cfg, Some(perms)) 417 | } 418 | 419 | fn do_store( 420 | path: &Path, 421 | cfg: T, 422 | perms: Option, 423 | ) -> Result<(), ConfyError> { 424 | let config_dir = path 425 | .parent() 426 | .ok_or_else(|| ConfyError::BadConfigDirectory(format!("{path:?} is a root or prefix")))?; 427 | fs::create_dir_all(config_dir).map_err(ConfyError::DirectoryCreationFailed)?; 428 | 429 | let s; 430 | #[cfg(any(feature = "toml_conf", feature = "basic_toml_conf"))] 431 | { 432 | s = toml_to_string_pretty(&cfg).map_err(ConfyError::SerializeTomlError)?; 433 | } 434 | #[cfg(feature = "yaml_conf")] 435 | { 436 | s = serde_yaml::to_string(&cfg).map_err(ConfyError::SerializeYamlError)?; 437 | } 438 | #[cfg(feature = "ron_conf")] 439 | { 440 | let pretty_cfg = ron::ser::PrettyConfig::default(); 441 | s = ron::ser::to_string_pretty(&cfg, pretty_cfg).map_err(ConfyError::SerializeRonError)?; 442 | } 443 | 444 | let mut f = OpenOptions::new() 445 | .write(true) 446 | .create(true) 447 | .truncate(true) 448 | .open(path) 449 | .map_err(ConfyError::OpenConfigurationFileError)?; 450 | 451 | if let Some(p) = perms { 452 | f.set_permissions(p) 453 | .map_err(ConfyError::SetPermissionsFileError)?; 454 | } 455 | 456 | f.write_all(s.as_bytes()) 457 | .map_err(ConfyError::WriteConfigurationFileError)?; 458 | Ok(()) 459 | } 460 | 461 | /// Get the configuration file path used by [`load`] and [`store`] 462 | /// 463 | /// This is useful if you want to show where the configuration file is to your user. 464 | /// 465 | /// [`load`]: fn.load.html 466 | /// [`store`]: fn.store.html 467 | pub fn get_configuration_file_path<'a>( 468 | app_name: &str, 469 | config_name: impl Into>, 470 | ) -> Result { 471 | let config_name = config_name.into().unwrap_or("default-config"); 472 | let project = ProjectDirs::from("rs", "", app_name).ok_or_else(|| { 473 | ConfyError::BadConfigDirectory("could not determine home directory path".to_string()) 474 | })?; 475 | 476 | let config_dir_str = get_configuration_directory_str(&project)?; 477 | 478 | let path = [config_dir_str, &format!("{config_name}.{EXTENSION}")] 479 | .iter() 480 | .collect(); 481 | 482 | Ok(path) 483 | } 484 | 485 | fn get_configuration_directory_str(project: &ProjectDirs) -> Result<&str, ConfyError> { 486 | let path = project.config_dir(); 487 | path.to_str() 488 | .ok_or_else(|| ConfyError::BadConfigDirectory(format!("{path:?} is not valid Unicode"))) 489 | } 490 | 491 | #[cfg(test)] 492 | mod tests { 493 | use super::*; 494 | use serde::Serializer; 495 | use serde_derive::{Deserialize, Serialize}; 496 | 497 | #[cfg(unix)] 498 | use std::os::unix::fs::PermissionsExt; 499 | 500 | #[derive(PartialEq, Default, Debug, Serialize, Deserialize)] 501 | struct ExampleConfig { 502 | name: String, 503 | count: usize, 504 | } 505 | 506 | /// Run a test function with a temporary config path as fixture. 507 | fn with_config_path(test_fn: fn(&Path)) { 508 | let config_dir = tempfile::tempdir().expect("creating test fixture failed"); 509 | // config_path should roughly correspond to the result of `get_configuration_file_path("example-app", "example-config")` 510 | let config_path = config_dir 511 | .path() 512 | .join("example-app") 513 | .join("example-config") 514 | .with_extension(EXTENSION); 515 | test_fn(&config_path); 516 | config_dir.close().expect("removing test fixture failed"); 517 | } 518 | 519 | /// [`load_path`] loads [`ExampleConfig`]. 520 | #[test] 521 | fn load_path_works() { 522 | with_config_path(|path| { 523 | let config: ExampleConfig = load_path(path).expect("load_path failed"); 524 | assert_eq!(config, ExampleConfig::default()); 525 | }) 526 | } 527 | 528 | /// [`load_or_else`] loads [`ExampleConfig`]. 529 | #[test] 530 | fn load_or_else_works() { 531 | with_config_path(|path| { 532 | let the_value = || ExampleConfig { 533 | name: "a".to_string(), 534 | count: 5, 535 | }; 536 | 537 | let config: ExampleConfig = load_or_else(path, the_value).expect("load_or_else failed"); 538 | assert_eq!(config, the_value()); 539 | }); 540 | 541 | with_config_path(|path| { 542 | fs::create_dir_all(path.parent().unwrap()).unwrap(); 543 | let mut file = File::create(path).expect("creating file failed"); 544 | file.write("some normal text".as_bytes()) 545 | .expect("write to file failed"); 546 | drop(file); 547 | 548 | let the_value = || ExampleConfig { 549 | name: "a".to_string(), 550 | count: 5, 551 | }; 552 | 553 | let config: ExampleConfig = load_or_else(path, the_value).expect("load_or_else failed"); 554 | assert_eq!(config, the_value()); 555 | }) 556 | } 557 | 558 | /// [`store_path`] stores [`ExampleConfig`]. 559 | #[test] 560 | fn test_store_path() { 561 | with_config_path(|path| { 562 | let config: ExampleConfig = ExampleConfig { 563 | name: "Test".to_string(), 564 | count: 42, 565 | }; 566 | store_path(path, &config).expect("store_path failed"); 567 | let loaded = load_path(path).expect("load_path failed"); 568 | assert_eq!(config, loaded); 569 | }) 570 | } 571 | 572 | /// [`store_path_perms`] stores [`ExampleConfig`], with only read permission for owner (UNIX). 573 | #[test] 574 | #[cfg(unix)] 575 | fn test_store_path_perms() { 576 | with_config_path(|path| { 577 | let config: ExampleConfig = ExampleConfig { 578 | name: "Secret".to_string(), 579 | count: 16549, 580 | }; 581 | store_path_perms(path, &config, Permissions::from_mode(0o600)) 582 | .expect("store_path_perms failed"); 583 | let loaded = load_path(path).expect("load_path failed"); 584 | assert_eq!(config, loaded); 585 | }) 586 | } 587 | 588 | /// [`store_path_perms`] stores [`ExampleConfig`], as read-only. 589 | #[test] 590 | fn test_store_path_perms_readonly() { 591 | with_config_path(|path| { 592 | let config: ExampleConfig = ExampleConfig { 593 | name: "Soon read-only".to_string(), 594 | count: 27115, 595 | }; 596 | store_path(path, &config).expect("store_path failed"); 597 | 598 | let metadata = fs::metadata(path).expect("reading metadata failed"); 599 | let mut permissions = metadata.permissions(); 600 | permissions.set_readonly(true); 601 | 602 | store_path_perms(path, &config, permissions).expect("store_path_perms failed"); 603 | 604 | assert!(fs::metadata(path) 605 | .expect("reading metadata failed") 606 | .permissions() 607 | .readonly()); 608 | }) 609 | } 610 | 611 | /// [`store_path`] fails when given a root path. 612 | #[test] 613 | fn test_store_path_root_error() { 614 | let err = store_path(PathBuf::from("/"), &ExampleConfig::default()) 615 | .expect_err("store_path should fail"); 616 | assert_eq!( 617 | err.to_string(), 618 | r#"Bad configuration directory: "/" is a root or prefix"#, 619 | ) 620 | } 621 | 622 | struct CannotSerialize; 623 | 624 | impl Serialize for CannotSerialize { 625 | fn serialize(&self, _serializer: S) -> Result 626 | where 627 | S: Serializer, 628 | { 629 | use serde::ser::Error; 630 | Err(S::Error::custom("cannot serialize CannotSerialize")) 631 | } 632 | } 633 | 634 | /// Verify that if you call store_path() with an object that fails to serialize, 635 | /// the file on disk will not be overwritten or truncated. 636 | #[test] 637 | fn test_store_path_atomic() -> Result<(), ConfyError> { 638 | let tmp = tempfile::NamedTempFile::new().expect("Failed to create NamedTempFile"); 639 | let path = tmp.path(); 640 | let message = "Hello world!"; 641 | 642 | // Write to file. 643 | { 644 | let mut f = OpenOptions::new() 645 | .write(true) 646 | .create(true) 647 | .truncate(true) 648 | .open(path) 649 | .map_err(ConfyError::OpenConfigurationFileError)?; 650 | 651 | f.write_all(message.as_bytes()) 652 | .map_err(ConfyError::WriteConfigurationFileError)?; 653 | 654 | f.flush().map_err(ConfyError::WriteConfigurationFileError)?; 655 | } 656 | 657 | // Call store_path() to overwrite file with an object that fails to serialize. 658 | let store_result = store_path(path, CannotSerialize); 659 | assert!(matches!(store_result, Err(_))); 660 | 661 | // Ensure file was not overwritten. 662 | let buf = { 663 | let mut f = OpenOptions::new() 664 | .read(true) 665 | .open(path) 666 | .map_err(ConfyError::OpenConfigurationFileError)?; 667 | 668 | let mut buf = String::new(); 669 | 670 | use std::io::Read; 671 | f.read_to_string(&mut buf) 672 | .map_err(ConfyError::ReadConfigurationFileError)?; 673 | buf 674 | }; 675 | 676 | assert_eq!(buf, message); 677 | Ok(()) 678 | } 679 | 680 | // Verify that [`load_path`] can deserialize into structs with differing names 681 | // as long as they have the same fields 682 | #[test] 683 | fn test_change_struct_name() -> Result<(), ConfyError> { 684 | with_config_path(|path| { 685 | #[derive(PartialEq, Default, Debug, Serialize, Deserialize)] 686 | struct AnotherExampleConfig { 687 | name: String, 688 | count: usize, 689 | } 690 | 691 | store_path(path, &ExampleConfig::default()).expect("store_path failed"); 692 | let _: AnotherExampleConfig = load_path(path).expect("load_path failed"); 693 | }); 694 | 695 | Ok(()) 696 | } 697 | } 698 | -------------------------------------------------------------------------------- /src/utils.rs: -------------------------------------------------------------------------------- 1 | //! Some storage utilities 2 | 3 | use std::fs::File; 4 | use std::io::{Error as IoError, Read}; 5 | 6 | pub trait CheckedStringRead { 7 | fn get_string(&mut self) -> Result; 8 | } 9 | 10 | impl CheckedStringRead for File { 11 | fn get_string(&mut self) -> Result { 12 | let mut s = String::new(); 13 | self.read_to_string(&mut s)?; 14 | Ok(s) 15 | } 16 | } 17 | --------------------------------------------------------------------------------