├── .github ├── FUNDING.yml ├── dependabot.yml └── workflows │ ├── periodic.yml │ └── regression.yml ├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── release.toml ├── structopt-toml-derive ├── Cargo.toml └── src │ └── lib.rs └── structopt-toml ├── Cargo.toml ├── build.rs ├── examples └── example.rs ├── src └── lib.rs └── tests ├── skeptic.rs └── test.rs /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: dalance 4 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: cargo 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | time: "20:00" 8 | open-pull-requests-limit: 10 9 | -------------------------------------------------------------------------------- /.github/workflows/periodic.yml: -------------------------------------------------------------------------------- 1 | name: Periodic 2 | 3 | on: 4 | schedule: 5 | - cron: 0 0 * * SUN 6 | 7 | jobs: 8 | build: 9 | 10 | strategy: 11 | matrix: 12 | os: [ubuntu-latest] 13 | rust: [stable, beta, nightly] 14 | 15 | runs-on: ${{ matrix.os }} 16 | 17 | steps: 18 | - name: Setup Rust 19 | uses: hecrj/setup-rust-action@v1 20 | with: 21 | rust-version: ${{ matrix.rust }} 22 | - name: Checkout 23 | uses: actions/checkout@v1 24 | - name: Run tests 25 | run: cargo test 26 | -------------------------------------------------------------------------------- /.github/workflows/regression.yml: -------------------------------------------------------------------------------- 1 | name: Regression 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | 9 | jobs: 10 | build: 11 | 12 | strategy: 13 | matrix: 14 | os: [ubuntu-latest] 15 | rust: [stable] 16 | 17 | runs-on: ${{ matrix.os }} 18 | 19 | steps: 20 | - name: Setup Rust 21 | uses: hecrj/setup-rust-action@v1 22 | with: 23 | rust-version: ${{ matrix.rust }} 24 | - name: Checkout 25 | uses: actions/checkout@v1 26 | - name: Run tests 27 | run: cargo test 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target 4 | */target 5 | 6 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 7 | # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock 8 | Cargo.lock 9 | 10 | # These are backup files generated by rustfmt 11 | **/*.rs.bk 12 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: required 2 | 3 | language: rust 4 | 5 | rust: 6 | - stable 7 | - beta 8 | - nightly 9 | 10 | matrix: 11 | allow_failures: 12 | - rust: nightly 13 | fast_finish: true 14 | 15 | script: 16 | - cargo test 17 | - cargo run --example example 18 | 19 | after_success: | 20 | if [[ $TRAVIS_RUST_VERSION == "stable" ]]; then 21 | RUSTFLAGS="--cfg procmacro2_semver_exempt" cargo install cargo-tarpaulin 22 | # Uncomment the following line for coveralls.io 23 | # cargo tarpaulin --ciserver travis-ci --coveralls $TRAVIS_JOB_ID 24 | 25 | # Uncomment the following two lines create and upload a report for codecov.io 26 | cargo tarpaulin --out Xml 27 | bash <(curl -s https://codecov.io/bash) 28 | fi 29 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = [ 3 | "structopt-toml", 4 | "structopt-toml-derive", 5 | ] 6 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018 dalance 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # structopt-toml 2 | An default value loader from TOML for structopt. 3 | It combinates with [structopt](https://github.com/TeXitoi/structopt). 4 | 5 | [![Actions Status](https://github.com/dalance/structopt-toml/workflows/Rust/badge.svg)](https://github.com/dalance/structopt-toml/actions) 6 | [![Crates.io](https://img.shields.io/crates/v/structopt-toml.svg)](https://crates.io/crates/structopt-toml) 7 | [![Docs.rs](https://docs.rs/structopt-toml/badge.svg)](https://docs.rs/structopt-toml) 8 | [![codecov](https://codecov.io/gh/dalance/structopt-toml/branch/master/graph/badge.svg)](https://codecov.io/gh/dalance/structopt-toml) 9 | 10 | ## Usage 11 | 12 | This crate must be used with `serde`, `serde_derive`, `structopt`, and `toml` explicitly. 13 | 14 | ```Cargo.toml 15 | [dependencies] 16 | serde = "1.0.104" 17 | serde_derive = "1.0.104" 18 | structopt = "0.3.11" 19 | structopt-toml = "0.5.1" 20 | toml = "0.5.6" 21 | ``` 22 | 23 | ## Example 24 | 25 | If `derive(Deserialize)`, `derive(StructOptToml)` and `serde(default)` are added to the struct with `derive(StructOpt)`, some functions like `from_args_with_toml` can be used. 26 | 27 | ```rust 28 | use serde_derive::Deserialize; 29 | use structopt::StructOpt; 30 | use structopt_toml::StructOptToml; 31 | 32 | #[derive(Debug, Deserialize, StructOpt, StructOptToml)] 33 | #[serde(default)] 34 | struct Opt { 35 | #[structopt(default_value = "0", short = "a")] a: i32, 36 | #[structopt(default_value = "0", short = "b")] b: i32, 37 | } 38 | 39 | fn main() { 40 | let toml_str = r#" 41 | a = 10 42 | "#; 43 | let opt = Opt::from_args_with_toml(toml_str).expect("toml parse failed"); 44 | println!("a:{}", opt.a); 45 | println!("b:{}", opt.b); 46 | } 47 | ``` 48 | 49 | The execution result is below. 50 | 51 | ```console 52 | $ ./example 53 | a:10 // value from TOML string 54 | b:0 // value from default_value of structopt 55 | 56 | $ ./example -a 20 57 | a:20 // value from command line argument 58 | b:0 59 | ``` 60 | 61 | ## License 62 | 63 | Licensed under either of 64 | 65 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 66 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 67 | 68 | at your option. 69 | 70 | ### Contribution 71 | 72 | Unless you explicitly state otherwise, any contribution intentionally 73 | submitted for inclusion in the work by you, as defined in the Apache-2.0 74 | license, shall be dual licensed as above, without any additional terms or 75 | conditions. 76 | -------------------------------------------------------------------------------- /release.toml: -------------------------------------------------------------------------------- 1 | no-dev-version = true 2 | consolidate-commits = true 3 | pre-release-commit-message = "Prepare to release" 4 | tag-message = "Bump version to v{{version}}" 5 | tag-prefix = "" 6 | dependent-version = "upgrade" 7 | -------------------------------------------------------------------------------- /structopt-toml-derive/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "structopt-toml-derive" 3 | version = "0.5.1" 4 | authors = ["dalance@gmail.com"] 5 | repository = "https://github.com/dalance/structopt-toml" 6 | keywords = ["cli", "structopt", "clap", "derive"] 7 | categories = ["command-line-interface"] 8 | license = "MIT OR Apache-2.0" 9 | description = "A derive crate of structopt-toml" 10 | edition = "2018" 11 | 12 | [package.metadata.release] 13 | disable-tag = true 14 | 15 | [lib] 16 | proc-macro = true 17 | 18 | [dependencies] 19 | proc-macro2 = "1.0.10" 20 | syn = "1.0.18" 21 | quote = "1.0.3" 22 | heck = "0.4.0" 23 | -------------------------------------------------------------------------------- /structopt-toml-derive/src/lib.rs: -------------------------------------------------------------------------------- 1 | extern crate proc_macro; 2 | extern crate syn; 3 | #[macro_use] 4 | extern crate quote; 5 | 6 | use heck::ToKebabCase; 7 | use proc_macro::TokenStream; 8 | use proc_macro2::TokenTree; 9 | use syn::parse::{Parse, ParseStream}; 10 | use syn::punctuated::Punctuated; 11 | use syn::token::Comma; 12 | use syn::{buffer::Cursor, DataStruct, DeriveInput, Field, Ident, LitStr}; 13 | 14 | #[proc_macro_derive(StructOptToml, attributes(structopt))] 15 | pub fn structopt_toml(input: TokenStream) -> TokenStream { 16 | let input: DeriveInput = syn::parse(input).unwrap(); 17 | let gen = impl_structopt_toml(&input); 18 | gen.into() 19 | } 20 | 21 | fn impl_structopt_toml(input: &DeriveInput) -> proc_macro2::TokenStream { 22 | use syn::Data::*; 23 | 24 | let struct_name = &input.ident; 25 | let inner_impl = match input.data { 26 | Struct(DataStruct { 27 | fields: syn::Fields::Named(ref fields), 28 | .. 29 | }) => impl_structopt_for_struct(struct_name, &fields.named), 30 | _ => panic!("structopt_toml only supports non-tuple struct"), 31 | }; 32 | 33 | quote!(#inner_impl) 34 | } 35 | 36 | fn impl_structopt_for_struct( 37 | name: &Ident, 38 | fields: &Punctuated, 39 | ) -> proc_macro2::TokenStream { 40 | let merged_fields = gen_merged_fields(fields); 41 | 42 | quote! { 43 | impl ::structopt_toml::StructOptToml for #name { 44 | fn merge<'a>(from_toml: Self, from_args: Self, args: &::structopt_toml::clap::ArgMatches) -> Self where 45 | Self: Sized, 46 | Self: ::structopt_toml::structopt::StructOpt, 47 | Self: ::structopt_toml::serde::de::Deserialize<'a> 48 | { 49 | Self { 50 | #merged_fields 51 | } 52 | } 53 | } 54 | 55 | impl Default for #name { 56 | fn default() -> Self { 57 | #name::from_args() 58 | } 59 | } 60 | } 61 | } 62 | 63 | fn gen_merged_fields(fields: &Punctuated) -> proc_macro2::TokenStream { 64 | let fields = fields.iter().map(|field| { 65 | let explicit_name = load_explicit_name(field); 66 | 67 | // If the field is decorated with `#[structopt(flatten)]` we have to treat it differently. 68 | // We can't check its existence with `args.is_present` and `args.occurrences_of` 69 | // and instead we delegate and call its own `StructOptToml` implementation of `merge` 70 | let is_flatten = is_flatten(field); 71 | 72 | // by default the clap arg name is the field name in kebab-case, unless overwritten with `name=` 73 | let field_name = field.ident.as_ref().unwrap(); 74 | let field_type = field.ty.clone(); 75 | let name_str = explicit_name.unwrap_or_else(|| format!("{}", field_name).to_kebab_case()); 76 | let structopt_name = LitStr::new(&name_str, field_name.span()); 77 | if is_flatten { 78 | quote!( 79 | #field_name: { 80 | <#field_type as ::structopt_toml::StructOptToml>::merge( 81 | from_toml.#field_name, 82 | from_args.#field_name, 83 | args 84 | ) 85 | } 86 | ) 87 | } else { 88 | quote!( 89 | #field_name: { 90 | if args.is_present(#structopt_name) && args.occurrences_of(#structopt_name) > 0 { 91 | from_args.#field_name 92 | } else { 93 | from_toml.#field_name 94 | } 95 | } 96 | ) 97 | } 98 | }); 99 | quote! ( 100 | #( #fields ),* 101 | ) 102 | } 103 | 104 | /// Loads the structopt name from the strcutopt attribute. 105 | /// i.e. from an attribute of the form `#[structopt(..., name = "some-name", ...)]` 106 | fn load_explicit_name(field: &Field) -> Option { 107 | field 108 | .attrs 109 | .iter() 110 | .filter(|&attr| attr.path.is_ident("structopt")) 111 | .filter_map(|attr| { 112 | // extract parentheses 113 | let ts = attr.parse_args().ok()?; 114 | // find name = `value` in attribute 115 | syn::parse2::(ts).map(|nv| nv.0).ok() 116 | }) 117 | .next() 118 | } 119 | 120 | /// Checks whether the attribute is marked as flattened 121 | /// i.e. `#[structopt(flatten)]` 122 | fn is_flatten(field: &Field) -> bool { 123 | field 124 | .attrs 125 | .iter() 126 | .filter(|&attr| attr.path.is_ident("structopt")) 127 | .filter_map(|attr| attr.parse_meta().ok()) 128 | .map(|meta| { 129 | let list = match meta { 130 | syn::Meta::List(list) => list, 131 | _ => return false, 132 | }; 133 | let nested = match list.nested.first() { 134 | Some(nested) => nested, 135 | _ => return false, 136 | }; 137 | let inner_meta = match nested { 138 | syn::NestedMeta::Meta(inner_meta) => inner_meta, 139 | _ => return false, 140 | }; 141 | let path = match inner_meta { 142 | syn::Meta::Path(path) => path, 143 | _ => return false, 144 | }; 145 | path.is_ident("flatten") 146 | }) 147 | .next() 148 | .unwrap_or(false) 149 | } 150 | 151 | #[derive(Debug)] 152 | struct NameVal(String); 153 | 154 | impl Parse for NameVal { 155 | fn parse(input: ParseStream) -> syn::Result { 156 | #[derive(PartialEq, Eq, Debug)] 157 | enum Match { 158 | NameToken, 159 | PunctEq, 160 | LitVal, 161 | } 162 | let mut state = Match::NameToken; 163 | let result = input.step(|cursor| { 164 | let mut rest = *cursor; 165 | while let Some((tt, next)) = rest.token_tree() { 166 | match tt { 167 | TokenTree::Ident(ident) if ident == "name" && state == Match::NameToken => { 168 | state = Match::PunctEq; 169 | } 170 | TokenTree::Punct(punct) 171 | if punct.as_char() == '=' && state == Match::PunctEq => 172 | { 173 | state = Match::LitVal; 174 | } 175 | TokenTree::Literal(lit) if state == Match::LitVal => { 176 | return Ok((lit.to_string().replace("\"", ""), Cursor::empty())); 177 | } 178 | _ => { 179 | // on first incorrect token reset 180 | state = Match::NameToken; 181 | } 182 | } 183 | rest = next; 184 | } 185 | Err(cursor.error("End reached")) 186 | }); 187 | result.map(Self).map_err(|_| input.error("Not found")) 188 | } 189 | } 190 | -------------------------------------------------------------------------------- /structopt-toml/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "structopt-toml" 3 | version = "0.5.1" 4 | authors = ["dalance@gmail.com"] 5 | repository = "https://github.com/dalance/structopt-toml" 6 | keywords = ["cli", "structopt", "clap", "derive"] 7 | categories = ["command-line-interface"] 8 | license = "MIT OR Apache-2.0" 9 | readme = "../README.md" 10 | description = "An default value loader from TOML for structopt" 11 | build = "build.rs" 12 | edition = "2018" 13 | 14 | [badges] 15 | travis-ci = { repository = "dalance/structopt-toml" } 16 | codecov = { repository = "dalance/structopt-toml", branch = "master", service = "github" } 17 | 18 | [features] 19 | default = ["clap/default", "structopt/default"] 20 | 21 | [dependencies] 22 | clap = { version = "2.33.0", default-features = false } 23 | anyhow = "1.0.42" 24 | toml = "0.5.6" 25 | serde = "1.0.104" 26 | serde_derive = "1.0.104" 27 | structopt = { version = "0.3.11", default-features = false } 28 | structopt-toml-derive = { version = "^0.5.1", path = "../structopt-toml-derive" } 29 | 30 | [build-dependencies] 31 | skeptic = "0.13" 32 | 33 | [dev-dependencies] 34 | skeptic = "0.13" 35 | 36 | [package.metadata.release] 37 | pre-release-replacements = [ 38 | {file = "../README.md", search = "structopt-toml = \"[a-z0-9\\.-]+\"", replace = "structopt-toml = \"{{version}}\""}, 39 | ] 40 | -------------------------------------------------------------------------------- /structopt-toml/build.rs: -------------------------------------------------------------------------------- 1 | use std::path::PathBuf; 2 | 3 | fn main() { 4 | let path = PathBuf::from("../README.md"); 5 | if path.exists() { 6 | skeptic::generate_doc_tests(&[path]); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /structopt-toml/examples/example.rs: -------------------------------------------------------------------------------- 1 | use serde_derive::Deserialize; 2 | use structopt::StructOpt; 3 | use structopt_toml::StructOptToml; 4 | 5 | #[derive(Debug, Deserialize, StructOpt, StructOptToml)] 6 | #[serde(default)] 7 | struct Opt { 8 | #[structopt(default_value = "0", short = "a")] 9 | a: i32, 10 | #[structopt(default_value = "0", short = "b")] 11 | b: i32, 12 | } 13 | 14 | fn main() { 15 | let toml_str = r#" 16 | a = 10 17 | "#; 18 | let opt = Opt::from_args_with_toml(toml_str).expect("toml parse failed"); 19 | println!("a:{}", opt.a); 20 | println!("b:{}", opt.b); 21 | } 22 | -------------------------------------------------------------------------------- /structopt-toml/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! `structopt-toml` is an default value loader from TOML for structopt. 2 | //! 3 | //! ## Examples 4 | //! 5 | //! The following example show a quick example of `structopt-toml`. 6 | //! 7 | //! If `derive(Deserialize)`, `derive(StructOptToml)` and `serde(default)` are added to the struct 8 | //! with `derive(StructOpt)`, some functions like `from_args_with_toml` can be used. 9 | //! 10 | //! ``` 11 | //! use serde_derive::Deserialize; 12 | //! use structopt::StructOpt; 13 | //! use structopt_toml::StructOptToml; 14 | //! 15 | //! #[derive(Debug, Deserialize, StructOpt, StructOptToml)] 16 | //! #[serde(default)] 17 | //! struct Opt { 18 | //! #[structopt(default_value = "0", short = "a")] a: i32, 19 | //! #[structopt(default_value = "0", short = "b")] b: i32, 20 | //! } 21 | //! 22 | //! let toml_str = r#" 23 | //! a = 10 24 | //! "#; 25 | //! let opt = Opt::from_args_with_toml(toml_str).expect("toml parse failed"); 26 | //! println!("a:{}", opt.a); 27 | //! println!("b:{}", opt.b); 28 | //! ``` 29 | //! 30 | //! The execution result of the above example is below. 31 | //! 32 | //! ```ignore 33 | //! $ ./example 34 | //! a:10 // value from TOML string 35 | //! b:0 // value from default_value of structopt 36 | //! 37 | //! $ ./example -a 20 38 | //! a:20 // value from command line argument 39 | //! b:0 40 | //! ``` 41 | 42 | extern crate anyhow; 43 | extern crate clap as _clap; 44 | extern crate serde as _serde; 45 | extern crate structopt as _structopt; 46 | extern crate toml as _toml; 47 | 48 | #[allow(unused_imports)] 49 | #[macro_use] 50 | extern crate structopt_toml_derive; 51 | 52 | #[doc(hidden)] 53 | pub use structopt_toml_derive::*; 54 | 55 | use std::ffi::OsString; 56 | 57 | /// Re-export of clap 58 | pub mod clap { 59 | pub use _clap::*; 60 | } 61 | /// Re-export of serde 62 | pub mod serde { 63 | pub use _serde::*; 64 | } 65 | /// Re-export of structopt 66 | pub mod structopt { 67 | pub use _structopt::*; 68 | } 69 | 70 | pub trait StructOptToml { 71 | /// Merge the struct from TOML and the struct from args 72 | fn merge<'a>(from_toml: Self, from_args: Self, args: &_clap::ArgMatches) -> Self 73 | where 74 | Self: Sized, 75 | Self: _structopt::StructOpt, 76 | Self: _serde::de::Deserialize<'a>; 77 | 78 | /// Creates the struct from `clap::ArgMatches` with initial values from TOML. 79 | fn from_clap_with_toml<'a>( 80 | toml_str: &'a str, 81 | args: &_clap::ArgMatches, 82 | ) -> Result 83 | where 84 | Self: Sized, 85 | Self: _structopt::StructOpt, 86 | Self: _serde::de::Deserialize<'a>, 87 | { 88 | let from_args: Self = _structopt::StructOpt::from_clap(args); 89 | let from_toml: Self = _toml::from_str(toml_str)?; 90 | Ok(Self::merge(from_toml, from_args, args)) 91 | } 92 | 93 | /// Creates the struct from command line arguments with initial values from TOML. 94 | fn from_args_with_toml<'a>(toml_str: &'a str) -> Result 95 | where 96 | Self: Sized, 97 | Self: _structopt::StructOpt, 98 | Self: _serde::de::Deserialize<'a>, 99 | { 100 | let clap = Self::clap(); 101 | let args = clap.get_matches(); 102 | Self::from_clap_with_toml(toml_str, &args) 103 | } 104 | 105 | /// Creates the struct from iterator with initial values from TOML. 106 | fn from_iter_with_toml<'a, I>(toml_str: &'a str, iter: I) -> Result 107 | where 108 | Self: Sized, 109 | Self: _structopt::StructOpt, 110 | Self: _serde::de::Deserialize<'a>, 111 | I: IntoIterator, 112 | I::Item: Into + Clone, 113 | { 114 | let clap = Self::clap(); 115 | let args = clap.get_matches_from(iter); 116 | Self::from_clap_with_toml(toml_str, &args) 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /structopt-toml/tests/skeptic.rs: -------------------------------------------------------------------------------- 1 | include!(concat!(env!("OUT_DIR"), "/skeptic-tests.rs")); 2 | -------------------------------------------------------------------------------- /structopt-toml/tests/test.rs: -------------------------------------------------------------------------------- 1 | use serde_derive::Deserialize; 2 | use structopt::StructOpt; 3 | use structopt_toml::StructOptToml; 4 | 5 | #[derive(Debug, Deserialize, StructOpt, StructOptToml)] 6 | #[serde(default)] 7 | struct Test { 8 | #[structopt(default_value = "0", long = "a0")] 9 | a0: i32, 10 | #[structopt(default_value = "1", long = "a1")] 11 | a1: i32, 12 | #[structopt(default_value = "2", long = "a2")] 13 | a2: i32, 14 | #[structopt(default_value = "3", long = "a3")] 15 | a3: i32, 16 | 17 | #[structopt(name = "B0", default_value = "10", long = "b0")] 18 | b0: i32, 19 | #[structopt(name = "B1", default_value = "11", long = "b1")] 20 | b1: i32, 21 | #[structopt(name = "B2", default_value = "12", long = "b2")] 22 | b2: i32, 23 | #[structopt(name = "B3", default_value = "13", long = "b3")] 24 | b3: i32, 25 | 26 | #[structopt(long = "c0")] 27 | c0: Option, 28 | #[structopt(long = "c1")] 29 | c1: Option, 30 | #[structopt(long = "c2")] 31 | c2: Option, 32 | #[structopt(long = "c3")] 33 | c3: Option, 34 | 35 | #[structopt(long = "d0")] 36 | d0: Vec, 37 | #[structopt(long = "d1")] 38 | d1: Vec, 39 | #[structopt(long = "d2")] 40 | d2: Vec, 41 | #[structopt(long = "d3")] 42 | d3: Vec, 43 | 44 | #[structopt(long = "quiet")] 45 | quiet: bool, 46 | } 47 | 48 | #[test] 49 | fn test() { 50 | let toml_str = r#" 51 | a2 = 102 52 | a3 = 103 53 | b2 = 112 54 | b3 = 113 55 | c2 = 122 56 | c3 = 123 57 | d2 = [132] 58 | d3 = [133] 59 | "#; 60 | let args = vec![ 61 | "test", "--a1", "201", "--a3", "203", "--b1", "211", "--b3", "213", "--c1", "221", "--c3", 62 | "223", "--d1", "231", "--d3", "233", 63 | ]; 64 | let test = Test::from_iter_with_toml(toml_str, args.iter()).unwrap(); 65 | assert_eq!(test.a0, 0); 66 | assert_eq!(test.a1, 201); 67 | assert_eq!(test.a2, 102); 68 | assert_eq!(test.a3, 203); 69 | assert_eq!(test.b0, 10); 70 | assert_eq!(test.b1, 211); 71 | assert_eq!(test.b2, 112); 72 | assert_eq!(test.b3, 213); 73 | assert_eq!(test.c0, None); 74 | assert_eq!(test.c1, Some(221)); 75 | assert_eq!(test.c2, Some(122)); 76 | assert_eq!(test.c3, Some(223)); 77 | assert_eq!(test.d0, vec![]); 78 | assert_eq!(test.d1, vec![231]); 79 | assert_eq!(test.d2, vec![132]); 80 | assert_eq!(test.d3, vec![233]); 81 | } 82 | 83 | static POSSIBLE_VALUES: &[&str] = &["one", "two"]; 84 | 85 | #[derive(Debug, Deserialize, StructOpt, StructOptToml)] 86 | #[serde(default)] 87 | struct Bar { 88 | #[structopt(possible_values = POSSIBLE_VALUES, name = "bar")] 89 | val: Option, 90 | } 91 | 92 | #[test] 93 | fn test_args_with_other_attributes() { 94 | let toml_str = r#" 95 | bar = "one" 96 | "#; 97 | let test = Bar::from_args_with_toml(toml_str); 98 | match dbg!(test) { 99 | Err(_) => assert!(false), 100 | _ => assert!(true), 101 | } 102 | } 103 | 104 | #[derive(Debug, Deserialize, StructOpt, StructOptToml)] 105 | #[serde(default)] 106 | struct Outer { 107 | #[structopt(long = "one", default_value = "1")] 108 | one: u32, 109 | #[structopt(flatten)] 110 | two: Inner, 111 | } 112 | 113 | #[derive(Debug, Deserialize, StructOpt, StructOptToml)] 114 | struct Inner { 115 | #[structopt(long = "three", default_value = "1")] 116 | three: u32, 117 | #[structopt(long = "four", default_value = "1")] 118 | four: u32, 119 | } 120 | 121 | #[test] 122 | fn test_flatten_args() { 123 | let toml_str = r#" 124 | one = 2 125 | two.three = 2 126 | two.four = 2 127 | "#; 128 | let args = vec!["test", "--four", "3"]; 129 | let test = Outer::from_iter_with_toml(toml_str, args.iter()).unwrap(); 130 | assert_eq!(test.one, 2); 131 | assert_eq!(test.two.three, 2); 132 | assert_eq!(test.two.four, 3); 133 | } 134 | 135 | #[test] 136 | fn test_toml_failed() { 137 | let toml_str = r#" 138 | a2 = "aaa" 139 | a3 = [102] 140 | c3 = 123 141 | d2 = 132 142 | "#; 143 | let args = vec!["test"]; 144 | let test = Test::from_iter_with_toml(toml_str, args.iter()); 145 | match test { 146 | Err(_) => assert!(true), 147 | _ => assert!(false), 148 | } 149 | } 150 | 151 | #[test] 152 | fn test_toml_args() { 153 | let toml_str = r#" 154 | a2 = 102 155 | a3 = 103 156 | b2 = 112 157 | b3 = 113 158 | c2 = 122 159 | c3 = 123 160 | d2 = [132] 161 | d3 = [133] 162 | "#; 163 | let test = Test::from_args_with_toml(toml_str).unwrap(); 164 | assert_eq!(test.a0, 0); 165 | assert_eq!(test.a1, 1); 166 | assert_eq!(test.a2, 102); 167 | assert_eq!(test.a3, 103); 168 | assert_eq!(test.b0, 10); 169 | assert_eq!(test.b1, 11); 170 | assert_eq!(test.b2, 112); 171 | assert_eq!(test.b3, 113); 172 | assert_eq!(test.c0, None); 173 | assert_eq!(test.c1, None); 174 | assert_eq!(test.c2, Some(122)); 175 | assert_eq!(test.c3, Some(123)); 176 | assert_eq!(test.d0, vec![]); 177 | assert_eq!(test.d1, vec![]); 178 | assert_eq!(test.d2, vec![132]); 179 | assert_eq!(test.d3, vec![133]); 180 | } 181 | --------------------------------------------------------------------------------