confy-0.6.1/.cargo_vcs_info.json0000644000000001360000000000100121560ustar { "git": { "sha1": "15cfb0427a98092813b8bc2e75fa4578dd11fb3a" }, "path_in_vcs": "" }confy-0.6.1/.github/workflows/ci.yml000064400000000000000000000034301046102023000154610ustar 00000000000000on: [push, pull_request] name: CI jobs: check: name: Check runs-on: ${{ matrix.os }} strategy: matrix: rust: - stable - beta - nightly os: - ubuntu-latest - macOS-latest - windows-latest 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: needs: [check] name: Test Suite runs-on: ${{ matrix.os }} strategy: matrix: rust: - stable - beta - nightly os: - ubuntu-latest - macOS-latest - windows-latest 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 clippy: needs: [check] 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 confy-0.6.1/.github/workflows/fixup-merge-block.yml000064400000000000000000000003361046102023000204100ustar 00000000000000on: [pull_request] name: Git Checks jobs: block-fixup: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2.0.0 - name: Block Fixup Commit Merge uses: 13rac1/block-fixup-merge-action@v2.0.0 confy-0.6.1/.gitignore000064400000000000000000000005221046102023000127350ustar 00000000000000# Generated by Cargo # will have compiled files and executables /target/ # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock Cargo.lock # These are backup files generated by rustfmt **/*.rs.bk /target **/*.rs.bk Cargo.lock confy-0.6.1/Cargo.lock0000644000000324160000000000100101370ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "base64" version = "0.21.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" [[package]] name = "bitflags" version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed570934406eb16438a4e976b1b4500774099c13b8cb96eec99f620f05090ddf" dependencies = [ "serde", ] [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "confy" version = "0.6.1" dependencies = [ "directories", "ron", "serde", "serde_derive", "serde_yaml", "tempfile", "thiserror", "toml", ] [[package]] name = "directories" version = "5.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a49173b84e034382284f27f1af4dcbbd231ffa358c0fe316541a7337f376a35" dependencies = [ "dirs-sys", ] [[package]] name = "dirs-sys" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" dependencies = [ "libc", "option-ext", "redox_users", "windows-sys 0.48.0", ] [[package]] name = "equivalent" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" [[package]] name = "errno" version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a258e46cdc063eb8519c00b9fc845fc47bcfca4130e2f08e88665ceda8474245" dependencies = [ "libc", "windows-sys 0.52.0", ] [[package]] name = "fastrand" version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" [[package]] name = "getrandom" version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "190092ea657667030ac6a35e305e62fc4dd69fd98ac98631e5d3a2b1575a12b5" dependencies = [ "cfg-if", "libc", "wasi", ] [[package]] name = "hashbrown" version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604" [[package]] name = "indexmap" version = "2.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b0b929d511467233429c45a44ac1dcaa21ba0f5ba11e4879e6ed28ddb4f9df4" dependencies = [ "equivalent", "hashbrown", ] [[package]] name = "itoa" version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c" [[package]] name = "libc" version = "0.2.153" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd" [[package]] name = "libredox" version = "0.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85c833ca1e66078851dba29046874e38f08b2c883700aa29a03ddd3b23814ee8" dependencies = [ "bitflags 2.4.2", "libc", "redox_syscall", ] [[package]] name = "linux-raw-sys" version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c" [[package]] name = "memchr" version = "2.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "523dc4f511e55ab87b694dc30d0f820d60906ef06413f93d4d7a1385599cc149" [[package]] name = "option-ext" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" [[package]] name = "proc-macro2" version = "1.0.78" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2422ad645d89c99f8f3e6b88a9fdeca7fabeac836b1002371c4367c8f984aae" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" dependencies = [ "proc-macro2", ] [[package]] name = "redox_syscall" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" dependencies = [ "bitflags 1.3.2", ] [[package]] name = "redox_users" version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a18479200779601e498ada4e8c1e1f50e3ee19deb0259c25825a98b5603b2cb4" dependencies = [ "getrandom", "libredox", "thiserror", ] [[package]] name = "ron" version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b91f7eff05f748767f183df4320a63d6936e9c6107d97c9e6bdd9784f4289c94" dependencies = [ "base64", "bitflags 2.4.2", "serde", "serde_derive", ] [[package]] name = "rustix" version = "0.38.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ea3e1a662af26cd7a3ba09c0297a31af215563ecf42817c98df621387f4e949" dependencies = [ "bitflags 2.4.2", "errno", "libc", "linux-raw-sys", "windows-sys 0.52.0", ] [[package]] name = "ryu" version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e86697c916019a8588c99b5fac3cead74ec0b4b819707a682fd4d23fa0ce1ba1" [[package]] name = "serde" version = "1.0.197" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3fb1c873e1b9b056a4dc4c0c198b24c3ffa059243875552b2bd0933b1aee4ce2" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.197" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_spanned" version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eb3622f419d1296904700073ea6cc23ad690adbd66f13ea683df73298736f0c1" dependencies = [ "serde", ] [[package]] name = "serde_yaml" version = "0.9.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8fd075d994154d4a774f95b51fb96bdc2832b0ea48425c92546073816cda1f2f" dependencies = [ "indexmap", "itoa", "ryu", "serde", "unsafe-libyaml", ] [[package]] name = "syn" version = "2.0.52" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b699d15b36d1f02c3e7c69f8ffef53de37aefae075d8488d4ba1a7788d574a07" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "tempfile" version = "3.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1" dependencies = [ "cfg-if", "fastrand", "rustix", "windows-sys 0.52.0", ] [[package]] name = "thiserror" version = "1.0.57" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e45bcbe8ed29775f228095caf2cd67af7a4ccf756ebff23a306bf3e8b47b24b" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" version = "1.0.57" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a953cb265bef375dae3de6663da4d3804eee9682ea80d8e2542529b73c531c81" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "toml" version = "0.8.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a9aad4a3066010876e8dcf5a8a06e70a558751117a145c6ce2b82c2e2054290" dependencies = [ "serde", "serde_spanned", "toml_datetime", "toml_edit", ] [[package]] name = "toml_datetime" version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3550f4e9685620ac18a50ed434eb3aec30db8ba93b0287467bca5826ea25baf1" dependencies = [ "serde", ] [[package]] name = "toml_edit" version = "0.22.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2c1b5fd4128cc8d3e0cb74d4ed9a9cc7c7284becd4df68f5f940e1ad123606f6" dependencies = [ "indexmap", "serde", "serde_spanned", "toml_datetime", "winnow", ] [[package]] name = "unicode-ident" version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] name = "unsafe-libyaml" version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab4c90930b95a82d00dc9e9ac071b4991924390d46cbd0dfe566148667605e4b" [[package]] name = "wasi" version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "windows-sys" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" dependencies = [ "windows-targets 0.48.5", ] [[package]] name = "windows-sys" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ "windows-targets 0.52.4", ] [[package]] name = "windows-targets" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" dependencies = [ "windows_aarch64_gnullvm 0.48.5", "windows_aarch64_msvc 0.48.5", "windows_i686_gnu 0.48.5", "windows_i686_msvc 0.48.5", "windows_x86_64_gnu 0.48.5", "windows_x86_64_gnullvm 0.48.5", "windows_x86_64_msvc 0.48.5", ] [[package]] name = "windows-targets" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7dd37b7e5ab9018759f893a1952c9420d060016fc19a472b4bb20d1bdd694d1b" dependencies = [ "windows_aarch64_gnullvm 0.52.4", "windows_aarch64_msvc 0.52.4", "windows_i686_gnu 0.52.4", "windows_i686_msvc 0.52.4", "windows_x86_64_gnu 0.52.4", "windows_x86_64_gnullvm 0.52.4", "windows_x86_64_msvc 0.52.4", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" [[package]] name = "windows_aarch64_gnullvm" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bcf46cf4c365c6f2d1cc93ce535f2c8b244591df96ceee75d8e83deb70a9cac9" [[package]] name = "windows_aarch64_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" [[package]] name = "windows_aarch64_msvc" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da9f259dd3bcf6990b55bffd094c4f7235817ba4ceebde8e6d11cd0c5633b675" [[package]] name = "windows_i686_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" [[package]] name = "windows_i686_gnu" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b474d8268f99e0995f25b9f095bc7434632601028cf86590aea5c8a5cb7801d3" [[package]] name = "windows_i686_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" [[package]] name = "windows_i686_msvc" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1515e9a29e5bed743cb4415a9ecf5dfca648ce85ee42e15873c3cd8610ff8e02" [[package]] name = "windows_x86_64_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" [[package]] name = "windows_x86_64_gnu" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5eee091590e89cc02ad514ffe3ead9eb6b660aedca2183455434b93546371a03" [[package]] name = "windows_x86_64_gnullvm" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ca79f2451b49fa9e2af39f0747fe999fcda4f5e241b2898624dca97a1f2177" [[package]] name = "windows_x86_64_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "windows_x86_64_msvc" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32b752e52a2da0ddfbdbcc6fceadfeede4c939ed16d13e648833a61dfb611ed8" [[package]] name = "winnow" version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dffa400e67ed5a4dd237983829e66475f0a4a26938c4b04c21baede6262215b8" dependencies = [ "memchr", ] confy-0.6.1/Cargo.toml0000644000000024230000000000100101550ustar # 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 are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "confy" version = "0.6.1" authors = ["Katharina Fey "] description = "Boilerplate-free configuration management" documentation = "https://docs.rs/confy" readme = "README.md" license = "MIT/X11 OR Apache-2.0" repository = "https://github.com/rust-cli/confy" [[example]] name = "simple" [dependencies.directories] version = "5" [dependencies.ron] version = "0.8.0" optional = true [dependencies.serde] version = "^1.0" [dependencies.serde_yaml] version = "0.9" optional = true [dependencies.thiserror] version = "1.0" [dependencies.toml] version = "0.8" optional = true [dev-dependencies.serde_derive] version = "^1.0" [dev-dependencies.tempfile] version = "3.2.0" [features] default = ["toml_conf"] ron_conf = ["ron"] toml_conf = ["toml"] yaml_conf = ["serde_yaml"] confy-0.6.1/Cargo.toml.orig000064400000000000000000000013111046102023000136310ustar 00000000000000[package] name = "confy" version = "0.6.1" authors = ["Katharina Fey "] description = "Boilerplate-free configuration management" license = "MIT/X11 OR Apache-2.0" documentation = "https://docs.rs/confy" repository = "https://github.com/rust-cli/confy" readme = "README.md" edition = "2021" [dependencies] ron = { version = "0.8.0", optional = true } directories = "5" serde = "^1.0" serde_yaml = { version = "0.9", optional = true } thiserror = "1.0" toml = { version = "0.8", optional = true } [features] default = ["toml_conf"] toml_conf = ["toml"] yaml_conf = ["serde_yaml"] ron_conf = ["ron"] [[example]] name = "simple" [dev-dependencies] serde_derive = "^1.0" tempfile = "3.2.0" confy-0.6.1/LICENSE000064400000000000000000000000321046102023000117460ustar 00000000000000MIT OR X11 OR Apache-2.0+ confy-0.6.1/LICENSE-Apache-2.0000064400000000000000000000261321046102023000134330ustar 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 2024 Rust CLI Working Group 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. confy-0.6.1/LICENSE-MIT000064400000000000000000000020521046102023000124010ustar 00000000000000Copyright (c) 2024 Rust CLI Working Group 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. confy-0.6.1/LICENSE-X11000064400000000000000000000024151046102023000123240ustar 00000000000000Copyright (C) 2024 Rust CLI Working Group 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 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. 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. confy-0.6.1/README.md000064400000000000000000000073521046102023000122340ustar 00000000000000# confy [![crates.io](https://img.shields.io/crates/v/confy)](https://crates.io/crates/confy) [![docs.rs](https://img.shields.io/docsrs/confy)](https://docs.rs/confy/) [![Discord](https://img.shields.io/badge/chat-Discord-informational)](https://discord.gg/dwq4Zme) Zero-boilerplate configuration management. Focus on storing the right data, instead of worrying about how or where to store it. ```rust use serde_derive::{Serialize, Deserialize}; #[derive(Default, Debug, Serialize, Deserialize)] struct MyConfig { version: u8, api_key: String, } fn main() -> Result<(), Box> { let cfg: MyConfig = confy::load("my-app-name", None)?; dbg!(cfg); Ok(()) } ``` ## Confy's feature flags `confy` can be used with either `TOML`, `YAML`, or `RON` files. `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. 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. ### Using YAML 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`. Enable the feature in `Cargo.toml`: ```toml [dependencies.confy] features = ["yaml_conf"] default-features = false ``` ### Using RON 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`. Enable the feature in `Cargo.toml`: ```toml [dependencies.confy] features = ["ron_conf"] default-features = false ``` ## Changing error messages Information about adding context to error messages can be found at [Providing Context](https://rust-cli.github.io/book/tutorial/errors.html#providing-context) ## Breaking changes ### Version 0.6.0 In this version we bumped several dependencies which have had changes with some of the default (de)serialization process: * `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. * `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". ### Version 0.5.0 * The base functions `load` and `store` have been added an optional parameter in the event multiples configurations are needed, or ones with different filename. * 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. * 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. ### Version 0.4.0 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. Before version 0.4.0, the configuration file was written in the current directory. [`directories`]: https://crates.io/crates/directories [`directories-next`]: https://crates.io/crates/directories-next ## License This work is triple-licensed under MIT, MIT/X11, or the Apache 2.0 (or any later version). You may choose any one of these three licenses if you use this work. `SPDX-License-Identifier: MIT OR X11 OR Apache-2.0+` confy-0.6.1/examples/simple.rs000064400000000000000000000032311046102023000144220ustar 00000000000000//! The most simplest examples of how to use confy extern crate confy; #[macro_use] extern crate serde_derive; use std::io::Read; #[derive(Debug, Serialize, Deserialize)] struct ConfyConfig { name: String, comfy: bool, foo: i64, } impl Default for ConfyConfig { fn default() -> Self { ConfyConfig { name: "Unknown".to_string(), comfy: true, foo: 42, } } } fn main() -> Result<(), confy::ConfyError> { let cfg: ConfyConfig = confy::load("confy_simple_app", None)?; let file = confy::get_configuration_file_path("confy_simple_app", None)?; println!("The configuration file path is: {:#?}", file); println!("The configuration is:"); println!("{:#?}", cfg); println!("The wrote toml file content is:"); let mut content = String::new(); std::fs::File::open(&file) .expect("Failed to open toml configuration file.") .read_to_string(&mut content) .expect("Failed to read toml configuration file."); println!("{}", content); let cfg = ConfyConfig { name: "Test".to_string(), ..cfg }; confy::store("confy_simple_app",None, &cfg)?; println!("The updated toml file content is:"); let mut content = String::new(); std::fs::File::open(&file) .expect("Failed to open toml configuration file.") .read_to_string(&mut content) .expect("Failed to read toml configuration file."); println!("{}", content); let _cfg = ConfyConfig { name: "Test".to_string(), ..cfg }; std::fs::remove_dir_all(file.parent().unwrap()) .expect("Failed to remove directory"); Ok(()) } confy-0.6.1/src/lib.rs000064400000000000000000000444071046102023000126620ustar 00000000000000//! Zero-boilerplate configuration management //! //! ## Why? //! //! There are a lot of different requirements when //! selecting, loading and writing a config, //! depending on the operating system and other //! environment factors. //! //! In many applications this burden is left to you, //! the developer of an application, to figure out //! where to place the configuration files. //! //! This is where `confy` comes in. //! //! ## Idea //! //! `confy` takes care of figuring out operating system //! specific and environment paths before reading and //! writing a configuration. //! //! It gives you easy access to a configuration file //! which is mirrored into a Rust `struct` via [serde]. //! This way you only need to worry about the layout of //! your configuration, not where and how to store it. //! //! [serde]: https://docs.rs/serde //! //! `confy` uses the [`Default`] trait in Rust to automatically //! create a new configuration, if none is available to read //! from yet. //! This means that you can simply assume your application //! to have a configuration, which will be created with //! default values of your choosing, without requiring //! any special logic to handle creation. //! //! [`Default`]: https://doc.rust-lang.org/std/default/trait.Default.html //! //! ```rust,no_run //! use serde_derive::{Serialize, Deserialize}; //! //! #[derive(Serialize, Deserialize)] //! struct MyConfig { //! version: u8, //! api_key: String, //! } //! //! /// `MyConfig` implements `Default` //! impl ::std::default::Default for MyConfig { //! fn default() -> Self { Self { version: 0, api_key: "".into() } } //! } //! //! fn main() -> Result<(), confy::ConfyError> { //! let cfg = confy::load("my-app-name", None)?; //! Ok(()) //! } //! ``` //! //! Serde is a required dependency, and can be added with either the `serde_derive` crate or `serde` crate with feature derive as shown below //!```toml,no_run //![dependencies] //!serde = { version = "1.0.152", features = ["derive"] } # <- Only one serde version needed (serde or serde_derive) //!serde_derive = "1.0.152" # <- Only one serde version needed (serde or serde_derive) //!confy = "^0.5" //!``` //! Updating the configuration is then done via the [`store`] function. //! //! [`store`]: fn.store.html //! mod utils; use utils::*; use directories::ProjectDirs; use serde::{de::DeserializeOwned, Serialize}; use std::fs::{self, File, OpenOptions, Permissions}; use std::io::{ErrorKind::NotFound, Write}; use std::path::{Path, PathBuf}; use thiserror::Error; #[cfg(not(any(feature = "toml_conf", feature = "yaml_conf", feature = "ron_conf")))] compile_error!( "Exactly one config language feature must be enabled to use \ confy. Please enable one of either the `toml_conf`, `yaml_conf`, \ or `ron_conf` features." ); #[cfg(any( all(feature = "toml_conf", feature = "yaml_conf"), all(feature = "toml_conf", feature = "ron_conf"), all(feature = "ron_conf", feature = "yaml_conf"), ))] compile_error!( "Exactly one config language feature must be enabled to compile \ confy. Please disable one of either the `toml_conf`, `yaml_conf`, or `ron_conf` features. \ NOTE: `toml_conf` is a default feature, so disabling it might mean switching off \ default features for confy in your Cargo.toml" ); #[cfg(feature = "toml_conf")] const EXTENSION: &str = "toml"; #[cfg(feature = "yaml_conf")] const EXTENSION: &str = "yml"; #[cfg(feature = "ron_conf")] const EXTENSION: &str = "ron"; /// The errors the confy crate can encounter. #[derive(Debug, Error)] pub enum ConfyError { #[cfg(feature = "toml_conf")] #[error("Bad TOML data")] BadTomlData(#[source] toml::de::Error), #[cfg(feature = "yaml_conf")] #[error("Bad YAML data")] BadYamlData(#[source] serde_yaml::Error), #[cfg(feature = "ron_conf")] #[error("Bad RON data")] BadRonData(#[source] ron::error::SpannedError), #[error("Failed to create directory")] DirectoryCreationFailed(#[source] std::io::Error), #[error("Failed to load configuration file")] GeneralLoadError(#[source] std::io::Error), #[error("Bad configuration directory: {0}")] BadConfigDirectory(String), #[cfg(feature = "toml_conf")] #[error("Failed to serialize configuration data into TOML")] SerializeTomlError(#[source] toml::ser::Error), #[cfg(feature = "yaml_conf")] #[error("Failed to serialize configuration data into YAML")] SerializeYamlError(#[source] serde_yaml::Error), #[cfg(feature = "ron_conf")] #[error("Failed to serialize configuration data into RON")] SerializeRonError(#[source] ron::error::Error), #[error("Failed to write configuration file")] WriteConfigurationFileError(#[source] std::io::Error), #[error("Failed to read configuration file")] ReadConfigurationFileError(#[source] std::io::Error), #[error("Failed to open configuration file")] OpenConfigurationFileError(#[source] std::io::Error), #[error("Failed to set configuration file permissions")] SetPermissionsFileError(#[source] std::io::Error), } /// Load an application configuration from disk /// /// A new configuration file is created with default values if none /// exists. /// /// Errors that are returned from this function are I/O related, /// for example if the writing of the new configuration fails /// or `confy` encounters an operating system or environment /// that it does not support. /// /// **Note:** The type of configuration needs to be declared in some way /// that is inferable by the compiler. Also note that your /// configuration needs to implement `Default`. /// /// ```rust,no_run /// # use confy::ConfyError; /// # use serde_derive::{Serialize, Deserialize}; /// # fn main() -> Result<(), ConfyError> { /// #[derive(Default, Serialize, Deserialize)] /// struct MyConfig {} /// /// let cfg: MyConfig = confy::load("my-app-name", None)?; /// # Ok(()) /// # } /// ``` pub fn load<'a, T: Serialize + DeserializeOwned + Default>( app_name: &str, config_name: impl Into>, ) -> Result { get_configuration_file_path(app_name, config_name).and_then(load_path) } /// Load an application configuration from a specified path. /// /// A new configuration file is created with default values if none /// exists. /// /// This is an alternate version of [`load`] that allows the specification of /// an arbitrary path instead of a system one. For more information on errors /// and behavior, see [`load`]'s documentation. /// /// [`load`]: fn.load.html pub fn load_path( path: impl AsRef, ) -> Result { match File::open(&path) { Ok(mut cfg) => { let cfg_string = cfg .get_string() .map_err(ConfyError::ReadConfigurationFileError)?; #[cfg(feature = "toml_conf")] { let cfg_data = toml::from_str(&cfg_string); cfg_data.map_err(ConfyError::BadTomlData) } #[cfg(feature = "yaml_conf")] { let cfg_data = serde_yaml::from_str(&cfg_string); cfg_data.map_err(ConfyError::BadYamlData) } #[cfg(feature = "ron_conf")] { let cfg_data = ron::from_str(&cfg_string); cfg_data.map_err(ConfyError::BadRonData) } } Err(ref e) if e.kind() == NotFound => { if let Some(parent) = path.as_ref().parent() { fs::create_dir_all(parent).map_err(ConfyError::DirectoryCreationFailed)?; } let cfg = T::default(); store_path(path, &cfg)?; Ok(cfg) } Err(e) => Err(ConfyError::GeneralLoadError(e)), } } /// Save changes made to a configuration object /// /// This function will update a configuration, /// with the provided values, and create a new one, /// if none exists. /// /// You can also use this function to create a new configuration /// with different initial values than which are provided /// by your `Default` trait implementation, or if your /// configuration structure _can't_ implement `Default`. /// /// ```rust,no_run /// # use serde_derive::{Serialize, Deserialize}; /// # use confy::ConfyError; /// # fn main() -> Result<(), ConfyError> { /// #[derive(Serialize, Deserialize)] /// struct MyConf {} /// /// let my_cfg = MyConf {}; /// confy::store("my-app-name", None, my_cfg)?; /// # Ok(()) /// # } /// ``` /// /// Errors returned are I/O errors related to not being /// able to write the configuration file or if `confy` /// encounters an operating system or environment it does /// not support. pub fn store<'a, T: Serialize>( app_name: &str, config_name: impl Into>, cfg: T, ) -> Result<(), ConfyError> { let path = get_configuration_file_path(app_name, config_name)?; store_path(path, cfg) } /// Save changes made to a configuration object at a specified path /// /// This is an alternate version of [`store`] that allows the specification of /// file permissions that must be set. For more information on errors and /// behavior, see [`store`]'s documentation. /// /// [`store`]: fn.store.html pub fn store_perms<'a, T: Serialize>( app_name: &str, config_name: impl Into>, cfg: T, perms: Permissions, ) -> Result<(), ConfyError> { let path = get_configuration_file_path(app_name, config_name)?; store_path_perms(path, cfg, perms) } /// Save changes made to a configuration object at a specified path /// /// This is an alternate version of [`store`] that allows the specification of /// an arbitrary path instead of a system one. For more information on errors /// and behavior, see [`store`]'s documentation. /// /// [`store`]: fn.store.html pub fn store_path(path: impl AsRef, cfg: T) -> Result<(), ConfyError> { do_store(path.as_ref(), cfg, None) } /// Save changes made to a configuration object at a specified path /// /// This is an alternate version of [`store_path`] that allows the /// specification of file permissions that must be set. For more information on /// errors and behavior, see [`store`]'s documentation. /// /// [`store_path`]: fn.store_path.html pub fn store_path_perms( path: impl AsRef, cfg: T, perms: Permissions, ) -> Result<(), ConfyError> { do_store(path.as_ref(), cfg, Some(perms)) } fn do_store( path: &Path, cfg: T, perms: Option, ) -> Result<(), ConfyError> { let config_dir = path .parent() .ok_or_else(|| ConfyError::BadConfigDirectory(format!("{path:?} is a root or prefix")))?; fs::create_dir_all(config_dir).map_err(ConfyError::DirectoryCreationFailed)?; let s; #[cfg(feature = "toml_conf")] { s = toml::to_string_pretty(&cfg).map_err(ConfyError::SerializeTomlError)?; } #[cfg(feature = "yaml_conf")] { s = serde_yaml::to_string(&cfg).map_err(ConfyError::SerializeYamlError)?; } #[cfg(feature = "ron_conf")] { let pretty_cfg = ron::ser::PrettyConfig::default(); s = ron::ser::to_string_pretty(&cfg, pretty_cfg).map_err(ConfyError::SerializeRonError)?; } let mut f = OpenOptions::new() .write(true) .create(true) .truncate(true) .open(path) .map_err(ConfyError::OpenConfigurationFileError)?; if let Some(p) = perms { f.set_permissions(p) .map_err(ConfyError::SetPermissionsFileError)?; } f.write_all(s.as_bytes()) .map_err(ConfyError::WriteConfigurationFileError)?; Ok(()) } /// Get the configuration file path used by [`load`] and [`store`] /// /// This is useful if you want to show where the configuration file is to your user. /// /// [`load`]: fn.load.html /// [`store`]: fn.store.html pub fn get_configuration_file_path<'a>( app_name: &str, config_name: impl Into>, ) -> Result { let config_name = config_name.into().unwrap_or("default-config"); let project = ProjectDirs::from("rs", "", app_name).ok_or_else(|| { ConfyError::BadConfigDirectory("could not determine home directory path".to_string()) })?; let config_dir_str = get_configuration_directory_str(&project)?; let path = [config_dir_str, &format!("{config_name}.{EXTENSION}")] .iter() .collect(); Ok(path) } fn get_configuration_directory_str(project: &ProjectDirs) -> Result<&str, ConfyError> { let path = project.config_dir(); path.to_str() .ok_or_else(|| ConfyError::BadConfigDirectory(format!("{path:?} is not valid Unicode"))) } #[cfg(test)] mod tests { use super::*; use serde::Serializer; use serde_derive::{Deserialize, Serialize}; #[cfg(unix)] use std::os::unix::fs::PermissionsExt; #[derive(PartialEq, Default, Debug, Serialize, Deserialize)] struct ExampleConfig { name: String, count: usize, } /// Run a test function with a temporary config path as fixture. fn with_config_path(test_fn: fn(&Path)) { let config_dir = tempfile::tempdir().expect("creating test fixture failed"); // config_path should roughly correspond to the result of `get_configuration_file_path("example-app", "example-config")` let config_path = config_dir .path() .join("example-app") .join("example-config") .with_extension(EXTENSION); test_fn(&config_path); config_dir.close().expect("removing test fixture failed"); } /// [`load_path`] loads [`ExampleConfig`]. #[test] fn load_path_works() { with_config_path(|path| { let config: ExampleConfig = load_path(path).expect("load_path failed"); assert_eq!(config, ExampleConfig::default()); }) } /// [`store_path`] stores [`ExampleConfig`]. #[test] fn test_store_path() { with_config_path(|path| { let config: ExampleConfig = ExampleConfig { name: "Test".to_string(), count: 42, }; store_path(path, &config).expect("store_path failed"); let loaded = load_path(path).expect("load_path failed"); assert_eq!(config, loaded); }) } /// [`store_path_perms`] stores [`ExampleConfig`], with only read permission for owner (UNIX). #[test] #[cfg(unix)] fn test_store_path_perms() { with_config_path(|path| { let config: ExampleConfig = ExampleConfig { name: "Secret".to_string(), count: 16549, }; store_path_perms(path, &config, Permissions::from_mode(0o600)) .expect("store_path_perms failed"); let loaded = load_path(path).expect("load_path failed"); assert_eq!(config, loaded); }) } /// [`store_path_perms`] stores [`ExampleConfig`], as read-only. #[test] fn test_store_path_perms_readonly() { with_config_path(|path| { let config: ExampleConfig = ExampleConfig { name: "Soon read-only".to_string(), count: 27115, }; store_path(path, &config).expect("store_path failed"); let metadata = fs::metadata(path).expect("reading metadata failed"); let mut permissions = metadata.permissions(); permissions.set_readonly(true); store_path_perms(path, &config, permissions).expect("store_path_perms failed"); assert!(fs::metadata(path) .expect("reading metadata failed") .permissions() .readonly()); }) } /// [`store_path`] fails when given a root path. #[test] fn test_store_path_root_error() { let err = store_path(PathBuf::from("/"), &ExampleConfig::default()) .expect_err("store_path should fail"); assert_eq!( err.to_string(), r#"Bad configuration directory: "/" is a root or prefix"#, ) } struct CannotSerialize; impl Serialize for CannotSerialize { fn serialize(&self, _serializer: S) -> Result where S: Serializer, { use serde::ser::Error; Err(S::Error::custom("cannot serialize CannotSerialize")) } } /// Verify that if you call store_path() with an object that fails to serialize, /// the file on disk will not be overwritten or truncated. #[test] fn test_store_path_atomic() -> Result<(), ConfyError> { let tmp = tempfile::NamedTempFile::new().expect("Failed to create NamedTempFile"); let path = tmp.path(); let message = "Hello world!"; // Write to file. { let mut f = OpenOptions::new() .write(true) .create(true) .truncate(true) .open(path) .map_err(ConfyError::OpenConfigurationFileError)?; f.write_all(message.as_bytes()) .map_err(ConfyError::WriteConfigurationFileError)?; f.flush().map_err(ConfyError::WriteConfigurationFileError)?; } // Call store_path() to overwrite file with an object that fails to serialize. let store_result = store_path(path, CannotSerialize); assert!(matches!(store_result, Err(_))); // Ensure file was not overwritten. let buf = { let mut f = OpenOptions::new() .read(true) .open(path) .map_err(ConfyError::OpenConfigurationFileError)?; let mut buf = String::new(); use std::io::Read; f.read_to_string(&mut buf) .map_err(ConfyError::ReadConfigurationFileError)?; buf }; assert_eq!(buf, message); Ok(()) } // Verify that [`load_path`] can deserialize into structs with differing names // as long as they have the same fields #[test] fn test_change_struct_name() -> Result<(), ConfyError> { with_config_path(|path| { #[derive(PartialEq, Default, Debug, Serialize, Deserialize)] struct AnotherExampleConfig { name: String, count: usize, } store_path(path, &ExampleConfig::default()).expect("store_path failed"); let _: AnotherExampleConfig = load_path(path).expect("load_path failed"); }); Ok(()) } } confy-0.6.1/src/utils.rs000064400000000000000000000005541046102023000132470ustar 00000000000000//! Some storage utilities use std::fs::File; use std::io::{Error as IoError, Read}; pub trait CheckedStringRead { fn get_string(&mut self) -> Result; } impl CheckedStringRead for File { fn get_string(&mut self) -> Result { let mut s = String::new(); self.read_to_string(&mut s)?; Ok(s) } }