├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── examples ├── README.md ├── after_help.rs ├── at_least_two.rs ├── basic.rs ├── deny_missing_docs.rs ├── doc_comments.rs ├── enum_in_args.rs ├── enum_in_args_with_strum.rs ├── enum_tuple.rs ├── env.rs ├── example.rs ├── flatten.rs ├── gen_completions.rs ├── git.rs ├── group.rs ├── keyvalue.rs ├── negative_flag.rs ├── no_version.rs ├── rename_all.rs ├── required_if.rs ├── skip.rs ├── subcommand_aliases.rs └── true_or_false.rs ├── link-check-headers.json ├── src └── lib.rs ├── structopt-derive ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT └── src │ ├── attrs.rs │ ├── doc_comments.rs │ ├── lib.rs │ ├── parse.rs │ ├── spanned.rs │ └── ty.rs └── tests ├── argument_naming.rs ├── arguments.rs ├── author_version_about.rs ├── custom-string-parsers.rs ├── default_value.rs ├── deny-warnings.rs ├── doc-comments-help.rs ├── explicit_name_no_renaming.rs ├── flags.rs ├── flatten.rs ├── generics.rs ├── issues.rs ├── macro-errors.rs ├── nested-subcommands.rs ├── non_literal_attributes.rs ├── options.rs ├── privacy.rs ├── raw_bool_literal.rs ├── raw_idents.rs ├── regressions.rs ├── rename_all_env.rs ├── skip.rs ├── special_types.rs ├── subcommands.rs ├── ui ├── bool_default_value.rs ├── bool_default_value.stderr ├── bool_required.rs ├── bool_required.stderr ├── enum_flatten.rs ├── enum_flatten.stderr ├── external_subcommand_wrong_type.rs ├── external_subcommand_wrong_type.stderr ├── flatten_and_methods.rs ├── flatten_and_methods.stderr ├── flatten_and_parse.rs ├── flatten_and_parse.stderr ├── multiple_external_subcommand.rs ├── multiple_external_subcommand.stderr ├── non_existent_attr.rs ├── non_existent_attr.stderr ├── opt_opt_nonpositional.rs ├── opt_opt_nonpositional.stderr ├── opt_vec_nonpositional.rs ├── opt_vec_nonpositional.stderr ├── option_default_value.rs ├── option_default_value.stderr ├── option_required.rs ├── option_required.stderr ├── parse_empty_try_from_os.rs ├── parse_empty_try_from_os.stderr ├── parse_function_is_not_path.rs ├── parse_function_is_not_path.stderr ├── parse_literal_spec.rs ├── parse_literal_spec.stderr ├── parse_not_zero_args.rs ├── parse_not_zero_args.stderr ├── positional_bool.rs ├── positional_bool.stderr ├── raw.rs ├── raw.stderr ├── rename_all_wrong_casing.rs ├── rename_all_wrong_casing.stderr ├── skip_flatten.rs ├── skip_flatten.stderr ├── skip_subcommand.rs ├── skip_subcommand.stderr ├── skip_with_other_options.rs ├── skip_with_other_options.stderr ├── skip_without_default.rs ├── skip_without_default.stderr ├── struct_parse.rs ├── struct_parse.stderr ├── struct_subcommand.rs ├── struct_subcommand.stderr ├── structopt_empty_attr.rs ├── structopt_empty_attr.stderr ├── structopt_name_value_attr.rs ├── structopt_name_value_attr.stderr ├── subcommand_and_flatten.rs ├── subcommand_and_flatten.stderr ├── subcommand_and_methods.rs ├── subcommand_and_methods.stderr ├── subcommand_and_parse.rs ├── subcommand_and_parse.stderr ├── subcommand_opt_opt.rs ├── subcommand_opt_opt.stderr ├── subcommand_opt_vec.rs ├── subcommand_opt_vec.stderr ├── tuple_struct.rs └── tuple_struct.stderr ├── utils.rs └── we_need_syn_full.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | *~ 4 | expanded.rs 5 | 6 | .idea/ 7 | .vscode/ 8 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | if: type != push OR branch = master 2 | 3 | language: rust 4 | matrix: 5 | include: 6 | - rust: stable 7 | name: check if `cargo fmt --all` is applied 8 | before_script: rustup component add rustfmt-preview 9 | script: cargo fmt --all -- --check 10 | 11 | - language: node_js 12 | node_js: node 13 | name: check links 14 | install: npm install -g markdown-link-check 15 | script: 16 | - markdown-link-check -c link-check-headers.json README.md 17 | - markdown-link-check -c link-check-headers.json CHANGELOG.md 18 | - markdown-link-check -c link-check-headers.json examples/README.md 19 | 20 | - rust: stable 21 | name: clippy 22 | before_script: rustup component add clippy 23 | script: cargo clippy --all -- -D warnings 24 | 25 | - rust: 1.46.0 26 | - rust: stable 27 | - rust: beta 28 | - rust: nightly 29 | 30 | script: 31 | - cargo test 32 | 33 | jobs: 34 | allow_failures: 35 | - name: clippy 36 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "structopt" 3 | version = "0.3.26" 4 | edition = "2018" 5 | authors = ["Guillaume Pinot ", "others"] 6 | description = "Parse command line argument by defining a struct." 7 | documentation = "https://docs.rs/structopt" 8 | repository = "https://github.com/TeXitoi/structopt" 9 | keywords = ["clap", "cli", "derive", "docopt"] 10 | categories = ["command-line-interface"] 11 | license = "Apache-2.0 OR MIT" 12 | readme = "README.md" 13 | 14 | [features] 15 | default = ["clap/default"] 16 | suggestions = ["clap/suggestions"] 17 | color = ["clap/color"] 18 | wrap_help = ["clap/wrap_help"] 19 | yaml = ["clap/yaml"] 20 | lints = ["clap/lints"] 21 | debug = ["clap/debug"] 22 | no_cargo = ["clap/no_cargo"] 23 | doc = ["clap/doc"] 24 | paw = ["structopt-derive/paw", "paw_dep"] 25 | 26 | [badges] 27 | travis-ci = { repository = "TeXitoi/structopt" } 28 | 29 | [dependencies] 30 | clap = { version = "2.33", default-features = false } 31 | structopt-derive = { path = "structopt-derive", version = "=0.4.18" } 32 | lazy_static = "1.4.0" 33 | paw_dep = { version = "1", optional = true, package = "paw" } 34 | 35 | [dev-dependencies] 36 | trybuild = { version = "1.0.5", features = ["diff"] } 37 | rustversion = "1" 38 | strum = { version = "0.21", features = ["derive"] } 39 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Guillaume Pinot (@TeXitoi) 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 2 | 3 | [![Build status](https://travis-ci.com/TeXitoi/structopt.svg?branch=master)](https://app.travis-ci.com/github/TeXitoi/structopt) [![](https://img.shields.io/crates/v/structopt.svg)](https://crates.io/crates/structopt) [![](https://docs.rs/structopt/badge.svg)](https://docs.rs/structopt) 4 | [![unsafe forbidden](https://img.shields.io/badge/unsafe-forbidden-success.svg)](https://github.com/rust-secure-code/safety-dance/) 5 | 6 | Parse command line arguments by defining a struct. It combines [clap](https://crates.io/crates/clap) with custom derive. 7 | 8 | ## Maintenance 9 | 10 | As clap v3 is now out, and the structopt features are integrated into (almost as-is), structopt is now in maintenance mode: no new feature will be added. 11 | 12 | Bugs will be fixed, and documentation improvements will be accepted. 13 | 14 | See the [structopt -> clap migration guide](https://github.com/clap-rs/clap/blob/master/CHANGELOG.md#migrating) 15 | 16 | ## Documentation 17 | 18 | Find it on [Docs.rs](https://docs.rs/structopt). You can also check the [examples](https://github.com/TeXitoi/structopt/tree/master/examples) and the [changelog](https://github.com/TeXitoi/structopt/blob/master/CHANGELOG.md). 19 | 20 | ## Example 21 | 22 | Add `structopt` to your dependencies of your `Cargo.toml`: 23 | ```toml 24 | [dependencies] 25 | structopt = "0.3" 26 | ``` 27 | 28 | And then, in your rust file: 29 | ```rust 30 | use std::path::PathBuf; 31 | use structopt::StructOpt; 32 | 33 | /// A basic example 34 | #[derive(StructOpt, Debug)] 35 | #[structopt(name = "basic")] 36 | struct Opt { 37 | // A flag, true if used in the command line. Note doc comment will 38 | // be used for the help message of the flag. The name of the 39 | // argument will be, by default, based on the name of the field. 40 | /// Activate debug mode 41 | #[structopt(short, long)] 42 | debug: bool, 43 | 44 | // The number of occurrences of the `v/verbose` flag 45 | /// Verbose mode (-v, -vv, -vvv, etc.) 46 | #[structopt(short, long, parse(from_occurrences))] 47 | verbose: u8, 48 | 49 | /// Set speed 50 | #[structopt(short, long, default_value = "42")] 51 | speed: f64, 52 | 53 | /// Output file 54 | #[structopt(short, long, parse(from_os_str))] 55 | output: PathBuf, 56 | 57 | // the long option will be translated by default to kebab case, 58 | // i.e. `--nb-cars`. 59 | /// Number of cars 60 | #[structopt(short = "c", long)] 61 | nb_cars: Option, 62 | 63 | /// admin_level to consider 64 | #[structopt(short, long)] 65 | level: Vec, 66 | 67 | /// Files to process 68 | #[structopt(name = "FILE", parse(from_os_str))] 69 | files: Vec, 70 | } 71 | 72 | fn main() { 73 | let opt = Opt::from_args(); 74 | println!("{:#?}", opt); 75 | } 76 | ``` 77 | 78 | Using this example: 79 | ``` 80 | $ ./basic 81 | error: The following required arguments were not provided: 82 | --output 83 | 84 | USAGE: 85 | basic --output --speed 86 | 87 | For more information try --help 88 | $ ./basic --help 89 | basic 0.3.0 90 | Guillaume Pinot , others 91 | A basic example 92 | 93 | USAGE: 94 | basic [FLAGS] [OPTIONS] --output [--] [file]... 95 | 96 | FLAGS: 97 | -d, --debug Activate debug mode 98 | -h, --help Prints help information 99 | -V, --version Prints version information 100 | -v, --verbose Verbose mode (-v, -vv, -vvv, etc.) 101 | 102 | OPTIONS: 103 | -l, --level ... admin_level to consider 104 | -c, --nb-cars Number of cars 105 | -o, --output Output file 106 | -s, --speed Set speed [default: 42] 107 | 108 | ARGS: 109 | ... Files to process 110 | $ ./basic -o foo.txt 111 | Opt { 112 | debug: false, 113 | verbose: 0, 114 | speed: 42.0, 115 | output: "foo.txt", 116 | nb_cars: None, 117 | level: [], 118 | files: [], 119 | } 120 | $ ./basic -o foo.txt -dvvvs 1337 -l alice -l bob --nb-cars 4 bar.txt baz.txt 121 | Opt { 122 | debug: true, 123 | verbose: 3, 124 | speed: 1337.0, 125 | output: "foo.txt", 126 | nb_cars: Some( 127 | 4, 128 | ), 129 | level: [ 130 | "alice", 131 | "bob", 132 | ], 133 | files: [ 134 | "bar.txt", 135 | "baz.txt", 136 | ], 137 | } 138 | ``` 139 | 140 | ## StructOpt rustc version policy 141 | 142 | - Minimum rustc version modification must be specified in the [changelog](https://github.com/TeXitoi/structopt/blob/master/CHANGELOG.md) and in the [travis configuration](https://github.com/TeXitoi/structopt/blob/master/.travis.yml). 143 | - Contributors can increment minimum rustc version without any justification if the new version is required by the latest version of one of StructOpt's dependencies (`cargo update` will not fail on StructOpt). 144 | - Contributors can increment minimum rustc version if the library user experience is improved. 145 | 146 | ## License 147 | 148 | Licensed under either of 149 | 150 | - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or ) 151 | - MIT license ([LICENSE-MIT](LICENSE-MIT) or ) 152 | 153 | at your option. 154 | 155 | ### Contribution 156 | 157 | Unless you explicitly state otherwise, any contribution intentionally submitted 158 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be 159 | dual licensed as above, without any additional terms or conditions. 160 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # Collection of examples "how to use `structopt`" 2 | 3 | ### [Help on the bottom](after_help.rs) 4 | 5 | How to append a postscript to the help message generated. 6 | 7 | ### [At least N](at_least_two.rs) 8 | 9 | How to require presence of at least N values, like `val1 val2 ... valN ... valM`. 10 | 11 | ### [Basic](basic.rs) 12 | 13 | A basic example how to use `structopt`. 14 | 15 | ### [Deny missing docs](deny_missing_docs.rs) 16 | 17 | **This is not an example but a test**, it should be moved to `tests` folder 18 | as soon as [this](https://github.com/rust-lang/rust/issues/24584) is fixed (if ever). 19 | 20 | ### [Doc comments](doc_comments.rs) 21 | 22 | How to use doc comments in place of `help/long_help`. 23 | 24 | ### [Enums as arguments](enum_in_args.rs) 25 | 26 | How to use `arg_enum!` with `StructOpt`. 27 | 28 | ### [Arguments of subcommands in separate `struct`](enum_tuple.rs) 29 | 30 | How to extract subcommands' args into external structs. 31 | 32 | ### [Environment variables](env.rs) 33 | 34 | How to use environment variable fallback and how it interacts with `default_value`. 35 | 36 | ### [Advanced](example.rs) 37 | 38 | Somewhat complex example of usage of `structopt`. 39 | 40 | ### [Flatten](flatten.rs) 41 | 42 | How to use `#[structopt(flatten)]` 43 | 44 | ### [`bash` completions](gen_completions.rs) 45 | 46 | Generating `bash` completions with `structopt`. 47 | 48 | ### [Git](git.rs) 49 | 50 | Pseudo-`git` example, shows how to use subcommands and how to document them. 51 | 52 | ### [Groups](group.rs) 53 | 54 | Using `clap::Arg::group` with `structopt`. 55 | 56 | ### [`key=value` pairs](keyvalue.rs) 57 | 58 | How to parse `key=value` pairs. 59 | 60 | ### [`--no-*` flags](negative_flag.rs) 61 | 62 | How to add `no-thing` flag which is `true` by default and `false` if passed. 63 | 64 | ### [No version](no_version.rs) 65 | 66 | How to completely remove version. 67 | 68 | ### [Rename all](rename_all.rs) 69 | 70 | How `#[structopt(rename_all)]` works. 71 | 72 | ### [Required If](required_if.rs) 73 | 74 | How to use `#[structopt(required_if)]`. 75 | 76 | ### [Skip](skip.rs) 77 | 78 | How to use `#[structopt(skip)]`. 79 | 80 | ### [Aliases](subcommand_aliases.rs) 81 | 82 | How to use aliases 83 | 84 | ### [`true` or `false`](true_or_false.rs) 85 | 86 | How to express "`"true"` or `"false"` argument. 87 | -------------------------------------------------------------------------------- /examples/after_help.rs: -------------------------------------------------------------------------------- 1 | //! How to append a postscript to the help message generated. 2 | //! 3 | //! Running this example with --help prints this message: 4 | //! ----------------------------------------------------- 5 | //! structopt 0.3.25 6 | //! I am a program and I do things. 7 | //! 8 | //! Sometimes they even work. 9 | //! 10 | //! USAGE: 11 | //! after_help [FLAGS] 12 | //! 13 | //! FLAGS: 14 | //! -d 15 | //! Release the dragon 16 | //! 17 | //! -h, --help 18 | //! Prints help information 19 | //! 20 | //! -V, --version 21 | //! Prints version information 22 | //! 23 | //! 24 | //! Beware `-d`, dragons be here 25 | //! ----------------------------------------------------- 26 | 27 | use structopt::StructOpt; 28 | 29 | /// I am a program and I do things. 30 | /// 31 | /// Sometimes they even work. 32 | #[derive(StructOpt, Debug)] 33 | #[structopt(after_help = "Beware `-d`, dragons be here")] 34 | struct Opt { 35 | /// Release the dragon. 36 | #[structopt(short)] 37 | dragon: bool, 38 | } 39 | 40 | fn main() { 41 | let opt = Opt::from_args(); 42 | println!("{:?}", opt); 43 | } 44 | -------------------------------------------------------------------------------- /examples/at_least_two.rs: -------------------------------------------------------------------------------- 1 | //! How to require presence of at least N values, 2 | //! like `val1 val2 ... valN ... valM`. 3 | //! 4 | //! Running this example with --help prints this message: 5 | //! ----------------------------------------------------- 6 | //! structopt 0.3.25 7 | //! 8 | //! USAGE: 9 | //! at_least_two ... 10 | //! 11 | //! FLAGS: 12 | //! -h, --help Prints help information 13 | //! -V, --version Prints version information 14 | //! 15 | //! ARGS: 16 | //! ... 17 | //! ----------------------------------------------------- 18 | 19 | use structopt::StructOpt; 20 | 21 | #[derive(StructOpt, Debug)] 22 | struct Opt { 23 | #[structopt(required = true, min_values = 2)] 24 | foos: Vec, 25 | } 26 | 27 | fn main() { 28 | let opt = Opt::from_args(); 29 | println!("{:?}", opt); 30 | } 31 | -------------------------------------------------------------------------------- /examples/basic.rs: -------------------------------------------------------------------------------- 1 | //! A somewhat comprehensive example of a typical `StructOpt` usage.use 2 | //! 3 | //! Running this example with --help prints this message: 4 | //! ----------------------------------------------------- 5 | //! basic 0.3.25 6 | //! A basic example 7 | //! 8 | //! USAGE: 9 | //! basic [FLAGS] [OPTIONS] --output [--] [FILE]... 10 | //! 11 | //! FLAGS: 12 | //! -d, --debug Activate debug mode 13 | //! -h, --help Prints help information 14 | //! -V, --version Prints version information 15 | //! -v, --verbose Verbose mode (-v, -vv, -vvv, etc.) 16 | //! 17 | //! OPTIONS: 18 | //! -l, --level ... admin_level to consider 19 | //! -c, --nb-cars Number of cars 20 | //! -o, --output Output file 21 | //! -s, --speed Set speed [default: 42] 22 | //! 23 | //! ARGS: 24 | //! ... Files to process 25 | //! ----------------------------------------------------- 26 | 27 | use std::path::PathBuf; 28 | use structopt::StructOpt; 29 | 30 | /// A basic example 31 | #[derive(StructOpt, Debug)] 32 | #[structopt(name = "basic")] 33 | struct Opt { 34 | // A flag, true if used in the command line. Note doc comment will 35 | // be used for the help message of the flag. The name of the 36 | // argument will be, by default, based on the name of the field. 37 | /// Activate debug mode 38 | #[structopt(short, long)] 39 | debug: bool, 40 | 41 | // The number of occurrences of the `v/verbose` flag 42 | /// Verbose mode (-v, -vv, -vvv, etc.) 43 | #[structopt(short, long, parse(from_occurrences))] 44 | verbose: u8, 45 | 46 | /// Set speed 47 | #[structopt(short, long, default_value = "42")] 48 | speed: f64, 49 | 50 | /// Output file 51 | #[structopt(short, long, parse(from_os_str))] 52 | output: PathBuf, 53 | 54 | // the long option will be translated by default to kebab case, 55 | // i.e. `--nb-cars`. 56 | /// Number of cars 57 | #[structopt(short = "c", long)] 58 | nb_cars: Option, 59 | 60 | /// admin_level to consider 61 | #[structopt(short, long)] 62 | level: Vec, 63 | 64 | /// Files to process 65 | #[structopt(name = "FILE", parse(from_os_str))] 66 | files: Vec, 67 | } 68 | 69 | fn main() { 70 | let opt = Opt::from_args(); 71 | println!("{:#?}", opt); 72 | } 73 | -------------------------------------------------------------------------------- /examples/deny_missing_docs.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | // This should be in tests but it will not work until 10 | // https://github.com/rust-lang/rust/issues/24584 is fixed 11 | 12 | //! A test to check that structopt compiles with deny(missing_docs) 13 | //! 14 | //! Running this example with --help prints this message: 15 | //! ----------------------------------------------------- 16 | //! structopt 0.3.25 17 | //! Some subcommands 18 | //! 19 | //! USAGE: 20 | //! deny_missing_docs [FLAGS] [SUBCOMMAND] 21 | //! 22 | //! FLAGS: 23 | //! -h, --help Prints help information 24 | //! -V, --version Prints version information 25 | //! -v 26 | //! 27 | //! SUBCOMMANDS: 28 | //! a command A 29 | //! b command B 30 | //! c command C 31 | //! help Prints this message or the help of the given subcommand(s) 32 | //! ----------------------------------------------------- 33 | 34 | #![deny(missing_docs)] 35 | 36 | use structopt::StructOpt; 37 | 38 | /// The options 39 | #[derive(StructOpt, Debug, PartialEq)] 40 | pub struct Opt { 41 | #[structopt(short)] 42 | verbose: bool, 43 | #[structopt(subcommand)] 44 | cmd: Option, 45 | } 46 | 47 | /// Some subcommands 48 | #[derive(StructOpt, Debug, PartialEq)] 49 | pub enum Cmd { 50 | /// command A 51 | A, 52 | /// command B 53 | B { 54 | /// Alice? 55 | #[structopt(short)] 56 | alice: bool, 57 | }, 58 | /// command C 59 | C(COpt), 60 | } 61 | 62 | /// The options for C 63 | #[derive(StructOpt, Debug, PartialEq)] 64 | pub struct COpt { 65 | #[structopt(short)] 66 | bob: bool, 67 | } 68 | 69 | fn main() { 70 | println!("{:?}", Opt::from_args()); 71 | } 72 | -------------------------------------------------------------------------------- /examples/doc_comments.rs: -------------------------------------------------------------------------------- 1 | //! How to use doc comments in place of `help/long_help`. 2 | //! 3 | //! Running this example with --help prints this message: 4 | //! ----------------------------------------------------- 5 | //! basic 0.3.25 6 | //! A basic example for the usage of doc comments as replacement of the arguments `help`, `long_help`, `about` and 7 | //! `long_about` 8 | //! 9 | //! USAGE: 10 | //! doc_comments [FLAGS] 11 | //! 12 | //! FLAGS: 13 | //! -f, --first-flag 14 | //! Just use doc comments to replace `help`, `long_help`, `about` or `long_about` input 15 | //! 16 | //! -h, --help 17 | //! Prints help information 18 | //! 19 | //! -s, --second-flag 20 | //! Split between `help` and `long_help`. 21 | //! 22 | //! In the previous case structopt is going to present the whole comment both as text for the `help` and the 23 | //! `long_help` argument. 24 | //! 25 | //! But if the doc comment is formatted like this example -- with an empty second line splitting the heading and 26 | //! the rest of the comment -- only the first line is used as `help` argument. The `long_help` argument will 27 | //! still contain the whole comment. 28 | //! 29 | //! ## Attention 30 | //! 31 | //! Any formatting next to empty lines that could be used inside a doc comment is currently not preserved. If 32 | //! lists or other well formatted content is required it is necessary to use the related structopt argument with 33 | //! a raw string as shown on the `third_flag` description. 34 | //! -t, --third-flag 35 | //! This is a raw string. 36 | //! 37 | //! It can be used to pass well formatted content (e.g. lists or source 38 | //! code) in the description: 39 | //! 40 | //! - first example list entry 41 | //! - second example list entry 42 | //! 43 | //! -V, --version 44 | //! Prints version information 45 | //! 46 | //! 47 | //! SUBCOMMANDS: 48 | //! first The same rules described previously for flags. Are also true for in regards of sub-commands 49 | //! help Prints this message or the help of the given subcommand(s) 50 | //! second Applicable for both `about` an `help` 51 | //! ----------------------------------------------------- 52 | 53 | use structopt::StructOpt; 54 | 55 | /// A basic example for the usage of doc comments as replacement 56 | /// of the arguments `help`, `long_help`, `about` and `long_about`. 57 | #[derive(StructOpt, Debug)] 58 | #[structopt(name = "basic")] 59 | struct Opt { 60 | /// Just use doc comments to replace `help`, `long_help`, 61 | /// `about` or `long_about` input. 62 | #[structopt(short, long)] 63 | first_flag: bool, 64 | 65 | /// Split between `help` and `long_help`. 66 | /// 67 | /// In the previous case structopt is going to present 68 | /// the whole comment both as text for the `help` and the 69 | /// `long_help` argument. 70 | /// 71 | /// But if the doc comment is formatted like this example 72 | /// -- with an empty second line splitting the heading and 73 | /// the rest of the comment -- only the first line is used 74 | /// as `help` argument. The `long_help` argument will still 75 | /// contain the whole comment. 76 | /// 77 | /// ## Attention 78 | /// 79 | /// Any formatting next to empty lines that could be used 80 | /// inside a doc comment is currently not preserved. If 81 | /// lists or other well formatted content is required it is 82 | /// necessary to use the related structopt argument with a 83 | /// raw string as shown on the `third_flag` description. 84 | #[structopt(short, long)] 85 | second_flag: bool, 86 | 87 | #[structopt( 88 | short, 89 | long, 90 | long_help = r"This is a raw string. 91 | 92 | It can be used to pass well formatted content (e.g. lists or source 93 | code) in the description: 94 | 95 | - first example list entry 96 | - second example list entry 97 | " 98 | )] 99 | third_flag: bool, 100 | 101 | #[structopt(subcommand)] 102 | sub_command: SubCommand, 103 | } 104 | 105 | #[derive(StructOpt, Debug)] 106 | #[structopt()] 107 | enum SubCommand { 108 | /// The same rules described previously for flags. Are 109 | /// also true for in regards of sub-commands. 110 | First, 111 | 112 | /// Applicable for both `about` an `help`. 113 | /// 114 | /// The formatting rules described in the comment of the 115 | /// `second_flag` also apply to the description of 116 | /// sub-commands which is normally given through the `about` 117 | /// and `long_about` arguments. 118 | Second, 119 | } 120 | 121 | fn main() { 122 | let opt = Opt::from_args(); 123 | println!("{:?}", opt); 124 | } 125 | -------------------------------------------------------------------------------- /examples/enum_in_args.rs: -------------------------------------------------------------------------------- 1 | //! How to use `arg_enum!` with `StructOpt`. 2 | //! 3 | //! Running this example with --help prints this message: 4 | //! ----------------------------------------------------- 5 | //! structopt 0.3.25 6 | //! 7 | //! USAGE: 8 | //! enum_in_args 9 | //! 10 | //! FLAGS: 11 | //! -h, --help Prints help information 12 | //! -V, --version Prints version information 13 | //! 14 | //! ARGS: 15 | //! Important argument [possible values: Foo, Bar, FooBar] 16 | //! ----------------------------------------------------- 17 | 18 | use clap::arg_enum; 19 | use structopt::StructOpt; 20 | 21 | arg_enum! { 22 | #[derive(Debug)] 23 | enum Baz { 24 | Foo, 25 | Bar, 26 | FooBar 27 | } 28 | } 29 | 30 | #[derive(StructOpt, Debug)] 31 | struct Opt { 32 | /// Important argument. 33 | #[structopt(possible_values = &Baz::variants(), case_insensitive = true)] 34 | i: Baz, 35 | } 36 | 37 | fn main() { 38 | let opt = Opt::from_args(); 39 | println!("{:?}", opt); 40 | } 41 | -------------------------------------------------------------------------------- /examples/enum_in_args_with_strum.rs: -------------------------------------------------------------------------------- 1 | //! Running this example with --help prints this message: 2 | //! ----------------------------------------------------- 3 | //! structopt 0.3.25 4 | //! 5 | //! USAGE: 6 | //! enum_in_args_with_strum [OPTIONS] 7 | //! 8 | //! FLAGS: 9 | //! -h, --help Prints help information 10 | //! -V, --version Prints version information 11 | //! 12 | //! OPTIONS: 13 | //! --format [default: txt] [possible values: txt, md, html] 14 | //! ----------------------------------------------------- 15 | 16 | use structopt::StructOpt; 17 | use strum::{EnumString, EnumVariantNames, VariantNames}; 18 | 19 | const DEFAULT: &str = "txt"; 20 | 21 | #[derive(StructOpt, Debug)] 22 | struct Opt { 23 | #[structopt( 24 | long, 25 | possible_values = Format::VARIANTS, 26 | case_insensitive = true, 27 | default_value = DEFAULT, 28 | )] 29 | format: Format, 30 | } 31 | 32 | #[derive(EnumString, EnumVariantNames, Debug)] 33 | #[strum(serialize_all = "kebab_case")] 34 | enum Format { 35 | Txt, 36 | Md, 37 | Html, 38 | } 39 | 40 | fn main() { 41 | println!("{:?}", Opt::from_args()); 42 | } 43 | -------------------------------------------------------------------------------- /examples/enum_tuple.rs: -------------------------------------------------------------------------------- 1 | //! How to extract subcommands' args into external structs. 2 | //! 3 | //! Running this example with --help prints this message: 4 | //! ----------------------------------------------------- 5 | //! classify 0.3.25 6 | //! 7 | //! USAGE: 8 | //! enum_tuple 9 | //! 10 | //! FLAGS: 11 | //! -h, --help Prints help information 12 | //! -V, --version Prints version information 13 | //! 14 | //! SUBCOMMANDS: 15 | //! foo 16 | //! help Prints this message or the help of the given subcommand(s) 17 | //! ----------------------------------------------------- 18 | 19 | use structopt::StructOpt; 20 | 21 | #[derive(Debug, StructOpt)] 22 | pub struct Foo { 23 | pub bar: Option, 24 | } 25 | 26 | #[derive(Debug, StructOpt)] 27 | pub enum Command { 28 | #[structopt(name = "foo")] 29 | Foo(Foo), 30 | } 31 | 32 | #[derive(Debug, StructOpt)] 33 | #[structopt(name = "classify")] 34 | pub struct ApplicationArguments { 35 | #[structopt(subcommand)] 36 | pub command: Command, 37 | } 38 | 39 | fn main() { 40 | let opt = ApplicationArguments::from_args(); 41 | println!("{:?}", opt); 42 | } 43 | -------------------------------------------------------------------------------- /examples/env.rs: -------------------------------------------------------------------------------- 1 | //! How to use environment variable fallback an how it 2 | //! interacts with `default_value`. 3 | //! 4 | //! Running this example with --help prints this message: 5 | //! ----------------------------------------------------- 6 | //! env 0.3.25 7 | //! Example for allowing to specify options via environment variables 8 | //! 9 | //! USAGE: 10 | //! env [OPTIONS] --api-url 11 | //! 12 | //! FLAGS: 13 | //! -h, --help Prints help information 14 | //! -V, --version Prints version information 15 | //! 16 | //! OPTIONS: 17 | //! --api-url URL for the API server [env: API_URL=] 18 | //! --retries Number of retries [env: RETRIES=] [default: 5] 19 | //! ----------------------------------------------------- 20 | 21 | use structopt::StructOpt; 22 | 23 | /// Example for allowing to specify options via environment variables. 24 | #[derive(StructOpt, Debug)] 25 | #[structopt(name = "env")] 26 | struct Opt { 27 | // Use `env` to enable specifying the option with an environment 28 | // variable. Command line arguments take precedence over env. 29 | /// URL for the API server 30 | #[structopt(long, env = "API_URL")] 31 | api_url: String, 32 | 33 | // The default value is used if neither argument nor environment 34 | // variable is specified. 35 | /// Number of retries 36 | #[structopt(long, env = "RETRIES", default_value = "5")] 37 | retries: u32, 38 | } 39 | 40 | fn main() { 41 | let opt = Opt::from_args(); 42 | println!("{:#?}", opt); 43 | } 44 | -------------------------------------------------------------------------------- /examples/example.rs: -------------------------------------------------------------------------------- 1 | //! Somewhat complex example of usage of structopt. 2 | //! 3 | //! Running this example with --help prints this message: 4 | //! ----------------------------------------------------- 5 | //! example 0.3.25 6 | //! An example of StructOpt usage 7 | //! 8 | //! USAGE: 9 | //! example [FLAGS] [OPTIONS] [--] [output] 10 | //! 11 | //! FLAGS: 12 | //! -d, --debug Activate debug mode 13 | //! -h, --help Prints help information 14 | //! -V, --version Prints version information 15 | //! 16 | //! OPTIONS: 17 | //! --log Log file, stdout if no file, no logging if not present 18 | //! --optv ... 19 | //! -s, --speed Set speed [default: 42] 20 | //! 21 | //! ARGS: 22 | //! Input file 23 | //! Output file, stdout if not present 24 | //! ----------------------------------------------------- 25 | 26 | use structopt::StructOpt; 27 | 28 | #[derive(StructOpt, Debug)] 29 | #[structopt(name = "example")] 30 | /// An example of StructOpt usage. 31 | struct Opt { 32 | // A flag, true if used in the command line. 33 | #[structopt(short, long)] 34 | /// Activate debug mode 35 | debug: bool, 36 | 37 | // An argument of type float, with a default value. 38 | #[structopt(short, long, default_value = "42")] 39 | /// Set speed 40 | speed: f64, 41 | 42 | // Needed parameter, the first on the command line. 43 | /// Input file 44 | input: String, 45 | 46 | // An optional parameter, will be `None` if not present on the 47 | // command line. 48 | /// Output file, stdout if not present 49 | output: Option, 50 | 51 | // An optional parameter with optional value, will be `None` if 52 | // not present on the command line, will be `Some(None)` if no 53 | // argument is provided (i.e. `--log`) and will be 54 | // `Some(Some(String))` if argument is provided (e.g. `--log 55 | // log.txt`). 56 | #[structopt(long)] 57 | #[allow(clippy::option_option)] 58 | /// Log file, stdout if no file, no logging if not present 59 | log: Option>, 60 | 61 | // An optional list of values, will be `None` if not present on 62 | // the command line, will be `Some(vec![])` if no argument is 63 | // provided (i.e. `--optv`) and will be `Some(Vec)` if 64 | // argument list is provided (e.g. `--optv a b c`). 65 | #[structopt(long)] 66 | optv: Option>, 67 | 68 | // Skipped option: it won't be parsed and will be filled with the 69 | // default value for its type (in this case it'll be an empty string). 70 | #[structopt(skip)] 71 | skipped: String, 72 | } 73 | 74 | fn main() { 75 | let opt = Opt::from_args(); 76 | println!("{:?}", opt); 77 | } 78 | -------------------------------------------------------------------------------- /examples/flatten.rs: -------------------------------------------------------------------------------- 1 | //! How to use flattening. 2 | //! 3 | //! Running this example with --help prints this message: 4 | //! ----------------------------------------------------- 5 | //! structopt 0.3.25 6 | //! 7 | //! USAGE: 8 | //! flatten [FLAGS] -g -u 9 | //! 10 | //! FLAGS: 11 | //! -h, --help Prints help information 12 | //! -V, --version Prints version information 13 | //! -v switch verbosity on 14 | //! 15 | //! OPTIONS: 16 | //! -g daemon group 17 | //! -u daemon user 18 | //! ----------------------------------------------------- 19 | 20 | use structopt::StructOpt; 21 | 22 | #[derive(StructOpt, Debug)] 23 | struct Cmdline { 24 | /// switch verbosity on 25 | #[structopt(short)] 26 | verbose: bool, 27 | 28 | #[structopt(flatten)] 29 | daemon_opts: DaemonOpts, 30 | } 31 | 32 | #[derive(StructOpt, Debug)] 33 | struct DaemonOpts { 34 | /// daemon user 35 | #[structopt(short)] 36 | user: String, 37 | 38 | /// daemon group 39 | #[structopt(short)] 40 | group: String, 41 | } 42 | 43 | fn main() { 44 | let opt = Cmdline::from_args(); 45 | println!("{:?}", opt); 46 | } 47 | -------------------------------------------------------------------------------- /examples/gen_completions.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2019-present structopt developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | //! Running this example with --help prints this message: 10 | //! ----------------------------------------------------- 11 | //! structopt 0.3.25 12 | //! An example of how to generate bash completions with structopt 13 | //! 14 | //! USAGE: 15 | //! gen_completions [FLAGS] 16 | //! 17 | //! FLAGS: 18 | //! -d, --debug Activate debug mode 19 | //! -h, --help Prints help information 20 | //! -V, --version Prints version information 21 | //! ----------------------------------------------------- 22 | 23 | use structopt::clap::Shell; 24 | use structopt::StructOpt; 25 | 26 | #[derive(StructOpt, Debug)] 27 | /// An example of how to generate bash completions with structopt. 28 | struct Opt { 29 | #[structopt(short, long)] 30 | /// Activate debug mode 31 | debug: bool, 32 | } 33 | 34 | fn main() { 35 | // generate `bash` completions in "target" directory 36 | Opt::clap().gen_completions(env!("CARGO_PKG_NAME"), Shell::Bash, "target"); 37 | 38 | let opt = Opt::from_args(); 39 | println!("{:?}", opt); 40 | } 41 | -------------------------------------------------------------------------------- /examples/git.rs: -------------------------------------------------------------------------------- 1 | //! `git.rs` serves as a demonstration of how to use subcommands, 2 | //! as well as a demonstration of adding documentation to subcommands. 3 | //! Documentation can be added either through doc comments or 4 | //! `help`/`about` attributes. 5 | //! 6 | //! Running this example with --help prints this message: 7 | //! ----------------------------------------------------- 8 | //! git 0.3.25 9 | //! the stupid content tracker 10 | //! 11 | //! USAGE: 12 | //! git 13 | //! 14 | //! FLAGS: 15 | //! -h, --help Prints help information 16 | //! -V, --version Prints version information 17 | //! 18 | //! SUBCOMMANDS: 19 | //! add 20 | //! fetch fetch branches from remote repository 21 | //! help Prints this message or the help of the given subcommand(s) 22 | //! ----------------------------------------------------- 23 | 24 | use structopt::StructOpt; 25 | 26 | #[derive(StructOpt, Debug)] 27 | #[structopt(name = "git")] 28 | /// the stupid content tracker 29 | enum Opt { 30 | /// fetch branches from remote repository 31 | Fetch { 32 | #[structopt(long)] 33 | dry_run: bool, 34 | #[structopt(long)] 35 | all: bool, 36 | #[structopt(default_value = "origin")] 37 | repository: String, 38 | }, 39 | #[structopt(help = "add files to the staging area")] 40 | Add { 41 | #[structopt(short)] 42 | interactive: bool, 43 | #[structopt(short)] 44 | all: bool, 45 | files: Vec, 46 | }, 47 | } 48 | 49 | fn main() { 50 | let matches = Opt::from_args(); 51 | 52 | println!("{:?}", matches); 53 | } 54 | -------------------------------------------------------------------------------- /examples/group.rs: -------------------------------------------------------------------------------- 1 | //! How to use `clap::Arg::group` 2 | //! 3 | //! Running this example with --help prints this message: 4 | //! ----------------------------------------------------- 5 | //! structopt 0.3.25 6 | //! 7 | //! USAGE: 8 | //! group [OPTIONS] <--method |--get|--head|--post|--put|--delete> 9 | //! 10 | //! FLAGS: 11 | //! --delete HTTP DELETE 12 | //! --get HTTP GET 13 | //! -h, --help Prints help information 14 | //! --head HTTP HEAD 15 | //! --post HTTP POST 16 | //! --put HTTP PUT 17 | //! -V, --version Prints version information 18 | //! 19 | //! OPTIONS: 20 | //! --method Set a custom HTTP verb 21 | //! ----------------------------------------------------- 22 | 23 | use structopt::{clap::ArgGroup, StructOpt}; 24 | 25 | #[derive(StructOpt, Debug)] 26 | #[structopt(group = ArgGroup::with_name("verb").required(true))] 27 | struct Opt { 28 | /// Set a custom HTTP verb 29 | #[structopt(long, group = "verb")] 30 | method: Option, 31 | /// HTTP GET 32 | #[structopt(long, group = "verb")] 33 | get: bool, 34 | /// HTTP HEAD 35 | #[structopt(long, group = "verb")] 36 | head: bool, 37 | /// HTTP POST 38 | #[structopt(long, group = "verb")] 39 | post: bool, 40 | /// HTTP PUT 41 | #[structopt(long, group = "verb")] 42 | put: bool, 43 | /// HTTP DELETE 44 | #[structopt(long, group = "verb")] 45 | delete: bool, 46 | } 47 | 48 | fn main() { 49 | let opt = Opt::from_args(); 50 | println!("{:?}", opt); 51 | } 52 | -------------------------------------------------------------------------------- /examples/keyvalue.rs: -------------------------------------------------------------------------------- 1 | //! How to parse "key=value" pairs with structopt. 2 | //! 3 | //! Running this example with --help prints this message: 4 | //! ----------------------------------------------------- 5 | //! structopt 0.3.25 6 | //! 7 | //! USAGE: 8 | //! keyvalue [OPTIONS] 9 | //! 10 | //! FLAGS: 11 | //! -h, --help Prints help information 12 | //! -V, --version Prints version information 13 | //! 14 | //! OPTIONS: 15 | //! -D ... 16 | //! ----------------------------------------------------- 17 | 18 | use std::error::Error; 19 | use structopt::StructOpt; 20 | 21 | /// Parse a single key-value pair 22 | fn parse_key_val(s: &str) -> Result<(T, U), Box> 23 | where 24 | T: std::str::FromStr, 25 | T::Err: Error + 'static, 26 | U: std::str::FromStr, 27 | U::Err: Error + 'static, 28 | { 29 | let pos = s 30 | .find('=') 31 | .ok_or_else(|| format!("invalid KEY=value: no `=` found in `{}`", s))?; 32 | Ok((s[..pos].parse()?, s[pos + 1..].parse()?)) 33 | } 34 | 35 | #[derive(StructOpt, Debug)] 36 | struct Opt { 37 | // number_of_values = 1 forces the user to repeat the -D option for each key-value pair: 38 | // my_program -D a=1 -D b=2 39 | // Without number_of_values = 1 you can do: 40 | // my_program -D a=1 b=2 41 | // but this makes adding an argument after the values impossible: 42 | // my_program -D a=1 -D b=2 my_input_file 43 | // becomes invalid. 44 | #[structopt(short = "D", parse(try_from_str = parse_key_val), number_of_values = 1)] 45 | defines: Vec<(String, i32)>, 46 | } 47 | 48 | fn main() { 49 | let opt = Opt::from_args(); 50 | println!("{:?}", opt); 51 | } 52 | -------------------------------------------------------------------------------- /examples/negative_flag.rs: -------------------------------------------------------------------------------- 1 | //! How to add `no-thing` flag which is `true` by default and 2 | //! `false` if passed. 3 | //! 4 | //! Running this example with --help prints this message: 5 | //! ----------------------------------------------------- 6 | //! structopt 0.3.25 7 | //! 8 | //! USAGE: 9 | //! negative_flag [FLAGS] 10 | //! 11 | //! FLAGS: 12 | //! -h, --help Prints help information 13 | //! -V, --version Prints version information 14 | //! --no-verbose 15 | //! ----------------------------------------------------- 16 | 17 | use structopt::StructOpt; 18 | 19 | #[derive(Debug, StructOpt)] 20 | struct Opt { 21 | #[structopt(long = "no-verbose", parse(from_flag = std::ops::Not::not))] 22 | verbose: bool, 23 | } 24 | 25 | fn main() { 26 | let cmd = Opt::from_args(); 27 | println!("{:#?}", cmd); 28 | } 29 | -------------------------------------------------------------------------------- /examples/no_version.rs: -------------------------------------------------------------------------------- 1 | //! How to completely remove version. 2 | //! 3 | //! Running this example with --help prints this message: 4 | //! ----------------------------------------------------- 5 | //! no_version 6 | //! 7 | //! USAGE: 8 | //! no_version 9 | //! 10 | //! FLAGS: 11 | //! -h, --help Prints help information 12 | //! ----------------------------------------------------- 13 | 14 | use structopt::clap::AppSettings; 15 | use structopt::StructOpt; 16 | 17 | #[derive(StructOpt, Debug)] 18 | #[structopt( 19 | name = "no_version", 20 | no_version, 21 | global_settings = &[AppSettings::DisableVersion] 22 | )] 23 | struct Opt {} 24 | 25 | fn main() { 26 | let opt = Opt::from_args(); 27 | println!("{:?}", opt); 28 | } 29 | -------------------------------------------------------------------------------- /examples/rename_all.rs: -------------------------------------------------------------------------------- 1 | //! Example on how the `rename_all` parameter works. 2 | //! 3 | //! `rename_all` can be used to override the casing style used during argument 4 | //! generation. By default the `kebab-case` style will be used but there are a wide 5 | //! variety of other styles available. 6 | //! 7 | //! ## Supported styles overview: 8 | //! 9 | //! - **Camel Case**: Indicate word boundaries with uppercase letter, excluding 10 | //! the first word. 11 | //! - **Kebab Case**: Keep all letters lowercase and indicate word boundaries 12 | //! with hyphens. 13 | //! - **Pascal Case**: Indicate word boundaries with uppercase letter, 14 | //! including the first word. 15 | //! - **Screaming Snake Case**: Keep all letters uppercase and indicate word 16 | //! boundaries with underscores. 17 | //! - **Snake Case**: Keep all letters lowercase and indicate word boundaries 18 | //! with underscores. 19 | //! - **Verbatim**: Use the original attribute name defined in the code. 20 | //! 21 | //! - **Lower Case**: Keep all letters lowercase and remove word boundaries. 22 | //! 23 | //! - **Upper Case**: Keep all letters uppercase and remove word boundaries. 24 | //! 25 | //! Running this example with --help prints this message: 26 | //! ----------------------------------------------------- 27 | //! rename_all 0.3.25 28 | //! 29 | //! USAGE: 30 | //! rename_all 31 | //! 32 | //! FLAGS: 33 | //! -h, --help Prints help information 34 | //! -V, --version Prints version information 35 | //! 36 | //! SUBCOMMANDS: 37 | //! FIRST_COMMAND A screaming loud first command. Only use if necessary 38 | //! SecondCommand Not nearly as loud as the first command 39 | //! help Prints this message or the help of the given subcommand(s) 40 | //! ----------------------------------------------------- 41 | 42 | use structopt::StructOpt; 43 | 44 | #[derive(StructOpt, Debug)] 45 | #[structopt(name = "rename_all", rename_all = "screaming_snake_case")] 46 | enum Opt { 47 | // This subcommand will be named `FIRST_COMMAND`. As the command doesn't 48 | // override the initial casing style, ... 49 | /// A screaming loud first command. Only use if necessary. 50 | FirstCommand { 51 | // this flag will be available as `--FOO` and `-F`. 52 | /// This flag will even scream louder. 53 | #[structopt(long, short)] 54 | foo: bool, 55 | }, 56 | 57 | // As we override the casing style for this variant the related subcommand 58 | // will be named `SecondCommand`. 59 | /// Not nearly as loud as the first command. 60 | #[structopt(rename_all = "pascal_case")] 61 | SecondCommand { 62 | // We can also override it again on a single field. 63 | /// Nice quiet flag. No one is annoyed. 64 | #[structopt(rename_all = "snake_case", long)] 65 | bar_option: bool, 66 | 67 | // Renaming will not be propagated into subcommand flagged enums. If 68 | // a non default casing style is required it must be defined on the 69 | // enum itself. 70 | #[structopt(subcommand)] 71 | cmds: Subcommands, 72 | 73 | // or flattened structs. 74 | #[structopt(flatten)] 75 | options: BonusOptions, 76 | }, 77 | } 78 | 79 | #[derive(StructOpt, Debug)] 80 | enum Subcommands { 81 | // This one will be available as `first-subcommand`. 82 | FirstSubcommand, 83 | } 84 | 85 | #[derive(StructOpt, Debug)] 86 | struct BonusOptions { 87 | // And this one will be available as `baz-option`. 88 | #[structopt(long)] 89 | baz_option: bool, 90 | } 91 | 92 | fn main() { 93 | let opt = Opt::from_args(); 94 | println!("{:?}", opt); 95 | } 96 | -------------------------------------------------------------------------------- /examples/required_if.rs: -------------------------------------------------------------------------------- 1 | //! How to use `required_if` with structopt. 2 | //! 3 | //! Running this example with --help prints this message: 4 | //! ----------------------------------------------------- 5 | //! structopt 0.3.25 6 | //! 7 | //! USAGE: 8 | //! required_if -o [FILE] 9 | //! 10 | //! FLAGS: 11 | //! -h, --help Prints help information 12 | //! -V, --version Prints version information 13 | //! 14 | //! OPTIONS: 15 | //! -o Where to write the output: to `stdout` or `file` 16 | //! 17 | //! ARGS: 18 | //! File name: only required when `out-type` is set to `file` 19 | //! ----------------------------------------------------- 20 | 21 | use structopt::StructOpt; 22 | 23 | #[derive(Debug, StructOpt, PartialEq)] 24 | struct Opt { 25 | /// Where to write the output: to `stdout` or `file` 26 | #[structopt(short)] 27 | out_type: String, 28 | 29 | /// File name: only required when `out-type` is set to `file` 30 | #[structopt(name = "FILE", required_if("out-type", "file"))] 31 | file_name: Option, 32 | } 33 | 34 | fn main() { 35 | let opt = Opt::from_args(); 36 | println!("{:?}", opt); 37 | } 38 | 39 | #[cfg(test)] 40 | mod tests { 41 | use super::*; 42 | 43 | #[test] 44 | fn test_opt_out_type_file_without_file_name_returns_err() { 45 | let opt = Opt::from_iter_safe(&["test", "-o", "file"]); 46 | let err = opt.unwrap_err(); 47 | assert_eq!(err.kind, clap::ErrorKind::MissingRequiredArgument); 48 | } 49 | 50 | #[test] 51 | fn test_opt_out_type_file_with_file_name_returns_ok() { 52 | let opt = Opt::from_iter_safe(&["test", "-o", "file", "filename"]); 53 | let opt = opt.unwrap(); 54 | assert_eq!( 55 | opt, 56 | Opt { 57 | out_type: "file".into(), 58 | file_name: Some("filename".into()), 59 | } 60 | ); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /examples/skip.rs: -------------------------------------------------------------------------------- 1 | //! How to use `#[structopt(skip)]` 2 | 3 | use structopt::StructOpt; 4 | 5 | #[derive(StructOpt, Debug, PartialEq)] 6 | pub struct Opt { 7 | #[structopt(long, short)] 8 | number: u32, 9 | #[structopt(skip)] 10 | k: Kind, 11 | #[structopt(skip)] 12 | v: Vec, 13 | 14 | #[structopt(skip = Kind::A)] 15 | k2: Kind, 16 | #[structopt(skip = vec![1, 2, 3])] 17 | v2: Vec, 18 | #[structopt(skip = "cake")] // &str implements Into 19 | s: String, 20 | } 21 | 22 | #[derive(Debug, PartialEq)] 23 | enum Kind { 24 | A, 25 | B, 26 | } 27 | 28 | impl Default for Kind { 29 | fn default() -> Self { 30 | return Kind::B; 31 | } 32 | } 33 | 34 | fn main() { 35 | assert_eq!( 36 | Opt::from_iter(&["test", "-n", "10"]), 37 | Opt { 38 | number: 10, 39 | k: Kind::B, 40 | v: vec![], 41 | 42 | k2: Kind::A, 43 | v2: vec![1, 2, 3], 44 | s: String::from("cake") 45 | } 46 | ); 47 | } 48 | -------------------------------------------------------------------------------- /examples/subcommand_aliases.rs: -------------------------------------------------------------------------------- 1 | //! How to assign some aliases to subcommands 2 | //! 3 | //! Running this example with --help prints this message: 4 | //! ----------------------------------------------------- 5 | //! structopt 0.3.25 6 | //! 7 | //! USAGE: 8 | //! subcommand_aliases 9 | //! 10 | //! FLAGS: 11 | //! -h, --help Prints help information 12 | //! -V, --version Prints version information 13 | //! 14 | //! SUBCOMMANDS: 15 | //! bar 16 | //! foo 17 | //! help Prints this message or the help of the given subcommand(s) 18 | //! ----------------------------------------------------- 19 | 20 | use structopt::clap::AppSettings; 21 | use structopt::StructOpt; 22 | 23 | #[derive(StructOpt, Debug)] 24 | // https://docs.rs/clap/2/clap/enum.AppSettings.html#variant.InferSubcommands 25 | #[structopt(setting = AppSettings::InferSubcommands)] 26 | enum Opt { 27 | // https://docs.rs/clap/2/clap/struct.App.html#method.alias 28 | #[structopt(alias = "foobar")] 29 | Foo, 30 | // https://docs.rs/clap/2/clap/struct.App.html#method.aliases 31 | #[structopt(aliases = &["baz", "fizz"])] 32 | Bar, 33 | } 34 | 35 | fn main() { 36 | let opt = Opt::from_args(); 37 | println!("{:?}", opt); 38 | } 39 | -------------------------------------------------------------------------------- /examples/true_or_false.rs: -------------------------------------------------------------------------------- 1 | //! How to parse `--foo=true --bar=false` and turn them into bool. 2 | 3 | use structopt::StructOpt; 4 | 5 | fn true_or_false(s: &str) -> Result { 6 | match s { 7 | "true" => Ok(true), 8 | "false" => Ok(false), 9 | _ => Err("expected `true` or `false`"), 10 | } 11 | } 12 | 13 | #[derive(StructOpt, Debug, PartialEq)] 14 | struct Opt { 15 | // Default parser for `try_from_str` is FromStr::from_str. 16 | // `impl FromStr for bool` parses `true` or `false` so this 17 | // works as expected. 18 | #[structopt(long, parse(try_from_str))] 19 | foo: bool, 20 | 21 | // Of course, this could be done with an explicit parser function. 22 | #[structopt(long, parse(try_from_str = true_or_false))] 23 | bar: bool, 24 | 25 | // `bool` can be positional only with explicit `parse(...)` annotation 26 | #[structopt(parse(try_from_str))] 27 | boom: bool, 28 | } 29 | 30 | fn main() { 31 | assert_eq!( 32 | Opt::from_iter(&["test", "--foo=true", "--bar=false", "true"]), 33 | Opt { 34 | foo: true, 35 | bar: false, 36 | boom: true 37 | } 38 | ); 39 | // no beauty, only truth and falseness 40 | assert!(Opt::from_iter_safe(&["test", "--foo=beauty"]).is_err()); 41 | } 42 | -------------------------------------------------------------------------------- /link-check-headers.json: -------------------------------------------------------------------------------- 1 | { 2 | "httpHeaders": [ 3 | { 4 | "urls": [ 5 | "https://", 6 | "http://" 7 | ], 8 | "headers": { 9 | "User-Agent": "broken links checker (https://github.com/TeXitoi/structopt)", 10 | "Accept": "text/html" 11 | } 12 | } 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /structopt-derive/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "structopt-derive" 3 | version = "0.4.18" 4 | edition = "2018" 5 | authors = ["Guillaume Pinot "] 6 | description = "Parse command line argument by defining a struct, derive crate." 7 | documentation = "https://docs.rs/structopt-derive" 8 | repository = "https://github.com/TeXitoi/structopt" 9 | keywords = ["clap", "cli", "derive", "docopt"] 10 | categories = ["command-line-interface"] 11 | license = "Apache-2.0/MIT" 12 | 13 | [badges] 14 | travis-ci = { repository = "TeXitoi/structopt" } 15 | 16 | [dependencies] 17 | syn = { version = "1", features = ["full"] } 18 | quote = "1" 19 | proc-macro2 = "1" 20 | heck = "0.4.0" 21 | proc-macro-error = "1.0.0" 22 | 23 | [features] 24 | paw = [] 25 | 26 | [lib] 27 | proc-macro = true 28 | -------------------------------------------------------------------------------- /structopt-derive/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Guillaume Pinot (@TeXitoi) 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 | -------------------------------------------------------------------------------- /structopt-derive/src/doc_comments.rs: -------------------------------------------------------------------------------- 1 | //! The preprocessing we apply to doc comments. 2 | //! 3 | //! structopt works in terms of "paragraphs". Paragraph is a sequence of 4 | //! non-empty adjacent lines, delimited by sequences of blank (whitespace only) lines. 5 | 6 | use crate::attrs::Method; 7 | use quote::{format_ident, quote}; 8 | use std::iter; 9 | 10 | pub fn process_doc_comment(lines: Vec, name: &str, preprocess: bool) -> Vec { 11 | // multiline comments (`/** ... */`) may have LFs (`\n`) in them, 12 | // we need to split so we could handle the lines correctly 13 | // 14 | // we also need to remove leading and trailing blank lines 15 | let mut lines: Vec<&str> = lines 16 | .iter() 17 | .skip_while(|s| is_blank(s)) 18 | .flat_map(|s| s.split('\n')) 19 | .collect(); 20 | 21 | while let Some(true) = lines.last().map(|s| is_blank(s)) { 22 | lines.pop(); 23 | } 24 | 25 | // remove one leading space no matter what 26 | for line in lines.iter_mut() { 27 | if line.starts_with(' ') { 28 | *line = &line[1..]; 29 | } 30 | } 31 | 32 | if lines.is_empty() { 33 | return vec![]; 34 | } 35 | 36 | let short_name = format_ident!("{}", name); 37 | let long_name = format_ident!("long_{}", name); 38 | 39 | if let Some(first_blank) = lines.iter().position(|s| is_blank(s)) { 40 | let (short, long) = if preprocess { 41 | let paragraphs = split_paragraphs(&lines); 42 | let short = paragraphs[0].clone(); 43 | let long = paragraphs.join("\n\n"); 44 | (remove_period(short), long) 45 | } else { 46 | let short = lines[..first_blank].join("\n"); 47 | let long = lines.join("\n"); 48 | (short, long) 49 | }; 50 | 51 | vec![ 52 | Method::new(short_name, quote!(#short)), 53 | Method::new(long_name, quote!(#long)), 54 | ] 55 | } else { 56 | let short = if preprocess { 57 | let s = merge_lines(&lines); 58 | remove_period(s) 59 | } else { 60 | lines.join("\n") 61 | }; 62 | 63 | vec![Method::new(short_name, quote!(#short))] 64 | } 65 | } 66 | 67 | fn split_paragraphs(lines: &[&str]) -> Vec { 68 | let mut last_line = 0; 69 | iter::from_fn(|| { 70 | let slice = &lines[last_line..]; 71 | let start = slice.iter().position(|s| !is_blank(s)).unwrap_or(0); 72 | 73 | let slice = &slice[start..]; 74 | let len = slice 75 | .iter() 76 | .position(|s| is_blank(s)) 77 | .unwrap_or_else(|| slice.len()); 78 | 79 | last_line += start + len; 80 | 81 | if len != 0 { 82 | Some(merge_lines(&slice[..len])) 83 | } else { 84 | None 85 | } 86 | }) 87 | .collect() 88 | } 89 | 90 | fn remove_period(mut s: String) -> String { 91 | if s.ends_with('.') && !s.ends_with("..") { 92 | s.pop(); 93 | } 94 | s 95 | } 96 | 97 | fn is_blank(s: &str) -> bool { 98 | s.trim().is_empty() 99 | } 100 | 101 | fn merge_lines(lines: &[&str]) -> String { 102 | lines.iter().map(|s| s.trim()).collect::>().join(" ") 103 | } 104 | -------------------------------------------------------------------------------- /structopt-derive/src/parse.rs: -------------------------------------------------------------------------------- 1 | use std::iter::FromIterator; 2 | 3 | use proc_macro_error::{abort, ResultExt}; 4 | use quote::ToTokens; 5 | use syn::{ 6 | self, parenthesized, 7 | parse::{Parse, ParseBuffer, ParseStream}, 8 | punctuated::Punctuated, 9 | Attribute, Expr, ExprLit, Ident, Lit, LitBool, LitStr, Token, 10 | }; 11 | 12 | pub enum StructOptAttr { 13 | // single-identifier attributes 14 | Short(Ident), 15 | Long(Ident), 16 | Env(Ident), 17 | Flatten(Ident), 18 | Subcommand(Ident), 19 | ExternalSubcommand(Ident), 20 | NoVersion(Ident), 21 | VerbatimDocComment(Ident), 22 | 23 | // ident [= "string literal"] 24 | About(Ident, Option), 25 | Author(Ident, Option), 26 | DefaultValue(Ident, Option), 27 | 28 | // ident = "string literal" 29 | Version(Ident, LitStr), 30 | RenameAllEnv(Ident, LitStr), 31 | RenameAll(Ident, LitStr), 32 | NameLitStr(Ident, LitStr), 33 | 34 | // parse(parser_kind [= parser_func]) 35 | Parse(Ident, ParserSpec), 36 | 37 | // ident [= arbitrary_expr] 38 | Skip(Ident, Option), 39 | 40 | // ident = arbitrary_expr 41 | NameExpr(Ident, Expr), 42 | 43 | // ident(arbitrary_expr,*) 44 | MethodCall(Ident, Vec), 45 | } 46 | 47 | impl Parse for StructOptAttr { 48 | fn parse(input: ParseStream<'_>) -> syn::Result { 49 | use self::StructOptAttr::*; 50 | 51 | let name: Ident = input.parse()?; 52 | let name_str = name.to_string(); 53 | 54 | if input.peek(Token![=]) { 55 | // `name = value` attributes. 56 | let assign_token = input.parse::()?; // skip '=' 57 | 58 | if input.peek(LitStr) { 59 | let lit: LitStr = input.parse()?; 60 | let lit_str = lit.value(); 61 | 62 | let check_empty_lit = |s| { 63 | if lit_str.is_empty() { 64 | abort!( 65 | lit, 66 | "`#[structopt({} = \"\")]` is deprecated in structopt 0.3, \ 67 | now it's default behavior", 68 | s 69 | ); 70 | } 71 | }; 72 | 73 | match &*name_str { 74 | "rename_all" => Ok(RenameAll(name, lit)), 75 | "rename_all_env" => Ok(RenameAllEnv(name, lit)), 76 | "default_value" => Ok(DefaultValue(name, Some(lit))), 77 | 78 | "version" => { 79 | check_empty_lit("version"); 80 | Ok(Version(name, lit)) 81 | } 82 | 83 | "author" => { 84 | check_empty_lit("author"); 85 | Ok(Author(name, Some(lit))) 86 | } 87 | 88 | "about" => { 89 | check_empty_lit("about"); 90 | Ok(About(name, Some(lit))) 91 | } 92 | 93 | "skip" => { 94 | let expr = ExprLit { 95 | attrs: vec![], 96 | lit: Lit::Str(lit), 97 | }; 98 | let expr = Expr::Lit(expr); 99 | Ok(Skip(name, Some(expr))) 100 | } 101 | 102 | _ => Ok(NameLitStr(name, lit)), 103 | } 104 | } else { 105 | match input.parse::() { 106 | Ok(expr) => { 107 | if name_str == "skip" { 108 | Ok(Skip(name, Some(expr))) 109 | } else { 110 | Ok(NameExpr(name, expr)) 111 | } 112 | } 113 | 114 | Err(_) => abort! { 115 | assign_token, 116 | "expected `string literal` or `expression` after `=`" 117 | }, 118 | } 119 | } 120 | } else if input.peek(syn::token::Paren) { 121 | // `name(...)` attributes. 122 | let nested; 123 | parenthesized!(nested in input); 124 | 125 | match name_str.as_ref() { 126 | "parse" => { 127 | let parser_specs: Punctuated = 128 | nested.parse_terminated(ParserSpec::parse)?; 129 | 130 | if parser_specs.len() == 1 { 131 | Ok(Parse(name, parser_specs[0].clone())) 132 | } else { 133 | abort!(name, "`parse` must have exactly one argument") 134 | } 135 | } 136 | 137 | "raw" => match nested.parse::() { 138 | Ok(bool_token) => { 139 | let expr = ExprLit { 140 | attrs: vec![], 141 | lit: Lit::Bool(bool_token), 142 | }; 143 | let expr = Expr::Lit(expr); 144 | Ok(MethodCall(name, vec![expr])) 145 | } 146 | 147 | Err(_) => { 148 | abort!(name, 149 | "`#[structopt(raw(...))` attributes are removed in structopt 0.3, \ 150 | they are replaced with raw methods"; 151 | help = "if you meant to call `clap::Arg::raw()` method \ 152 | you should use bool literal, like `raw(true)` or `raw(false)`"; 153 | note = raw_method_suggestion(nested); 154 | ); 155 | } 156 | }, 157 | 158 | _ => { 159 | let method_args: Punctuated<_, Token![,]> = 160 | nested.parse_terminated(Expr::parse)?; 161 | Ok(MethodCall(name, Vec::from_iter(method_args))) 162 | } 163 | } 164 | } else { 165 | // Attributes represented with a sole identifier. 166 | match name_str.as_ref() { 167 | "long" => Ok(Long(name)), 168 | "short" => Ok(Short(name)), 169 | "env" => Ok(Env(name)), 170 | "flatten" => Ok(Flatten(name)), 171 | "subcommand" => Ok(Subcommand(name)), 172 | "external_subcommand" => Ok(ExternalSubcommand(name)), 173 | "no_version" => Ok(NoVersion(name)), 174 | "verbatim_doc_comment" => Ok(VerbatimDocComment(name)), 175 | 176 | "default_value" => Ok(DefaultValue(name, None)), 177 | "about" => (Ok(About(name, None))), 178 | "author" => (Ok(Author(name, None))), 179 | 180 | "skip" => Ok(Skip(name, None)), 181 | 182 | "version" => abort!( 183 | name, 184 | "#[structopt(version)] is invalid attribute, \ 185 | structopt 0.3 inherits version from Cargo.toml by default, \ 186 | no attribute needed" 187 | ), 188 | 189 | _ => abort!(name, "unexpected attribute: {}", name_str), 190 | } 191 | } 192 | } 193 | } 194 | 195 | #[derive(Clone)] 196 | pub struct ParserSpec { 197 | pub kind: Ident, 198 | pub eq_token: Option, 199 | pub parse_func: Option, 200 | } 201 | 202 | impl Parse for ParserSpec { 203 | fn parse(input: ParseStream<'_>) -> syn::Result { 204 | let kind = input 205 | .parse() 206 | .map_err(|_| input.error("parser specification must start with identifier"))?; 207 | let eq_token = input.parse()?; 208 | let parse_func = match eq_token { 209 | None => None, 210 | Some(_) => Some(input.parse()?), 211 | }; 212 | Ok(ParserSpec { 213 | kind, 214 | eq_token, 215 | parse_func, 216 | }) 217 | } 218 | } 219 | 220 | fn raw_method_suggestion(ts: ParseBuffer) -> String { 221 | let do_parse = move || -> Result<(Ident, Punctuated), syn::Error> { 222 | let name = ts.parse()?; 223 | let _eq: Token![=] = ts.parse()?; 224 | let val: LitStr = ts.parse()?; 225 | let exprs = val.parse_with(Punctuated::::parse_terminated)?; 226 | Ok((name, exprs)) 227 | }; 228 | 229 | fn to_string(val: &T) -> String { 230 | val.to_token_stream() 231 | .to_string() 232 | .replace(" ", "") 233 | .replace(",", ", ") 234 | } 235 | 236 | if let Ok((name, exprs)) = do_parse() { 237 | let suggestion = if exprs.len() == 1 { 238 | let val = to_string(&exprs[0]); 239 | format!(" = {}", val) 240 | } else { 241 | let val = exprs 242 | .into_iter() 243 | .map(|expr| to_string(&expr)) 244 | .collect::>() 245 | .join(", "); 246 | 247 | format!("({})", val) 248 | }; 249 | 250 | format!( 251 | "if you need to call `clap::Arg/App::{}` method you \ 252 | can do it like this: #[structopt({}{})]", 253 | name, name, suggestion 254 | ) 255 | } else { 256 | "if you need to call some method from `clap::Arg/App` \ 257 | you should use raw method, see \ 258 | https://docs.rs/structopt/0.3/structopt/#raw-methods" 259 | .into() 260 | } 261 | } 262 | 263 | pub fn parse_structopt_attributes(all_attrs: &[Attribute]) -> Vec { 264 | all_attrs 265 | .iter() 266 | .filter(|attr| attr.path.is_ident("structopt")) 267 | .flat_map(|attr| { 268 | attr.parse_args_with(Punctuated::::parse_terminated) 269 | .unwrap_or_abort() 270 | }) 271 | .collect() 272 | } 273 | -------------------------------------------------------------------------------- /structopt-derive/src/spanned.rs: -------------------------------------------------------------------------------- 1 | use proc_macro2::{Ident, Span, TokenStream}; 2 | use quote::ToTokens; 3 | use std::ops::{Deref, DerefMut}; 4 | use syn::LitStr; 5 | 6 | /// An entity with a span attached. 7 | #[derive(Debug, Clone)] 8 | pub struct Sp { 9 | span: Span, 10 | val: T, 11 | } 12 | 13 | impl Sp { 14 | pub fn new(val: T, span: Span) -> Self { 15 | Sp { val, span } 16 | } 17 | 18 | pub fn call_site(val: T) -> Self { 19 | Sp { 20 | val, 21 | span: Span::call_site(), 22 | } 23 | } 24 | 25 | pub fn span(&self) -> Span { 26 | self.span 27 | } 28 | } 29 | 30 | impl Deref for Sp { 31 | type Target = T; 32 | 33 | fn deref(&self) -> &T { 34 | &self.val 35 | } 36 | } 37 | 38 | impl DerefMut for Sp { 39 | fn deref_mut(&mut self) -> &mut T { 40 | &mut self.val 41 | } 42 | } 43 | 44 | impl From for Sp { 45 | fn from(ident: Ident) -> Self { 46 | Sp { 47 | val: ident.to_string(), 48 | span: ident.span(), 49 | } 50 | } 51 | } 52 | 53 | impl From for Sp { 54 | fn from(lit: LitStr) -> Self { 55 | Sp { 56 | val: lit.value(), 57 | span: lit.span(), 58 | } 59 | } 60 | } 61 | 62 | impl<'a> From> for Sp { 63 | fn from(sp: Sp<&'a str>) -> Self { 64 | Sp::new(sp.val.into(), sp.span) 65 | } 66 | } 67 | 68 | impl PartialEq for Sp { 69 | fn eq(&self, other: &T) -> bool { 70 | self.val == *other 71 | } 72 | } 73 | 74 | impl PartialEq for Sp { 75 | fn eq(&self, other: &Sp) -> bool { 76 | self.val == **other 77 | } 78 | } 79 | 80 | impl> AsRef for Sp { 81 | fn as_ref(&self) -> &str { 82 | self.val.as_ref() 83 | } 84 | } 85 | 86 | impl ToTokens for Sp { 87 | fn to_tokens(&self, stream: &mut TokenStream) { 88 | // this is the simplest way out of correct ones to change span on 89 | // arbitrary token tree I can come up with 90 | let tt = self.val.to_token_stream().into_iter().map(|mut tt| { 91 | tt.set_span(self.span); 92 | tt 93 | }); 94 | 95 | stream.extend(tt); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /structopt-derive/src/ty.rs: -------------------------------------------------------------------------------- 1 | //! Special types handling 2 | 3 | use crate::spanned::Sp; 4 | 5 | use syn::{ 6 | spanned::Spanned, GenericArgument, Path, PathArguments, PathArguments::AngleBracketed, 7 | PathSegment, Type, TypePath, 8 | }; 9 | 10 | #[derive(Copy, Clone, PartialEq, Debug)] 11 | pub enum Ty { 12 | Bool, 13 | Vec, 14 | Option, 15 | OptionOption, 16 | OptionVec, 17 | Other, 18 | } 19 | 20 | impl Ty { 21 | pub fn from_syn_ty(ty: &syn::Type) -> Sp { 22 | use Ty::*; 23 | let t = |kind| Sp::new(kind, ty.span()); 24 | 25 | if is_simple_ty(ty, "bool") { 26 | t(Bool) 27 | } else if is_generic_ty(ty, "Vec") { 28 | t(Vec) 29 | } else if let Some(subty) = subty_if_name(ty, "Option") { 30 | if is_generic_ty(subty, "Option") { 31 | t(OptionOption) 32 | } else if is_generic_ty(subty, "Vec") { 33 | t(OptionVec) 34 | } else { 35 | t(Option) 36 | } 37 | } else { 38 | t(Other) 39 | } 40 | } 41 | } 42 | 43 | pub fn sub_type(ty: &syn::Type) -> Option<&syn::Type> { 44 | subty_if(ty, |_| true) 45 | } 46 | 47 | fn only_last_segment(ty: &syn::Type) -> Option<&PathSegment> { 48 | match ty { 49 | Type::Path(TypePath { 50 | qself: None, 51 | path: 52 | Path { 53 | leading_colon: None, 54 | segments, 55 | }, 56 | }) => only_one(segments.iter()), 57 | 58 | _ => None, 59 | } 60 | } 61 | 62 | fn subty_if(ty: &syn::Type, f: F) -> Option<&syn::Type> 63 | where 64 | F: FnOnce(&PathSegment) -> bool, 65 | { 66 | let ty = strip_group(ty); 67 | 68 | only_last_segment(ty) 69 | .filter(|segment| f(segment)) 70 | .and_then(|segment| { 71 | if let AngleBracketed(args) = &segment.arguments { 72 | only_one(args.args.iter()).and_then(|genneric| { 73 | if let GenericArgument::Type(ty) = genneric { 74 | Some(ty) 75 | } else { 76 | None 77 | } 78 | }) 79 | } else { 80 | None 81 | } 82 | }) 83 | } 84 | 85 | pub fn subty_if_name<'a>(ty: &'a syn::Type, name: &str) -> Option<&'a syn::Type> { 86 | subty_if(ty, |seg| seg.ident == name) 87 | } 88 | 89 | pub fn is_simple_ty(ty: &syn::Type, name: &str) -> bool { 90 | let ty = strip_group(ty); 91 | 92 | only_last_segment(ty) 93 | .map(|segment| { 94 | if let PathArguments::None = segment.arguments { 95 | segment.ident == name 96 | } else { 97 | false 98 | } 99 | }) 100 | .unwrap_or(false) 101 | } 102 | 103 | // If the struct is placed inside of a macro_rules! declaration, 104 | // in some circumstances, the tokens inside will be enclosed 105 | // in `proc_macro::Group` delimited by invisible `proc_macro::Delimiter::None`. 106 | // 107 | // In syn speak, this is encoded via `*::Group` variants. We don't really care about 108 | // that, so let's just strip it. 109 | // 110 | // Details: https://doc.rust-lang.org/proc_macro/enum.Delimiter.html#variant.None 111 | // See also: https://github.com/TeXitoi/structopt/issues/439 112 | fn strip_group(mut ty: &syn::Type) -> &syn::Type { 113 | while let Type::Group(group) = ty { 114 | ty = &*group.elem; 115 | } 116 | 117 | ty 118 | } 119 | 120 | fn is_generic_ty(ty: &syn::Type, name: &str) -> bool { 121 | subty_if_name(ty, name).is_some() 122 | } 123 | 124 | fn only_one(mut iter: I) -> Option 125 | where 126 | I: Iterator, 127 | { 128 | iter.next().filter(|_| iter.next().is_none()) 129 | } 130 | -------------------------------------------------------------------------------- /tests/argument_naming.rs: -------------------------------------------------------------------------------- 1 | use structopt::StructOpt; 2 | 3 | #[test] 4 | fn test_single_word_enum_variant_is_default_renamed_into_kebab_case() { 5 | #[derive(StructOpt, Debug, PartialEq)] 6 | enum Opt { 7 | Command { foo: u32 }, 8 | } 9 | 10 | assert_eq!( 11 | Opt::Command { foo: 0 }, 12 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "command", "0"])) 13 | ); 14 | } 15 | 16 | #[test] 17 | fn test_multi_word_enum_variant_is_renamed() { 18 | #[derive(StructOpt, Debug, PartialEq)] 19 | enum Opt { 20 | FirstCommand { foo: u32 }, 21 | } 22 | 23 | assert_eq!( 24 | Opt::FirstCommand { foo: 0 }, 25 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "first-command", "0"])) 26 | ); 27 | } 28 | 29 | #[test] 30 | fn test_standalone_long_generates_kebab_case() { 31 | #[derive(StructOpt, Debug, PartialEq)] 32 | #[allow(non_snake_case)] 33 | struct Opt { 34 | #[structopt(long)] 35 | FOO_OPTION: bool, 36 | } 37 | 38 | assert_eq!( 39 | Opt { FOO_OPTION: true }, 40 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "--foo-option"])) 41 | ); 42 | } 43 | 44 | #[test] 45 | fn test_custom_long_overwrites_default_name() { 46 | #[derive(StructOpt, Debug, PartialEq)] 47 | struct Opt { 48 | #[structopt(long = "foo")] 49 | foo_option: bool, 50 | } 51 | 52 | assert_eq!( 53 | Opt { foo_option: true }, 54 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "--foo"])) 55 | ); 56 | } 57 | 58 | #[test] 59 | fn test_standalone_long_uses_previous_defined_custom_name() { 60 | #[derive(StructOpt, Debug, PartialEq)] 61 | struct Opt { 62 | #[structopt(name = "foo", long)] 63 | foo_option: bool, 64 | } 65 | 66 | assert_eq!( 67 | Opt { foo_option: true }, 68 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "--foo"])) 69 | ); 70 | } 71 | 72 | #[test] 73 | fn test_standalone_long_ignores_afterwards_defined_custom_name() { 74 | #[derive(StructOpt, Debug, PartialEq)] 75 | struct Opt { 76 | #[structopt(long, name = "foo")] 77 | foo_option: bool, 78 | } 79 | 80 | assert_eq!( 81 | Opt { foo_option: true }, 82 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "--foo-option"])) 83 | ); 84 | } 85 | 86 | #[test] 87 | fn test_standalone_short_generates_kebab_case() { 88 | #[derive(StructOpt, Debug, PartialEq)] 89 | #[allow(non_snake_case)] 90 | struct Opt { 91 | #[structopt(short)] 92 | FOO_OPTION: bool, 93 | } 94 | 95 | assert_eq!( 96 | Opt { FOO_OPTION: true }, 97 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-f"])) 98 | ); 99 | } 100 | 101 | #[test] 102 | fn test_custom_short_overwrites_default_name() { 103 | #[derive(StructOpt, Debug, PartialEq)] 104 | struct Opt { 105 | #[structopt(short = "o")] 106 | foo_option: bool, 107 | } 108 | 109 | assert_eq!( 110 | Opt { foo_option: true }, 111 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-o"])) 112 | ); 113 | } 114 | 115 | #[test] 116 | fn test_standalone_short_uses_previous_defined_custom_name() { 117 | #[derive(StructOpt, Debug, PartialEq)] 118 | struct Opt { 119 | #[structopt(name = "option", short)] 120 | foo_option: bool, 121 | } 122 | 123 | assert_eq!( 124 | Opt { foo_option: true }, 125 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-o"])) 126 | ); 127 | } 128 | 129 | #[test] 130 | fn test_standalone_short_ignores_afterwards_defined_custom_name() { 131 | #[derive(StructOpt, Debug, PartialEq)] 132 | struct Opt { 133 | #[structopt(short, name = "option")] 134 | foo_option: bool, 135 | } 136 | 137 | assert_eq!( 138 | Opt { foo_option: true }, 139 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-f"])) 140 | ); 141 | } 142 | 143 | #[test] 144 | fn test_standalone_long_uses_previous_defined_casing() { 145 | #[derive(StructOpt, Debug, PartialEq)] 146 | struct Opt { 147 | #[structopt(rename_all = "screaming_snake", long)] 148 | foo_option: bool, 149 | } 150 | 151 | assert_eq!( 152 | Opt { foo_option: true }, 153 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "--FOO_OPTION"])) 154 | ); 155 | } 156 | 157 | #[test] 158 | fn test_standalone_short_uses_previous_defined_casing() { 159 | #[derive(StructOpt, Debug, PartialEq)] 160 | struct Opt { 161 | #[structopt(rename_all = "screaming_snake", short)] 162 | foo_option: bool, 163 | } 164 | 165 | assert_eq!( 166 | Opt { foo_option: true }, 167 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-F"])) 168 | ); 169 | } 170 | 171 | #[test] 172 | fn test_standalone_long_works_with_verbatim_casing() { 173 | #[derive(StructOpt, Debug, PartialEq)] 174 | #[allow(non_snake_case)] 175 | struct Opt { 176 | #[structopt(rename_all = "verbatim", long)] 177 | _fOO_oPtiON: bool, 178 | } 179 | 180 | assert_eq!( 181 | Opt { _fOO_oPtiON: true }, 182 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "--_fOO_oPtiON"])) 183 | ); 184 | } 185 | 186 | #[test] 187 | fn test_standalone_short_works_with_verbatim_casing() { 188 | #[derive(StructOpt, Debug, PartialEq)] 189 | struct Opt { 190 | #[structopt(rename_all = "verbatim", short)] 191 | _foo: bool, 192 | } 193 | 194 | assert_eq!( 195 | Opt { _foo: true }, 196 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-_"])) 197 | ); 198 | } 199 | 200 | #[test] 201 | fn test_rename_all_is_propagated_from_struct_to_fields() { 202 | #[derive(StructOpt, Debug, PartialEq)] 203 | #[structopt(rename_all = "screaming_snake")] 204 | struct Opt { 205 | #[structopt(long)] 206 | foo: bool, 207 | } 208 | 209 | assert_eq!( 210 | Opt { foo: true }, 211 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "--FOO"])) 212 | ); 213 | } 214 | 215 | #[test] 216 | fn test_rename_all_is_not_propagated_from_struct_into_flattened() { 217 | #[derive(StructOpt, Debug, PartialEq)] 218 | #[structopt(rename_all = "screaming_snake")] 219 | struct Opt { 220 | #[structopt(flatten)] 221 | foo: Foo, 222 | } 223 | 224 | #[derive(StructOpt, Debug, PartialEq)] 225 | struct Foo { 226 | #[structopt(long)] 227 | foo: bool, 228 | } 229 | 230 | assert_eq!( 231 | Opt { 232 | foo: Foo { foo: true } 233 | }, 234 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "--foo"])) 235 | ); 236 | } 237 | 238 | #[test] 239 | fn test_rename_all_is_not_propagated_from_struct_into_subcommand() { 240 | #[derive(StructOpt, Debug, PartialEq)] 241 | #[structopt(rename_all = "screaming_snake")] 242 | struct Opt { 243 | #[structopt(subcommand)] 244 | foo: Foo, 245 | } 246 | 247 | #[derive(StructOpt, Debug, PartialEq)] 248 | enum Foo { 249 | Command { 250 | #[structopt(long)] 251 | foo: bool, 252 | }, 253 | } 254 | 255 | assert_eq!( 256 | Opt { 257 | foo: Foo::Command { foo: true } 258 | }, 259 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "command", "--foo"])) 260 | ); 261 | } 262 | 263 | #[test] 264 | fn test_rename_all_is_propagated_from_enum_to_variants_and_their_fields() { 265 | #[derive(StructOpt, Debug, PartialEq)] 266 | #[structopt(rename_all = "screaming_snake")] 267 | enum Opt { 268 | FirstVariant, 269 | SecondVariant { 270 | #[structopt(long)] 271 | foo: bool, 272 | }, 273 | } 274 | 275 | assert_eq!( 276 | Opt::FirstVariant, 277 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "FIRST_VARIANT"])) 278 | ); 279 | 280 | assert_eq!( 281 | Opt::SecondVariant { foo: true }, 282 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "SECOND_VARIANT", "--FOO"])) 283 | ); 284 | } 285 | 286 | #[test] 287 | fn test_rename_all_is_propagation_can_be_overridden() { 288 | #[derive(StructOpt, Debug, PartialEq)] 289 | #[structopt(rename_all = "screaming_snake")] 290 | enum Opt { 291 | #[structopt(rename_all = "kebab_case")] 292 | FirstVariant { 293 | #[structopt(long)] 294 | foo_option: bool, 295 | }, 296 | SecondVariant { 297 | #[structopt(rename_all = "kebab_case", long)] 298 | foo_option: bool, 299 | }, 300 | } 301 | 302 | assert_eq!( 303 | Opt::FirstVariant { foo_option: true }, 304 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "first-variant", "--foo-option"])) 305 | ); 306 | 307 | assert_eq!( 308 | Opt::SecondVariant { foo_option: true }, 309 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "SECOND_VARIANT", "--foo-option"])) 310 | ); 311 | } 312 | 313 | #[test] 314 | fn test_lower_is_renamed() { 315 | #[derive(StructOpt, Debug, PartialEq)] 316 | struct Opt { 317 | #[structopt(rename_all = "lower", long)] 318 | foo_option: bool, 319 | } 320 | 321 | assert_eq!( 322 | Opt { foo_option: true }, 323 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "--foooption"])) 324 | ); 325 | } 326 | 327 | #[test] 328 | fn test_upper_is_renamed() { 329 | #[derive(StructOpt, Debug, PartialEq)] 330 | struct Opt { 331 | #[structopt(rename_all = "upper", long)] 332 | foo_option: bool, 333 | } 334 | 335 | assert_eq!( 336 | Opt { foo_option: true }, 337 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "--FOOOPTION"])) 338 | ); 339 | } 340 | -------------------------------------------------------------------------------- /tests/arguments.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::clap; 10 | use structopt::StructOpt; 11 | 12 | #[test] 13 | fn required_argument() { 14 | #[derive(StructOpt, PartialEq, Debug)] 15 | struct Opt { 16 | arg: i32, 17 | } 18 | assert_eq!(Opt { arg: 42 }, Opt::from_iter(&["test", "42"])); 19 | assert!(Opt::clap().get_matches_from_safe(&["test"]).is_err()); 20 | assert!(Opt::clap() 21 | .get_matches_from_safe(&["test", "42", "24"]) 22 | .is_err()); 23 | } 24 | 25 | #[test] 26 | fn optional_argument() { 27 | #[derive(StructOpt, PartialEq, Debug)] 28 | struct Opt { 29 | arg: Option, 30 | } 31 | assert_eq!(Opt { arg: Some(42) }, Opt::from_iter(&["test", "42"])); 32 | assert_eq!(Opt { arg: None }, Opt::from_iter(&["test"])); 33 | assert!(Opt::clap() 34 | .get_matches_from_safe(&["test", "42", "24"]) 35 | .is_err()); 36 | } 37 | 38 | #[test] 39 | fn argument_with_default() { 40 | #[derive(StructOpt, PartialEq, Debug)] 41 | struct Opt { 42 | #[structopt(default_value = "42")] 43 | arg: i32, 44 | } 45 | assert_eq!(Opt { arg: 24 }, Opt::from_iter(&["test", "24"])); 46 | assert_eq!(Opt { arg: 42 }, Opt::from_iter(&["test"])); 47 | assert!(Opt::clap() 48 | .get_matches_from_safe(&["test", "42", "24"]) 49 | .is_err()); 50 | } 51 | 52 | #[test] 53 | fn arguments() { 54 | #[derive(StructOpt, PartialEq, Debug)] 55 | struct Opt { 56 | arg: Vec, 57 | } 58 | assert_eq!(Opt { arg: vec![24] }, Opt::from_iter(&["test", "24"])); 59 | assert_eq!(Opt { arg: vec![] }, Opt::from_iter(&["test"])); 60 | assert_eq!( 61 | Opt { arg: vec![24, 42] }, 62 | Opt::from_iter(&["test", "24", "42"]) 63 | ); 64 | } 65 | 66 | #[test] 67 | fn arguments_safe() { 68 | #[derive(StructOpt, PartialEq, Debug)] 69 | struct Opt { 70 | arg: Vec, 71 | } 72 | assert_eq!( 73 | Opt { arg: vec![24] }, 74 | Opt::from_iter_safe(&["test", "24"]).unwrap() 75 | ); 76 | assert_eq!(Opt { arg: vec![] }, Opt::from_iter_safe(&["test"]).unwrap()); 77 | assert_eq!( 78 | Opt { arg: vec![24, 42] }, 79 | Opt::from_iter_safe(&["test", "24", "42"]).unwrap() 80 | ); 81 | 82 | assert_eq!( 83 | clap::ErrorKind::ValueValidation, 84 | Opt::from_iter_safe(&["test", "NOPE"]).err().unwrap().kind 85 | ); 86 | } 87 | -------------------------------------------------------------------------------- /tests/author_version_about.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | mod utils; 10 | 11 | use structopt::StructOpt; 12 | use utils::*; 13 | 14 | #[test] 15 | fn no_author_version_about() { 16 | #[derive(StructOpt, PartialEq, Debug)] 17 | #[structopt(name = "foo", no_version)] 18 | struct Opt {} 19 | 20 | let output = get_long_help::(); 21 | assert!(output.starts_with("foo \n\nUSAGE:")); 22 | } 23 | 24 | #[test] 25 | fn use_env() { 26 | #[derive(StructOpt, PartialEq, Debug)] 27 | #[structopt(author, about)] 28 | struct Opt {} 29 | 30 | let output = get_long_help::(); 31 | assert!(output.starts_with("structopt 0.")); 32 | assert!(output.contains("Guillaume Pinot , others")); 33 | assert!(output.contains("Parse command line argument by defining a struct.")); 34 | } 35 | 36 | #[test] 37 | fn explicit_version_not_str() { 38 | const VERSION: &str = "custom version"; 39 | 40 | #[derive(StructOpt)] 41 | #[structopt(version = VERSION)] 42 | pub struct Opt {} 43 | 44 | let output = get_long_help::(); 45 | assert!(output.contains("custom version")); 46 | } 47 | 48 | #[test] 49 | fn no_version_gets_propagated() { 50 | #[derive(StructOpt, PartialEq, Debug)] 51 | #[structopt(no_version)] 52 | enum Action { 53 | Move, 54 | } 55 | 56 | let output = get_subcommand_long_help::("move"); 57 | assert_eq!(output.lines().next(), Some("test-move ")); 58 | } 59 | -------------------------------------------------------------------------------- /tests/custom-string-parsers.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | use std::ffi::{CString, OsStr, OsString}; 12 | use std::num::ParseIntError; 13 | use std::path::PathBuf; 14 | 15 | #[derive(StructOpt, PartialEq, Debug)] 16 | struct PathOpt { 17 | #[structopt(short, long, parse(from_os_str))] 18 | path: PathBuf, 19 | 20 | #[structopt(short, default_value = "../", parse(from_os_str))] 21 | default_path: PathBuf, 22 | 23 | #[structopt(short, parse(from_os_str))] 24 | vector_path: Vec, 25 | 26 | #[structopt(short, parse(from_os_str))] 27 | option_path_1: Option, 28 | 29 | #[structopt(short = "q", parse(from_os_str))] 30 | option_path_2: Option, 31 | } 32 | 33 | #[test] 34 | fn test_path_opt_simple() { 35 | assert_eq!( 36 | PathOpt { 37 | path: PathBuf::from("/usr/bin"), 38 | default_path: PathBuf::from("../"), 39 | vector_path: vec![ 40 | PathBuf::from("/a/b/c"), 41 | PathBuf::from("/d/e/f"), 42 | PathBuf::from("/g/h/i"), 43 | ], 44 | option_path_1: None, 45 | option_path_2: Some(PathBuf::from("j.zip")), 46 | }, 47 | PathOpt::from_clap(&PathOpt::clap().get_matches_from(&[ 48 | "test", "-p", "/usr/bin", "-v", "/a/b/c", "-v", "/d/e/f", "-v", "/g/h/i", "-q", 49 | "j.zip", 50 | ])) 51 | ); 52 | } 53 | 54 | fn parse_hex(input: &str) -> Result { 55 | u64::from_str_radix(input, 16) 56 | } 57 | 58 | #[derive(StructOpt, PartialEq, Debug)] 59 | struct HexOpt { 60 | #[structopt(short, parse(try_from_str = parse_hex))] 61 | number: u64, 62 | } 63 | 64 | #[test] 65 | #[allow(clippy::unreadable_literal)] 66 | fn test_parse_hex() { 67 | assert_eq!( 68 | HexOpt { number: 5 }, 69 | HexOpt::from_clap(&HexOpt::clap().get_matches_from(&["test", "-n", "5"])) 70 | ); 71 | assert_eq!( 72 | HexOpt { number: 0xabcdef }, 73 | HexOpt::from_clap(&HexOpt::clap().get_matches_from(&["test", "-n", "abcdef"])) 74 | ); 75 | 76 | let err = HexOpt::clap() 77 | .get_matches_from_safe(&["test", "-n", "gg"]) 78 | .unwrap_err(); 79 | assert!( 80 | err.message.contains("invalid digit found in string"), 81 | "{}", 82 | err 83 | ); 84 | } 85 | 86 | fn custom_parser_1(_: &str) -> &'static str { 87 | "A" 88 | } 89 | fn custom_parser_2(_: &str) -> Result<&'static str, u32> { 90 | Ok("B") 91 | } 92 | fn custom_parser_3(_: &OsStr) -> &'static str { 93 | "C" 94 | } 95 | fn custom_parser_4(_: &OsStr) -> Result<&'static str, OsString> { 96 | Ok("D") 97 | } 98 | 99 | #[derive(StructOpt, PartialEq, Debug)] 100 | struct NoOpOpt { 101 | #[structopt(short, parse(from_str = custom_parser_1))] 102 | a: &'static str, 103 | #[structopt(short, parse(try_from_str = custom_parser_2))] 104 | b: &'static str, 105 | #[structopt(short, parse(from_os_str = custom_parser_3))] 106 | c: &'static str, 107 | #[structopt(short, parse(try_from_os_str = custom_parser_4))] 108 | d: &'static str, 109 | } 110 | 111 | #[test] 112 | fn test_every_custom_parser() { 113 | assert_eq!( 114 | NoOpOpt { 115 | a: "A", 116 | b: "B", 117 | c: "C", 118 | d: "D" 119 | }, 120 | NoOpOpt::from_clap( 121 | &NoOpOpt::clap().get_matches_from(&["test", "-a=?", "-b=?", "-c=?", "-d=?"]) 122 | ) 123 | ); 124 | } 125 | 126 | // Note: can't use `Vec` directly, as structopt would instead look for 127 | // conversion function from `&str` to `u8`. 128 | type Bytes = Vec; 129 | 130 | #[derive(StructOpt, PartialEq, Debug)] 131 | struct DefaultedOpt { 132 | #[structopt(short, parse(from_str))] 133 | bytes: Bytes, 134 | 135 | #[structopt(short, parse(try_from_str))] 136 | integer: u64, 137 | 138 | #[structopt(short, parse(from_os_str))] 139 | path: PathBuf, 140 | } 141 | 142 | #[test] 143 | fn test_parser_with_default_value() { 144 | assert_eq!( 145 | DefaultedOpt { 146 | bytes: b"E\xc2\xb2=p\xc2\xb2c\xc2\xb2+m\xc2\xb2c\xe2\x81\xb4".to_vec(), 147 | integer: 9000, 148 | path: PathBuf::from("src/lib.rs"), 149 | }, 150 | DefaultedOpt::from_clap(&DefaultedOpt::clap().get_matches_from(&[ 151 | "test", 152 | "-b", 153 | "E²=p²c²+m²c⁴", 154 | "-i", 155 | "9000", 156 | "-p", 157 | "src/lib.rs", 158 | ])) 159 | ); 160 | } 161 | 162 | #[derive(PartialEq, Debug)] 163 | struct Foo(u8); 164 | 165 | fn foo(value: u64) -> Foo { 166 | Foo(value as u8) 167 | } 168 | 169 | #[derive(StructOpt, PartialEq, Debug)] 170 | struct Occurrences { 171 | #[structopt(short, long, parse(from_occurrences))] 172 | signed: i32, 173 | 174 | #[structopt(short, parse(from_occurrences))] 175 | little_signed: i8, 176 | 177 | #[structopt(short, parse(from_occurrences))] 178 | unsigned: usize, 179 | 180 | #[structopt(short = "r", parse(from_occurrences))] 181 | little_unsigned: u8, 182 | 183 | #[structopt(short, long, parse(from_occurrences = foo))] 184 | custom: Foo, 185 | } 186 | 187 | #[test] 188 | fn test_parser_occurrences() { 189 | assert_eq!( 190 | Occurrences { 191 | signed: 3, 192 | little_signed: 1, 193 | unsigned: 0, 194 | little_unsigned: 4, 195 | custom: Foo(5), 196 | }, 197 | Occurrences::from_clap(&Occurrences::clap().get_matches_from(&[ 198 | "test", "-s", "--signed", "--signed", "-l", "-rrrr", "-cccc", "--custom", 199 | ])) 200 | ); 201 | } 202 | 203 | #[test] 204 | fn test_custom_bool() { 205 | fn parse_bool(s: &str) -> Result { 206 | match s { 207 | "true" => Ok(true), 208 | "false" => Ok(false), 209 | _ => Err(format!("invalid bool {}", s)), 210 | } 211 | } 212 | #[derive(StructOpt, PartialEq, Debug)] 213 | struct Opt { 214 | #[structopt(short, parse(try_from_str = parse_bool))] 215 | debug: bool, 216 | #[structopt( 217 | short, 218 | default_value = "false", 219 | parse(try_from_str = parse_bool) 220 | )] 221 | verbose: bool, 222 | #[structopt(short, parse(try_from_str = parse_bool))] 223 | tribool: Option, 224 | #[structopt(short, parse(try_from_str = parse_bool))] 225 | bitset: Vec, 226 | } 227 | 228 | assert!(Opt::clap().get_matches_from_safe(&["test"]).is_err()); 229 | assert!(Opt::clap().get_matches_from_safe(&["test", "-d"]).is_err()); 230 | assert!(Opt::clap() 231 | .get_matches_from_safe(&["test", "-dfoo"]) 232 | .is_err()); 233 | assert_eq!( 234 | Opt { 235 | debug: false, 236 | verbose: false, 237 | tribool: None, 238 | bitset: vec![], 239 | }, 240 | Opt::from_iter(&["test", "-dfalse"]) 241 | ); 242 | assert_eq!( 243 | Opt { 244 | debug: true, 245 | verbose: false, 246 | tribool: None, 247 | bitset: vec![], 248 | }, 249 | Opt::from_iter(&["test", "-dtrue"]) 250 | ); 251 | assert_eq!( 252 | Opt { 253 | debug: true, 254 | verbose: false, 255 | tribool: None, 256 | bitset: vec![], 257 | }, 258 | Opt::from_iter(&["test", "-dtrue", "-vfalse"]) 259 | ); 260 | assert_eq!( 261 | Opt { 262 | debug: true, 263 | verbose: true, 264 | tribool: None, 265 | bitset: vec![], 266 | }, 267 | Opt::from_iter(&["test", "-dtrue", "-vtrue"]) 268 | ); 269 | assert_eq!( 270 | Opt { 271 | debug: true, 272 | verbose: false, 273 | tribool: Some(false), 274 | bitset: vec![], 275 | }, 276 | Opt::from_iter(&["test", "-dtrue", "-tfalse"]) 277 | ); 278 | assert_eq!( 279 | Opt { 280 | debug: true, 281 | verbose: false, 282 | tribool: Some(true), 283 | bitset: vec![], 284 | }, 285 | Opt::from_iter(&["test", "-dtrue", "-ttrue"]) 286 | ); 287 | assert_eq!( 288 | Opt { 289 | debug: true, 290 | verbose: false, 291 | tribool: None, 292 | bitset: vec![false, true, false, false], 293 | }, 294 | Opt::from_iter(&["test", "-dtrue", "-bfalse", "-btrue", "-bfalse", "-bfalse"]) 295 | ); 296 | } 297 | 298 | #[test] 299 | fn test_cstring() { 300 | #[derive(StructOpt)] 301 | struct Opt { 302 | #[structopt(parse(try_from_str = CString::new))] 303 | c_string: CString, 304 | } 305 | assert!(Opt::clap().get_matches_from_safe(&["test"]).is_err()); 306 | assert_eq!(Opt::from_iter(&["test", "bla"]).c_string.to_bytes(), b"bla"); 307 | assert!(Opt::clap() 308 | .get_matches_from_safe(&["test", "bla\0bla"]) 309 | .is_err()); 310 | } 311 | -------------------------------------------------------------------------------- /tests/default_value.rs: -------------------------------------------------------------------------------- 1 | use structopt::StructOpt; 2 | 3 | mod utils; 4 | 5 | use utils::*; 6 | 7 | #[test] 8 | fn auto_default_value() { 9 | #[derive(StructOpt, PartialEq, Debug)] 10 | struct Opt { 11 | #[structopt(default_value)] 12 | arg: i32, 13 | } 14 | assert_eq!(Opt { arg: 0 }, Opt::from_iter(&["test"])); 15 | assert_eq!(Opt { arg: 1 }, Opt::from_iter(&["test", "1"])); 16 | 17 | let help = get_long_help::(); 18 | assert!(help.contains("[default: 0]")); 19 | } 20 | -------------------------------------------------------------------------------- /tests/deny-warnings.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | #![deny(warnings)] 10 | 11 | use structopt::StructOpt; 12 | 13 | fn try_str(s: &str) -> Result { 14 | Ok(s.into()) 15 | } 16 | 17 | #[test] 18 | fn warning_never_struct() { 19 | #[derive(Debug, PartialEq, StructOpt)] 20 | struct Opt { 21 | #[structopt(parse(try_from_str = try_str))] 22 | s: String, 23 | } 24 | assert_eq!( 25 | Opt { 26 | s: "foo".to_string() 27 | }, 28 | Opt::from_iter(&["test", "foo"]) 29 | ); 30 | } 31 | 32 | #[test] 33 | fn warning_never_enum() { 34 | #[derive(Debug, PartialEq, StructOpt)] 35 | enum Opt { 36 | Foo { 37 | #[structopt(parse(try_from_str = try_str))] 38 | s: String, 39 | }, 40 | } 41 | assert_eq!( 42 | Opt::Foo { 43 | s: "foo".to_string() 44 | }, 45 | Opt::from_iter(&["test", "foo", "foo"]) 46 | ); 47 | } 48 | -------------------------------------------------------------------------------- /tests/doc-comments-help.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | mod utils; 10 | 11 | use structopt::StructOpt; 12 | use utils::*; 13 | 14 | #[test] 15 | fn doc_comments() { 16 | /// Lorem ipsum 17 | #[derive(StructOpt, PartialEq, Debug)] 18 | struct LoremIpsum { 19 | /// Fooify a bar 20 | /// and a baz 21 | #[structopt(short, long)] 22 | foo: bool, 23 | } 24 | 25 | let help = get_long_help::(); 26 | assert!(help.contains("Lorem ipsum")); 27 | assert!(help.contains("Fooify a bar and a baz")); 28 | } 29 | 30 | #[test] 31 | fn help_is_better_than_comments() { 32 | /// Lorem ipsum 33 | #[derive(StructOpt, PartialEq, Debug)] 34 | #[structopt(name = "lorem-ipsum", about = "Dolor sit amet")] 35 | struct LoremIpsum { 36 | /// Fooify a bar 37 | #[structopt(short, long, help = "DO NOT PASS A BAR UNDER ANY CIRCUMSTANCES")] 38 | foo: bool, 39 | } 40 | 41 | let help = get_long_help::(); 42 | assert!(help.contains("Dolor sit amet")); 43 | assert!(!help.contains("Lorem ipsum")); 44 | assert!(help.contains("DO NOT PASS A BAR")); 45 | } 46 | 47 | #[test] 48 | fn empty_line_in_doc_comment_is_double_linefeed() { 49 | /// Foo. 50 | /// 51 | /// Bar 52 | #[derive(StructOpt, PartialEq, Debug)] 53 | #[structopt(name = "lorem-ipsum", no_version)] 54 | struct LoremIpsum {} 55 | 56 | let help = get_long_help::(); 57 | assert!(help.starts_with("lorem-ipsum \nFoo.\n\nBar\n\nUSAGE:")); 58 | } 59 | 60 | #[test] 61 | fn field_long_doc_comment_both_help_long_help() { 62 | /// Lorem ipsumclap 63 | #[derive(StructOpt, PartialEq, Debug)] 64 | #[structopt(name = "lorem-ipsum", about = "Dolor sit amet")] 65 | struct LoremIpsum { 66 | /// Dot is removed from multiline comments. 67 | /// 68 | /// Long help 69 | #[structopt(long)] 70 | foo: bool, 71 | 72 | /// Dot is removed from one short comment. 73 | #[structopt(long)] 74 | bar: bool, 75 | } 76 | 77 | let short_help = get_help::(); 78 | let long_help = get_long_help::(); 79 | 80 | assert!(short_help.contains("Dot is removed from one short comment")); 81 | assert!(!short_help.contains("Dot is removed from one short comment.")); 82 | assert!(short_help.contains("Dot is removed from multiline comments")); 83 | assert!(!short_help.contains("Dot is removed from multiline comments.")); 84 | assert!(long_help.contains("Long help")); 85 | assert!(!short_help.contains("Long help")); 86 | } 87 | 88 | #[test] 89 | fn top_long_doc_comment_both_help_long_help() { 90 | /// Lorem ipsumclap 91 | #[derive(StructOpt, Debug)] 92 | #[structopt(name = "lorem-ipsum", about = "Dolor sit amet")] 93 | struct LoremIpsum { 94 | #[structopt(subcommand)] 95 | foo: SubCommand, 96 | } 97 | 98 | #[derive(StructOpt, Debug)] 99 | pub enum SubCommand { 100 | /// DO NOT PASS A BAR UNDER ANY CIRCUMSTANCES 101 | /// 102 | /// Or something else 103 | Foo { 104 | #[structopt(help = "foo")] 105 | bars: Vec, 106 | }, 107 | } 108 | 109 | let short_help = get_help::(); 110 | let long_help = get_subcommand_long_help::("foo"); 111 | 112 | assert!(!short_help.contains("Or something else")); 113 | assert!(long_help.contains("DO NOT PASS A BAR UNDER ANY CIRCUMSTANCES")); 114 | assert!(long_help.contains("Or something else")); 115 | } 116 | 117 | #[test] 118 | fn verbatim_doc_comment() { 119 | /// DANCE! 120 | /// 121 | /// () 122 | /// | 123 | /// ( () ) 124 | /// ) ________ // ) 125 | /// () |\ \ // 126 | /// ( \\__ \ ______\// 127 | /// \__) | | 128 | /// | | | 129 | /// \ | | 130 | /// \|_______| 131 | /// // \\ 132 | /// (( || 133 | /// \\ || 134 | /// ( () || 135 | /// ( () ) ) 136 | #[derive(StructOpt, Debug)] 137 | #[structopt(verbatim_doc_comment)] 138 | struct SeeFigure1 { 139 | #[structopt(long)] 140 | foo: bool, 141 | } 142 | 143 | let help = get_long_help::(); 144 | let sample = r#" 145 | () 146 | | 147 | ( () ) 148 | ) ________ // ) 149 | () |\ \ // 150 | ( \\__ \ ______\// 151 | \__) | | 152 | | | | 153 | \ | | 154 | \|_______| 155 | // \\ 156 | (( || 157 | \\ || 158 | ( () || 159 | ( () ) )"#; 160 | 161 | assert!(help.contains(sample)) 162 | } 163 | 164 | #[test] 165 | fn verbatim_doc_comment_field() { 166 | #[derive(StructOpt, Debug)] 167 | struct App { 168 | /// This help ends in a period. 169 | #[structopt(long, verbatim_doc_comment)] 170 | foo: bool, 171 | /// This help does not end in a period. 172 | #[structopt(long)] 173 | bar: bool, 174 | } 175 | 176 | let help = get_long_help::(); 177 | let sample = r#" 178 | --bar 179 | This help does not end in a period 180 | 181 | --foo 182 | This help ends in a period."#; 183 | 184 | assert!(help.contains(sample)) 185 | } 186 | -------------------------------------------------------------------------------- /tests/explicit_name_no_renaming.rs: -------------------------------------------------------------------------------- 1 | mod utils; 2 | 3 | use structopt::StructOpt; 4 | use utils::*; 5 | 6 | #[test] 7 | fn explicit_short_long_no_rename() { 8 | #[derive(StructOpt, PartialEq, Debug)] 9 | struct Opt { 10 | #[structopt(short = ".", long = ".foo")] 11 | foo: Vec, 12 | } 13 | 14 | assert_eq!( 15 | Opt { 16 | foo: vec!["short".into(), "long".into()] 17 | }, 18 | Opt::from_iter(&["test", "-.", "short", "--.foo", "long"]) 19 | ); 20 | } 21 | 22 | #[test] 23 | fn explicit_name_no_rename() { 24 | #[derive(StructOpt, PartialEq, Debug)] 25 | struct Opt { 26 | #[structopt(name = ".options")] 27 | foo: Vec, 28 | } 29 | 30 | let help = get_long_help::(); 31 | assert!(help.contains("[.options]...")) 32 | } 33 | -------------------------------------------------------------------------------- /tests/flags.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[test] 12 | fn unique_flag() { 13 | #[derive(StructOpt, PartialEq, Debug)] 14 | struct Opt { 15 | #[structopt(short, long)] 16 | alice: bool, 17 | } 18 | 19 | assert_eq!( 20 | Opt { alice: false }, 21 | Opt::from_clap(&Opt::clap().get_matches_from(&["test"])) 22 | ); 23 | assert_eq!( 24 | Opt { alice: true }, 25 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a"])) 26 | ); 27 | assert_eq!( 28 | Opt { alice: true }, 29 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "--alice"])) 30 | ); 31 | assert!(Opt::clap().get_matches_from_safe(&["test", "-i"]).is_err()); 32 | assert!(Opt::clap() 33 | .get_matches_from_safe(&["test", "-a", "foo"]) 34 | .is_err()); 35 | assert!(Opt::clap() 36 | .get_matches_from_safe(&["test", "-a", "-a"]) 37 | .is_err()); 38 | assert!(Opt::clap() 39 | .get_matches_from_safe(&["test", "-a", "--alice"]) 40 | .is_err()); 41 | } 42 | 43 | #[test] 44 | fn multiple_flag() { 45 | #[derive(StructOpt, PartialEq, Debug)] 46 | struct Opt { 47 | #[structopt(short, long, parse(from_occurrences))] 48 | alice: u64, 49 | #[structopt(short, long, parse(from_occurrences))] 50 | bob: u8, 51 | } 52 | 53 | assert_eq!( 54 | Opt { alice: 0, bob: 0 }, 55 | Opt::from_clap(&Opt::clap().get_matches_from(&["test"])) 56 | ); 57 | assert_eq!( 58 | Opt { alice: 1, bob: 0 }, 59 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a"])) 60 | ); 61 | assert_eq!( 62 | Opt { alice: 2, bob: 0 }, 63 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a", "-a"])) 64 | ); 65 | assert_eq!( 66 | Opt { alice: 2, bob: 2 }, 67 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a", "--alice", "-bb"])) 68 | ); 69 | assert_eq!( 70 | Opt { alice: 3, bob: 1 }, 71 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-aaa", "--bob"])) 72 | ); 73 | assert!(Opt::clap().get_matches_from_safe(&["test", "-i"]).is_err()); 74 | assert!(Opt::clap() 75 | .get_matches_from_safe(&["test", "-a", "foo"]) 76 | .is_err()); 77 | } 78 | 79 | fn parse_from_flag(b: bool) -> std::sync::atomic::AtomicBool { 80 | std::sync::atomic::AtomicBool::new(b) 81 | } 82 | 83 | #[test] 84 | fn non_bool_flags() { 85 | #[derive(StructOpt, Debug)] 86 | struct Opt { 87 | #[structopt(short, long, parse(from_flag = parse_from_flag))] 88 | alice: std::sync::atomic::AtomicBool, 89 | #[structopt(short, long, parse(from_flag))] 90 | bob: std::sync::atomic::AtomicBool, 91 | } 92 | 93 | let falsey = Opt::from_clap(&Opt::clap().get_matches_from(&["test"])); 94 | assert!(!falsey.alice.load(std::sync::atomic::Ordering::Relaxed)); 95 | assert!(!falsey.bob.load(std::sync::atomic::Ordering::Relaxed)); 96 | 97 | let alice = Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a"])); 98 | assert!(alice.alice.load(std::sync::atomic::Ordering::Relaxed)); 99 | assert!(!alice.bob.load(std::sync::atomic::Ordering::Relaxed)); 100 | 101 | let bob = Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-b"])); 102 | assert!(!bob.alice.load(std::sync::atomic::Ordering::Relaxed)); 103 | assert!(bob.bob.load(std::sync::atomic::Ordering::Relaxed)); 104 | 105 | let both = Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-b", "-a"])); 106 | assert!(both.alice.load(std::sync::atomic::Ordering::Relaxed)); 107 | assert!(both.bob.load(std::sync::atomic::Ordering::Relaxed)); 108 | } 109 | 110 | #[test] 111 | fn combined_flags() { 112 | #[derive(StructOpt, PartialEq, Debug)] 113 | struct Opt { 114 | #[structopt(short, long)] 115 | alice: bool, 116 | #[structopt(short, long, parse(from_occurrences))] 117 | bob: u64, 118 | } 119 | 120 | assert_eq!( 121 | Opt { 122 | alice: false, 123 | bob: 0 124 | }, 125 | Opt::from_clap(&Opt::clap().get_matches_from(&["test"])) 126 | ); 127 | assert_eq!( 128 | Opt { 129 | alice: true, 130 | bob: 0 131 | }, 132 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a"])) 133 | ); 134 | assert_eq!( 135 | Opt { 136 | alice: true, 137 | bob: 0 138 | }, 139 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a"])) 140 | ); 141 | assert_eq!( 142 | Opt { 143 | alice: false, 144 | bob: 1 145 | }, 146 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-b"])) 147 | ); 148 | assert_eq!( 149 | Opt { 150 | alice: true, 151 | bob: 1 152 | }, 153 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "--alice", "--bob"])) 154 | ); 155 | assert_eq!( 156 | Opt { 157 | alice: true, 158 | bob: 4 159 | }, 160 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-bb", "-a", "-bb"])) 161 | ); 162 | } 163 | -------------------------------------------------------------------------------- /tests/flatten.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | mod utils; 12 | 13 | #[test] 14 | fn flatten() { 15 | #[derive(StructOpt, PartialEq, Debug)] 16 | struct Common { 17 | arg: i32, 18 | } 19 | 20 | #[derive(StructOpt, PartialEq, Debug)] 21 | struct Opt { 22 | #[structopt(flatten)] 23 | common: Common, 24 | } 25 | assert_eq!( 26 | Opt { 27 | common: Common { arg: 42 } 28 | }, 29 | Opt::from_iter(&["test", "42"]) 30 | ); 31 | assert!(Opt::clap().get_matches_from_safe(&["test"]).is_err()); 32 | assert!(Opt::clap() 33 | .get_matches_from_safe(&["test", "42", "24"]) 34 | .is_err()); 35 | } 36 | 37 | #[test] 38 | #[should_panic] 39 | fn flatten_twice() { 40 | #[derive(StructOpt, PartialEq, Debug)] 41 | struct Common { 42 | arg: i32, 43 | } 44 | 45 | #[derive(StructOpt, PartialEq, Debug)] 46 | struct Opt { 47 | #[structopt(flatten)] 48 | c1: Common, 49 | // Defines "arg" twice, so this should not work. 50 | #[structopt(flatten)] 51 | c2: Common, 52 | } 53 | Opt::from_iter(&["test", "42", "43"]); 54 | } 55 | 56 | #[test] 57 | fn flatten_in_subcommand() { 58 | #[derive(StructOpt, PartialEq, Debug)] 59 | struct Common { 60 | arg: i32, 61 | } 62 | 63 | #[derive(StructOpt, PartialEq, Debug)] 64 | struct Add { 65 | #[structopt(short)] 66 | interactive: bool, 67 | #[structopt(flatten)] 68 | common: Common, 69 | } 70 | 71 | #[derive(StructOpt, PartialEq, Debug)] 72 | enum Opt { 73 | Fetch { 74 | #[structopt(short)] 75 | all: bool, 76 | #[structopt(flatten)] 77 | common: Common, 78 | }, 79 | 80 | Add(Add), 81 | } 82 | 83 | assert_eq!( 84 | Opt::Fetch { 85 | all: false, 86 | common: Common { arg: 42 } 87 | }, 88 | Opt::from_iter(&["test", "fetch", "42"]) 89 | ); 90 | assert_eq!( 91 | Opt::Add(Add { 92 | interactive: true, 93 | common: Common { arg: 43 } 94 | }), 95 | Opt::from_iter(&["test", "add", "-i", "43"]) 96 | ); 97 | } 98 | 99 | #[test] 100 | fn merge_subcommands_with_flatten() { 101 | #[derive(StructOpt, PartialEq, Debug)] 102 | enum BaseCli { 103 | Command1(Command1), 104 | } 105 | 106 | #[derive(StructOpt, PartialEq, Debug)] 107 | struct Command1 { 108 | arg1: i32, 109 | } 110 | 111 | #[derive(StructOpt, PartialEq, Debug)] 112 | struct Command2 { 113 | arg2: i32, 114 | } 115 | 116 | #[derive(StructOpt, PartialEq, Debug)] 117 | enum Opt { 118 | #[structopt(flatten)] 119 | BaseCli(BaseCli), 120 | Command2(Command2), 121 | } 122 | 123 | assert_eq!( 124 | Opt::BaseCli(BaseCli::Command1(Command1 { arg1: 42 })), 125 | Opt::from_iter(&["test", "command1", "42"]) 126 | ); 127 | assert_eq!( 128 | Opt::Command2(Command2 { arg2: 43 }), 129 | Opt::from_iter(&["test", "command2", "43"]) 130 | ); 131 | } 132 | 133 | #[test] 134 | #[should_panic = "structopt misuse: You likely tried to #[flatten] a struct \ 135 | that contains #[subcommand]. This is forbidden."] 136 | fn subcommand_in_flatten() { 137 | #[derive(Debug, StructOpt)] 138 | pub enum Struct1 { 139 | #[structopt(flatten)] 140 | Struct1(Struct2), 141 | } 142 | 143 | #[derive(Debug, StructOpt)] 144 | pub struct Struct2 { 145 | #[structopt(subcommand)] 146 | command_type: Enum3, 147 | } 148 | 149 | #[derive(Debug, StructOpt)] 150 | pub enum Enum3 { 151 | Command { args: Vec }, 152 | } 153 | 154 | Struct1::from_iter(&["test", "command", "foo"]); 155 | } 156 | 157 | #[test] 158 | fn flatten_doc_comment() { 159 | #[derive(StructOpt, PartialEq, Debug)] 160 | struct Common { 161 | /// This is an arg. Arg means "argument". Command line argument. 162 | arg: i32, 163 | } 164 | 165 | #[derive(StructOpt, PartialEq, Debug)] 166 | struct Opt { 167 | /// The very important comment that clippy had me put here. 168 | /// It knows better. 169 | #[structopt(flatten)] 170 | common: Common, 171 | } 172 | assert_eq!( 173 | Opt { 174 | common: Common { arg: 42 } 175 | }, 176 | Opt::from_iter(&["test", "42"]) 177 | ); 178 | 179 | let help = utils::get_help::(); 180 | assert!(help.contains("This is an arg.")); 181 | assert!(!help.contains("The very important")); 182 | } 183 | -------------------------------------------------------------------------------- /tests/generics.rs: -------------------------------------------------------------------------------- 1 | use structopt::StructOpt; 2 | 3 | #[test] 4 | fn generic_struct_flatten() { 5 | #[derive(StructOpt, PartialEq, Debug)] 6 | struct Inner { 7 | pub answer: isize, 8 | } 9 | 10 | #[derive(StructOpt, PartialEq, Debug)] 11 | struct Outer { 12 | #[structopt(flatten)] 13 | pub inner: T, 14 | } 15 | 16 | assert_eq!( 17 | Outer { 18 | inner: Inner { answer: 42 } 19 | }, 20 | Outer::from_iter(&["--answer", "42"]) 21 | ) 22 | } 23 | 24 | #[test] 25 | fn generic_struct_flatten_w_where_clause() { 26 | #[derive(StructOpt, PartialEq, Debug)] 27 | struct Inner { 28 | pub answer: isize, 29 | } 30 | 31 | #[derive(StructOpt, PartialEq, Debug)] 32 | struct Outer 33 | where 34 | T: StructOpt, 35 | { 36 | #[structopt(flatten)] 37 | pub inner: T, 38 | } 39 | 40 | assert_eq!( 41 | Outer { 42 | inner: Inner { answer: 42 } 43 | }, 44 | Outer::from_iter(&["--answer", "42"]) 45 | ) 46 | } 47 | 48 | #[test] 49 | fn generic_enum() { 50 | #[derive(StructOpt, PartialEq, Debug)] 51 | struct Inner { 52 | pub answer: isize, 53 | } 54 | 55 | #[derive(StructOpt, PartialEq, Debug)] 56 | enum GenericEnum { 57 | Start(T), 58 | Stop, 59 | } 60 | 61 | assert_eq!( 62 | GenericEnum::Start(Inner { answer: 42 }), 63 | GenericEnum::from_iter(&["test", "start", "42"]) 64 | ) 65 | } 66 | 67 | #[test] 68 | fn generic_enum_w_where_clause() { 69 | #[derive(StructOpt, PartialEq, Debug)] 70 | struct Inner { 71 | pub answer: isize, 72 | } 73 | 74 | #[derive(StructOpt, PartialEq, Debug)] 75 | enum GenericEnum 76 | where 77 | T: StructOpt, 78 | { 79 | Start(T), 80 | Stop, 81 | } 82 | 83 | assert_eq!( 84 | GenericEnum::Start(Inner { answer: 42 }), 85 | GenericEnum::from_iter(&["test", "start", "42"]) 86 | ) 87 | } 88 | 89 | #[test] 90 | fn generic_w_fromstr_trait_bound() { 91 | use std::{fmt, str::FromStr}; 92 | 93 | #[derive(StructOpt, PartialEq, Debug)] 94 | struct Opt 95 | where 96 | T: FromStr, 97 | ::Err: fmt::Debug + fmt::Display, 98 | { 99 | answer: T, 100 | } 101 | 102 | assert_eq!( 103 | Opt:: { answer: 42 }, 104 | Opt::::from_iter(&["--answer", "42"]) 105 | ) 106 | } 107 | 108 | #[test] 109 | fn generic_wo_trait_bound() { 110 | use std::time::Duration; 111 | 112 | #[derive(StructOpt, PartialEq, Debug)] 113 | struct Opt { 114 | answer: isize, 115 | #[structopt(skip)] 116 | took: Option, 117 | } 118 | 119 | assert_eq!( 120 | Opt:: { 121 | answer: 42, 122 | took: None 123 | }, 124 | Opt::::from_iter(&["--answer", "42"]) 125 | ) 126 | } 127 | 128 | #[test] 129 | fn generic_where_clause_w_trailing_comma() { 130 | use std::{fmt, str::FromStr}; 131 | 132 | #[derive(StructOpt, PartialEq, Debug)] 133 | struct Opt 134 | where 135 | T: FromStr, 136 | ::Err: fmt::Debug + fmt::Display, 137 | { 138 | pub answer: T, 139 | } 140 | 141 | assert_eq!( 142 | Opt:: { answer: 42 }, 143 | Opt::::from_iter(&["--answer", "42"]) 144 | ) 145 | } 146 | -------------------------------------------------------------------------------- /tests/issues.rs: -------------------------------------------------------------------------------- 1 | // https://github.com/TeXitoi/structopt/issues/{NUMBER} 2 | 3 | mod utils; 4 | use utils::*; 5 | 6 | use structopt::StructOpt; 7 | 8 | #[test] 9 | fn issue_151() { 10 | use structopt::{clap::ArgGroup, StructOpt}; 11 | 12 | #[derive(StructOpt, Debug)] 13 | #[structopt(group = ArgGroup::with_name("verb").required(true).multiple(true))] 14 | struct Opt { 15 | #[structopt(long, group = "verb")] 16 | foo: bool, 17 | #[structopt(long, group = "verb")] 18 | bar: bool, 19 | } 20 | 21 | #[derive(Debug, StructOpt)] 22 | struct Cli { 23 | #[structopt(flatten)] 24 | a: Opt, 25 | } 26 | 27 | assert!(Cli::clap().get_matches_from_safe(&["test"]).is_err()); 28 | assert!(Cli::clap() 29 | .get_matches_from_safe(&["test", "--foo"]) 30 | .is_ok()); 31 | assert!(Cli::clap() 32 | .get_matches_from_safe(&["test", "--bar"]) 33 | .is_ok()); 34 | assert!(Cli::clap() 35 | .get_matches_from_safe(&["test", "--zebra"]) 36 | .is_err()); 37 | assert!(Cli::clap() 38 | .get_matches_from_safe(&["test", "--foo", "--bar"]) 39 | .is_ok()); 40 | } 41 | 42 | #[test] 43 | fn issue_289() { 44 | use structopt::{clap::AppSettings, StructOpt}; 45 | 46 | #[derive(StructOpt)] 47 | #[structopt(setting = AppSettings::InferSubcommands)] 48 | enum Args { 49 | SomeCommand(SubSubCommand), 50 | AnotherCommand, 51 | } 52 | 53 | #[derive(StructOpt)] 54 | #[structopt(setting = AppSettings::InferSubcommands)] 55 | enum SubSubCommand { 56 | TestCommand, 57 | } 58 | 59 | assert!(Args::clap() 60 | .get_matches_from_safe(&["test", "some-command", "test-command"]) 61 | .is_ok()); 62 | assert!(Args::clap() 63 | .get_matches_from_safe(&["test", "some", "test-command"]) 64 | .is_ok()); 65 | assert!(Args::clap() 66 | .get_matches_from_safe(&["test", "some-command", "test"]) 67 | .is_ok()); 68 | assert!(Args::clap() 69 | .get_matches_from_safe(&["test", "some", "test"]) 70 | .is_ok()); 71 | } 72 | 73 | #[test] 74 | fn issue_324() { 75 | fn my_version() -> &'static str { 76 | "MY_VERSION" 77 | } 78 | 79 | #[derive(StructOpt)] 80 | #[structopt(version = my_version())] 81 | struct Opt { 82 | #[structopt(subcommand)] 83 | _cmd: Option, 84 | } 85 | 86 | #[derive(StructOpt)] 87 | enum SubCommand { 88 | Start, 89 | } 90 | 91 | let help = get_long_help::(); 92 | assert!(help.contains("MY_VERSION")); 93 | } 94 | 95 | #[test] 96 | fn issue_359() { 97 | #[derive(Debug, PartialEq, StructOpt)] 98 | struct Opt { 99 | #[structopt(subcommand)] 100 | sub: Subcommands, 101 | } 102 | 103 | #[derive(Debug, PartialEq, StructOpt)] 104 | enum Subcommands { 105 | Add, 106 | 107 | #[structopt(external_subcommand)] 108 | Other(Vec), 109 | } 110 | 111 | assert_eq!( 112 | Opt { 113 | sub: Subcommands::Other(vec!["only_one_arg".into()]) 114 | }, 115 | Opt::from_iter(&["test", "only_one_arg"]) 116 | ); 117 | } 118 | 119 | #[test] 120 | fn issue_418() { 121 | use structopt::StructOpt; 122 | 123 | #[derive(Debug, StructOpt)] 124 | struct Opts { 125 | #[structopt(subcommand)] 126 | /// The command to run 127 | command: Command, 128 | } 129 | 130 | #[derive(Debug, StructOpt)] 131 | enum Command { 132 | /// Reticulate the splines 133 | #[structopt(visible_alias = "ret")] 134 | Reticulate { 135 | /// How many splines 136 | num_splines: u8, 137 | }, 138 | /// Frobnicate the rest 139 | #[structopt(visible_alias = "frob")] 140 | Frobnicate, 141 | } 142 | 143 | let help = get_long_help::(); 144 | assert!(help.contains("Reticulate the splines [aliases: ret]")); 145 | } 146 | 147 | #[test] 148 | fn issue_490() { 149 | use std::iter::FromIterator; 150 | use std::str::FromStr; 151 | use structopt::StructOpt; 152 | 153 | struct U16ish; 154 | impl FromStr for U16ish { 155 | type Err = (); 156 | fn from_str(_: &str) -> Result { 157 | unimplemented!() 158 | } 159 | } 160 | impl<'a> FromIterator<&'a U16ish> for Vec { 161 | fn from_iter>(_: T) -> Self { 162 | unimplemented!() 163 | } 164 | } 165 | 166 | #[derive(StructOpt, Debug)] 167 | struct Opt { 168 | opt_vec: Vec, 169 | #[structopt(long)] 170 | opt_opt_vec: Option>, 171 | } 172 | 173 | // Assert that it compiles 174 | } 175 | -------------------------------------------------------------------------------- /tests/macro-errors.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | 8 | #[rustversion::attr(any(not(stable), before(1.54)), ignore)] 9 | #[test] 10 | fn ui() { 11 | let t = trybuild::TestCases::new(); 12 | t.compile_fail("tests/ui/*.rs"); 13 | } 14 | -------------------------------------------------------------------------------- /tests/nested-subcommands.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, PartialEq, Debug)] 12 | struct Opt { 13 | #[structopt(short, long)] 14 | force: bool, 15 | #[structopt(short, long, parse(from_occurrences))] 16 | verbose: u64, 17 | #[structopt(subcommand)] 18 | cmd: Sub, 19 | } 20 | 21 | #[derive(StructOpt, PartialEq, Debug)] 22 | enum Sub { 23 | Fetch {}, 24 | Add {}, 25 | } 26 | 27 | #[derive(StructOpt, PartialEq, Debug)] 28 | struct Opt2 { 29 | #[structopt(short, long)] 30 | force: bool, 31 | #[structopt(short, long, parse(from_occurrences))] 32 | verbose: u64, 33 | #[structopt(subcommand)] 34 | cmd: Option, 35 | } 36 | 37 | #[test] 38 | fn test_no_cmd() { 39 | let result = Opt::clap().get_matches_from_safe(&["test"]); 40 | assert!(result.is_err()); 41 | 42 | assert_eq!( 43 | Opt2 { 44 | force: false, 45 | verbose: 0, 46 | cmd: None 47 | }, 48 | Opt2::from_clap(&Opt2::clap().get_matches_from(&["test"])) 49 | ); 50 | } 51 | 52 | #[test] 53 | fn test_fetch() { 54 | assert_eq!( 55 | Opt { 56 | force: false, 57 | verbose: 3, 58 | cmd: Sub::Fetch {} 59 | }, 60 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-vvv", "fetch"])) 61 | ); 62 | assert_eq!( 63 | Opt { 64 | force: true, 65 | verbose: 0, 66 | cmd: Sub::Fetch {} 67 | }, 68 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "--force", "fetch"])) 69 | ); 70 | } 71 | 72 | #[test] 73 | fn test_add() { 74 | assert_eq!( 75 | Opt { 76 | force: false, 77 | verbose: 0, 78 | cmd: Sub::Add {} 79 | }, 80 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "add"])) 81 | ); 82 | assert_eq!( 83 | Opt { 84 | force: false, 85 | verbose: 2, 86 | cmd: Sub::Add {} 87 | }, 88 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-vv", "add"])) 89 | ); 90 | } 91 | 92 | #[test] 93 | fn test_badinput() { 94 | let result = Opt::clap().get_matches_from_safe(&["test", "badcmd"]); 95 | assert!(result.is_err()); 96 | let result = Opt::clap().get_matches_from_safe(&["test", "add", "--verbose"]); 97 | assert!(result.is_err()); 98 | let result = Opt::clap().get_matches_from_safe(&["test", "--badopt", "add"]); 99 | assert!(result.is_err()); 100 | let result = Opt::clap().get_matches_from_safe(&["test", "add", "--badopt"]); 101 | assert!(result.is_err()); 102 | } 103 | 104 | #[derive(StructOpt, PartialEq, Debug)] 105 | struct Opt3 { 106 | #[structopt(short, long)] 107 | all: bool, 108 | #[structopt(subcommand)] 109 | cmd: Sub2, 110 | } 111 | 112 | #[derive(StructOpt, PartialEq, Debug)] 113 | enum Sub2 { 114 | Foo { 115 | file: String, 116 | #[structopt(subcommand)] 117 | cmd: Sub3, 118 | }, 119 | Bar {}, 120 | } 121 | 122 | #[derive(StructOpt, PartialEq, Debug)] 123 | enum Sub3 { 124 | Baz {}, 125 | Quux {}, 126 | } 127 | 128 | #[test] 129 | fn test_subsubcommand() { 130 | assert_eq!( 131 | Opt3 { 132 | all: true, 133 | cmd: Sub2::Foo { 134 | file: "lib.rs".to_string(), 135 | cmd: Sub3::Quux {} 136 | } 137 | }, 138 | Opt3::from_clap( 139 | &Opt3::clap().get_matches_from(&["test", "--all", "foo", "lib.rs", "quux"]) 140 | ) 141 | ); 142 | } 143 | 144 | #[derive(StructOpt, PartialEq, Debug)] 145 | enum SubSubCmdWithOption { 146 | Remote { 147 | #[structopt(subcommand)] 148 | cmd: Option, 149 | }, 150 | Stash { 151 | #[structopt(subcommand)] 152 | cmd: Stash, 153 | }, 154 | } 155 | #[derive(StructOpt, PartialEq, Debug)] 156 | enum Remote { 157 | Add { name: String, url: String }, 158 | Remove { name: String }, 159 | } 160 | 161 | #[derive(StructOpt, PartialEq, Debug)] 162 | enum Stash { 163 | Save, 164 | Pop, 165 | } 166 | 167 | #[test] 168 | fn sub_sub_cmd_with_option() { 169 | fn make(args: &[&str]) -> Option { 170 | SubSubCmdWithOption::clap() 171 | .get_matches_from_safe(args) 172 | .ok() 173 | .map(|m| SubSubCmdWithOption::from_clap(&m)) 174 | } 175 | assert_eq!( 176 | Some(SubSubCmdWithOption::Remote { cmd: None }), 177 | make(&["", "remote"]) 178 | ); 179 | assert_eq!( 180 | Some(SubSubCmdWithOption::Remote { 181 | cmd: Some(Remote::Add { 182 | name: "origin".into(), 183 | url: "http".into() 184 | }) 185 | }), 186 | make(&["", "remote", "add", "origin", "http"]) 187 | ); 188 | assert_eq!( 189 | Some(SubSubCmdWithOption::Stash { cmd: Stash::Save }), 190 | make(&["", "stash", "save"]) 191 | ); 192 | assert_eq!(None, make(&["", "stash"])); 193 | } 194 | -------------------------------------------------------------------------------- /tests/non_literal_attributes.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::clap::AppSettings; 10 | use structopt::StructOpt; 11 | 12 | pub const DISPLAY_ORDER: usize = 2; 13 | 14 | // Check if the global settings compile 15 | #[derive(StructOpt, Debug, PartialEq, Eq)] 16 | #[structopt(global_settings = &[AppSettings::ColoredHelp])] 17 | struct Opt { 18 | #[structopt( 19 | long = "x", 20 | display_order = DISPLAY_ORDER, 21 | next_line_help = true, 22 | default_value = "0", 23 | require_equals = true 24 | )] 25 | x: i32, 26 | 27 | #[structopt(short = "l", long = "level", aliases = &["set-level", "lvl"])] 28 | level: String, 29 | 30 | #[structopt(long("values"))] 31 | values: Vec, 32 | 33 | #[structopt(name = "FILE", requires_if("FILE", "values"))] 34 | files: Vec, 35 | } 36 | 37 | #[test] 38 | fn test_slice() { 39 | assert_eq!( 40 | Opt { 41 | x: 0, 42 | level: "1".to_string(), 43 | files: Vec::new(), 44 | values: vec![], 45 | }, 46 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-l", "1"])) 47 | ); 48 | assert_eq!( 49 | Opt { 50 | x: 0, 51 | level: "1".to_string(), 52 | files: Vec::new(), 53 | values: vec![], 54 | }, 55 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "--level", "1"])) 56 | ); 57 | assert_eq!( 58 | Opt { 59 | x: 0, 60 | level: "1".to_string(), 61 | files: Vec::new(), 62 | values: vec![], 63 | }, 64 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "--set-level", "1"])) 65 | ); 66 | assert_eq!( 67 | Opt { 68 | x: 0, 69 | level: "1".to_string(), 70 | files: Vec::new(), 71 | values: vec![], 72 | }, 73 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "--lvl", "1"])) 74 | ); 75 | } 76 | 77 | #[test] 78 | fn test_multi_args() { 79 | assert_eq!( 80 | Opt { 81 | x: 0, 82 | level: "1".to_string(), 83 | files: vec!["file".to_string()], 84 | values: vec![], 85 | }, 86 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-l", "1", "file"])) 87 | ); 88 | assert_eq!( 89 | Opt { 90 | x: 0, 91 | level: "1".to_string(), 92 | files: vec!["FILE".to_string()], 93 | values: vec![1], 94 | }, 95 | Opt::from_clap( 96 | &Opt::clap().get_matches_from(&["test", "-l", "1", "--values", "1", "--", "FILE"]), 97 | ) 98 | ); 99 | } 100 | 101 | #[test] 102 | fn test_multi_args_fail() { 103 | let result = Opt::clap().get_matches_from_safe(&["test", "-l", "1", "--", "FILE"]); 104 | assert!(result.is_err()); 105 | } 106 | 107 | #[test] 108 | fn test_bool() { 109 | assert_eq!( 110 | Opt { 111 | x: 1, 112 | level: "1".to_string(), 113 | files: vec![], 114 | values: vec![], 115 | }, 116 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-l", "1", "--x=1"])) 117 | ); 118 | let result = Opt::clap().get_matches_from_safe(&["test", "-l", "1", "--x", "1"]); 119 | assert!(result.is_err()); 120 | } 121 | 122 | fn parse_hex(input: &str) -> Result { 123 | u64::from_str_radix(input, 16) 124 | } 125 | 126 | #[derive(StructOpt, PartialEq, Debug)] 127 | struct HexOpt { 128 | #[structopt(short = "n", parse(try_from_str = parse_hex))] 129 | number: u64, 130 | } 131 | 132 | #[test] 133 | fn test_parse_hex_function_path() { 134 | assert_eq!( 135 | HexOpt { number: 5 }, 136 | HexOpt::from_clap(&HexOpt::clap().get_matches_from(&["test", "-n", "5"])) 137 | ); 138 | assert_eq!( 139 | HexOpt { number: 0xabcdef }, 140 | HexOpt::from_clap(&HexOpt::clap().get_matches_from(&["test", "-n", "abcdef"])) 141 | ); 142 | 143 | let err = HexOpt::clap() 144 | .get_matches_from_safe(&["test", "-n", "gg"]) 145 | .unwrap_err(); 146 | assert!( 147 | err.message.contains("invalid digit found in string"), 148 | "{}", 149 | err 150 | ); 151 | } 152 | -------------------------------------------------------------------------------- /tests/options.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[test] 12 | fn required_option() { 13 | #[derive(StructOpt, PartialEq, Debug)] 14 | struct Opt { 15 | #[structopt(short, long)] 16 | arg: i32, 17 | } 18 | assert_eq!( 19 | Opt { arg: 42 }, 20 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a42"])) 21 | ); 22 | assert_eq!( 23 | Opt { arg: 42 }, 24 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a", "42"])) 25 | ); 26 | assert_eq!( 27 | Opt { arg: 42 }, 28 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "--arg", "42"])) 29 | ); 30 | assert!(Opt::clap().get_matches_from_safe(&["test"]).is_err()); 31 | assert!(Opt::clap() 32 | .get_matches_from_safe(&["test", "-a42", "-a24"]) 33 | .is_err()); 34 | } 35 | 36 | #[test] 37 | fn optional_option() { 38 | #[derive(StructOpt, PartialEq, Debug)] 39 | struct Opt { 40 | #[structopt(short)] 41 | arg: Option, 42 | } 43 | assert_eq!( 44 | Opt { arg: Some(42) }, 45 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a42"])) 46 | ); 47 | assert_eq!( 48 | Opt { arg: None }, 49 | Opt::from_clap(&Opt::clap().get_matches_from(&["test"])) 50 | ); 51 | assert!(Opt::clap() 52 | .get_matches_from_safe(&["test", "-a42", "-a24"]) 53 | .is_err()); 54 | } 55 | 56 | #[test] 57 | fn option_with_default() { 58 | #[derive(StructOpt, PartialEq, Debug)] 59 | struct Opt { 60 | #[structopt(short, default_value = "42")] 61 | arg: i32, 62 | } 63 | assert_eq!( 64 | Opt { arg: 24 }, 65 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a24"])) 66 | ); 67 | assert_eq!( 68 | Opt { arg: 42 }, 69 | Opt::from_clap(&Opt::clap().get_matches_from(&["test"])) 70 | ); 71 | assert!(Opt::clap() 72 | .get_matches_from_safe(&["test", "-a42", "-a24"]) 73 | .is_err()); 74 | } 75 | 76 | #[test] 77 | fn option_with_raw_default() { 78 | #[derive(StructOpt, PartialEq, Debug)] 79 | struct Opt { 80 | #[structopt(short, default_value = "42")] 81 | arg: i32, 82 | } 83 | assert_eq!( 84 | Opt { arg: 24 }, 85 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a24"])) 86 | ); 87 | assert_eq!( 88 | Opt { arg: 42 }, 89 | Opt::from_clap(&Opt::clap().get_matches_from(&["test"])) 90 | ); 91 | assert!(Opt::clap() 92 | .get_matches_from_safe(&["test", "-a42", "-a24"]) 93 | .is_err()); 94 | } 95 | 96 | #[test] 97 | fn options() { 98 | #[derive(StructOpt, PartialEq, Debug)] 99 | struct Opt { 100 | #[structopt(short, long)] 101 | arg: Vec, 102 | } 103 | assert_eq!( 104 | Opt { arg: vec![24] }, 105 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a24"])) 106 | ); 107 | assert_eq!( 108 | Opt { arg: vec![] }, 109 | Opt::from_clap(&Opt::clap().get_matches_from(&["test"])) 110 | ); 111 | assert_eq!( 112 | Opt { arg: vec![24, 42] }, 113 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a24", "--arg", "42"])) 114 | ); 115 | } 116 | 117 | #[test] 118 | fn empty_default_value() { 119 | #[derive(StructOpt, PartialEq, Debug)] 120 | struct Opt { 121 | #[structopt(short, default_value = "")] 122 | arg: String, 123 | } 124 | assert_eq!(Opt { arg: "".into() }, Opt::from_iter(&["test"])); 125 | assert_eq!( 126 | Opt { arg: "foo".into() }, 127 | Opt::from_iter(&["test", "-afoo"]) 128 | ); 129 | } 130 | 131 | #[test] 132 | fn option_from_str() { 133 | #[derive(Debug, PartialEq)] 134 | struct A; 135 | 136 | impl<'a> From<&'a str> for A { 137 | fn from(_: &str) -> A { 138 | A 139 | } 140 | } 141 | 142 | #[derive(Debug, StructOpt, PartialEq)] 143 | struct Opt { 144 | #[structopt(parse(from_str))] 145 | a: Option, 146 | } 147 | 148 | assert_eq!(Opt { a: None }, Opt::from_iter(&["test"])); 149 | assert_eq!(Opt { a: Some(A) }, Opt::from_iter(&["test", "foo"])); 150 | } 151 | 152 | #[test] 153 | fn optional_argument_for_optional_option() { 154 | #[derive(StructOpt, PartialEq, Debug)] 155 | struct Opt { 156 | #[structopt(short)] 157 | #[allow(clippy::option_option)] 158 | arg: Option>, 159 | } 160 | assert_eq!( 161 | Opt { 162 | arg: Some(Some(42)) 163 | }, 164 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a42"])) 165 | ); 166 | assert_eq!( 167 | Opt { arg: Some(None) }, 168 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a"])) 169 | ); 170 | assert_eq!( 171 | Opt { arg: None }, 172 | Opt::from_clap(&Opt::clap().get_matches_from(&["test"])) 173 | ); 174 | assert!(Opt::clap() 175 | .get_matches_from_safe(&["test", "-a42", "-a24"]) 176 | .is_err()); 177 | } 178 | 179 | #[test] 180 | fn two_option_options() { 181 | #[derive(StructOpt, PartialEq, Debug)] 182 | #[allow(clippy::option_option)] 183 | struct Opt { 184 | #[structopt(short)] 185 | arg: Option>, 186 | 187 | #[structopt(long)] 188 | field: Option>, 189 | } 190 | assert_eq!( 191 | Opt { 192 | arg: Some(Some(42)), 193 | field: Some(Some("f".into())) 194 | }, 195 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a42", "--field", "f"])) 196 | ); 197 | assert_eq!( 198 | Opt { 199 | arg: Some(Some(42)), 200 | field: Some(None) 201 | }, 202 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a42", "--field"])) 203 | ); 204 | assert_eq!( 205 | Opt { 206 | arg: Some(None), 207 | field: Some(None) 208 | }, 209 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a", "--field"])) 210 | ); 211 | assert_eq!( 212 | Opt { 213 | arg: Some(None), 214 | field: Some(Some("f".into())) 215 | }, 216 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a", "--field", "f"])) 217 | ); 218 | assert_eq!( 219 | Opt { 220 | arg: None, 221 | field: Some(None) 222 | }, 223 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "--field"])) 224 | ); 225 | assert_eq!( 226 | Opt { 227 | arg: None, 228 | field: None 229 | }, 230 | Opt::from_clap(&Opt::clap().get_matches_from(&["test"])) 231 | ); 232 | } 233 | 234 | #[test] 235 | fn optional_vec() { 236 | #[derive(StructOpt, PartialEq, Debug)] 237 | struct Opt { 238 | #[structopt(short)] 239 | arg: Option>, 240 | } 241 | assert_eq!( 242 | Opt { arg: Some(vec![1]) }, 243 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a", "1"])) 244 | ); 245 | 246 | assert_eq!( 247 | Opt { 248 | arg: Some(vec![1, 2]) 249 | }, 250 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a1", "-a2"])) 251 | ); 252 | 253 | assert_eq!( 254 | Opt { 255 | arg: Some(vec![1, 2]) 256 | }, 257 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a1", "-a2", "-a"])) 258 | ); 259 | 260 | assert_eq!( 261 | Opt { 262 | arg: Some(vec![1, 2]) 263 | }, 264 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a1", "-a", "-a2"])) 265 | ); 266 | 267 | assert_eq!( 268 | Opt { 269 | arg: Some(vec![1, 2]) 270 | }, 271 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a", "1", "2"])) 272 | ); 273 | 274 | assert_eq!( 275 | Opt { 276 | arg: Some(vec![1, 2, 3]) 277 | }, 278 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a", "1", "2", "-a", "3"])) 279 | ); 280 | 281 | assert_eq!( 282 | Opt { arg: Some(vec![]) }, 283 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a"])) 284 | ); 285 | 286 | assert_eq!( 287 | Opt { arg: Some(vec![]) }, 288 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a", "-a"])) 289 | ); 290 | 291 | assert_eq!( 292 | Opt { arg: None }, 293 | Opt::from_clap(&Opt::clap().get_matches_from(&["test"])) 294 | ); 295 | } 296 | 297 | #[test] 298 | fn two_optional_vecs() { 299 | #[derive(StructOpt, PartialEq, Debug)] 300 | struct Opt { 301 | #[structopt(short)] 302 | arg: Option>, 303 | 304 | #[structopt(short)] 305 | b: Option>, 306 | } 307 | 308 | assert_eq!( 309 | Opt { 310 | arg: Some(vec![1]), 311 | b: Some(vec![]) 312 | }, 313 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a", "1", "-b"])) 314 | ); 315 | 316 | assert_eq!( 317 | Opt { 318 | arg: Some(vec![1]), 319 | b: Some(vec![]) 320 | }, 321 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a", "-b", "-a1"])) 322 | ); 323 | 324 | assert_eq!( 325 | Opt { 326 | arg: Some(vec![1, 2]), 327 | b: Some(vec![1, 2]) 328 | }, 329 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a1", "-a2", "-b1", "-b2"])) 330 | ); 331 | 332 | assert_eq!( 333 | Opt { arg: None, b: None }, 334 | Opt::from_clap(&Opt::clap().get_matches_from(&["test"])) 335 | ); 336 | } 337 | -------------------------------------------------------------------------------- /tests/privacy.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | mod options { 12 | use super::StructOpt; 13 | 14 | #[derive(Debug, StructOpt)] 15 | pub struct Options { 16 | #[structopt(subcommand)] 17 | pub subcommand: super::subcommands::SubCommand, 18 | } 19 | } 20 | 21 | mod subcommands { 22 | use super::StructOpt; 23 | 24 | #[derive(Debug, StructOpt)] 25 | pub enum SubCommand { 26 | /// foo 27 | Foo { 28 | /// foo 29 | bars: Vec, 30 | }, 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /tests/raw_bool_literal.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[test] 12 | fn raw_bool_literal() { 13 | #[derive(StructOpt, Debug, PartialEq)] 14 | #[structopt(no_version, name = "raw_bool")] 15 | struct Opt { 16 | #[structopt(raw(false))] 17 | a: String, 18 | #[structopt(raw(true))] 19 | b: String, 20 | } 21 | 22 | assert_eq!( 23 | Opt { 24 | a: "one".into(), 25 | b: "--help".into() 26 | }, 27 | Opt::from_iter(&["test", "one", "--", "--help"]) 28 | ); 29 | } 30 | -------------------------------------------------------------------------------- /tests/raw_idents.rs: -------------------------------------------------------------------------------- 1 | use structopt::StructOpt; 2 | 3 | #[test] 4 | fn raw_idents() { 5 | #[derive(StructOpt, Debug, PartialEq)] 6 | struct Opt { 7 | #[structopt(short, long)] 8 | r#type: Vec, 9 | } 10 | 11 | assert_eq!( 12 | Opt { 13 | r#type: vec!["long".into(), "short".into()] 14 | }, 15 | Opt::from_iter(&["test", "--type", "long", "-t", "short"]) 16 | ); 17 | } 18 | -------------------------------------------------------------------------------- /tests/regressions.rs: -------------------------------------------------------------------------------- 1 | use structopt::StructOpt; 2 | 3 | mod utils; 4 | use utils::*; 5 | 6 | #[test] 7 | fn invisible_group_issue_439() { 8 | macro_rules! m { 9 | ($bool:ty) => { 10 | #[derive(Debug, StructOpt)] 11 | struct Opts { 12 | #[structopt(long = "x")] 13 | x: $bool, 14 | } 15 | }; 16 | } 17 | 18 | m!(bool); 19 | 20 | let help = get_long_help::(); 21 | 22 | assert!(help.contains("--x")); 23 | assert!(!help.contains("--x ")); 24 | Opts::from_iter_safe(&["test", "--x"]).unwrap(); 25 | } 26 | 27 | #[test] 28 | fn issue_447() { 29 | macro_rules! Command { 30 | ( $name:ident, [ 31 | #[$meta:meta] $var:ident($inner:ty) 32 | ] ) => { 33 | #[derive(Debug, PartialEq, structopt::StructOpt)] 34 | enum $name { 35 | #[$meta] 36 | $var($inner), 37 | } 38 | }; 39 | } 40 | 41 | Command! {GitCmd, [ 42 | #[structopt(external_subcommand)] 43 | Ext(Vec) 44 | ]} 45 | } 46 | -------------------------------------------------------------------------------- /tests/rename_all_env.rs: -------------------------------------------------------------------------------- 1 | mod utils; 2 | 3 | use structopt::StructOpt; 4 | use utils::*; 5 | 6 | #[test] 7 | fn it_works() { 8 | #[derive(Debug, PartialEq, StructOpt)] 9 | #[structopt(rename_all_env = "kebab")] 10 | struct BehaviorModel { 11 | #[structopt(env)] 12 | be_nice: String, 13 | } 14 | 15 | let help = get_help::(); 16 | assert!(help.contains("[env: be-nice=]")); 17 | } 18 | 19 | #[test] 20 | fn default_is_screaming() { 21 | #[derive(Debug, PartialEq, StructOpt)] 22 | struct BehaviorModel { 23 | #[structopt(env)] 24 | be_nice: String, 25 | } 26 | 27 | let help = get_help::(); 28 | assert!(help.contains("[env: BE_NICE=]")); 29 | } 30 | 31 | #[test] 32 | fn overridable() { 33 | #[derive(Debug, PartialEq, StructOpt)] 34 | #[structopt(rename_all_env = "kebab")] 35 | struct BehaviorModel { 36 | #[structopt(env)] 37 | be_nice: String, 38 | 39 | #[structopt(rename_all_env = "pascal", env)] 40 | be_aggressive: String, 41 | } 42 | 43 | let help = get_help::(); 44 | assert!(help.contains("[env: be-nice=]")); 45 | assert!(help.contains("[env: BeAggressive=]")); 46 | } 47 | -------------------------------------------------------------------------------- /tests/skip.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[test] 12 | fn skip_1() { 13 | #[derive(StructOpt, Debug, PartialEq)] 14 | struct Opt { 15 | #[structopt(short)] 16 | x: u32, 17 | #[structopt(skip)] 18 | s: u32, 19 | } 20 | 21 | assert!(Opt::from_iter_safe(&["test", "-x", "10", "20"]).is_err()); 22 | assert_eq!( 23 | Opt::from_iter(&["test", "-x", "10"]), 24 | Opt { 25 | x: 10, 26 | s: 0, // default 27 | } 28 | ); 29 | } 30 | 31 | #[test] 32 | fn skip_2() { 33 | #[derive(StructOpt, Debug, PartialEq)] 34 | struct Opt { 35 | #[structopt(short)] 36 | x: u32, 37 | #[structopt(skip)] 38 | ss: String, 39 | #[structopt(skip)] 40 | sn: u8, 41 | y: u32, 42 | #[structopt(skip)] 43 | sz: u16, 44 | t: u32, 45 | } 46 | 47 | assert_eq!( 48 | Opt::from_iter(&["test", "-x", "10", "20", "30"]), 49 | Opt { 50 | x: 10, 51 | ss: String::from(""), 52 | sn: 0, 53 | y: 20, 54 | sz: 0, 55 | t: 30, 56 | } 57 | ); 58 | } 59 | 60 | #[test] 61 | fn skip_enum() { 62 | #[derive(Debug, PartialEq)] 63 | #[allow(unused)] 64 | enum Kind { 65 | A, 66 | B, 67 | } 68 | 69 | impl Default for Kind { 70 | fn default() -> Self { 71 | return Kind::B; 72 | } 73 | } 74 | 75 | #[derive(StructOpt, Debug, PartialEq)] 76 | pub struct Opt { 77 | #[structopt(long, short)] 78 | number: u32, 79 | #[structopt(skip)] 80 | k: Kind, 81 | #[structopt(skip)] 82 | v: Vec, 83 | } 84 | 85 | assert_eq!( 86 | Opt::from_iter(&["test", "-n", "10"]), 87 | Opt { 88 | number: 10, 89 | k: Kind::B, 90 | v: vec![], 91 | } 92 | ); 93 | } 94 | 95 | #[test] 96 | fn skip_help_doc_comments() { 97 | #[derive(StructOpt, Debug, PartialEq)] 98 | pub struct Opt { 99 | #[structopt(skip, help = "internal_stuff")] 100 | a: u32, 101 | 102 | #[structopt(skip, long_help = "internal_stuff\ndo not touch")] 103 | b: u32, 104 | 105 | /// Not meant to be used by clap. 106 | /// 107 | /// I want a default here. 108 | #[structopt(skip)] 109 | c: u32, 110 | 111 | #[structopt(short, parse(try_from_str))] 112 | n: u32, 113 | } 114 | 115 | assert_eq!( 116 | Opt::from_iter(&["test", "-n", "10"]), 117 | Opt { 118 | n: 10, 119 | a: 0, 120 | b: 0, 121 | c: 0, 122 | } 123 | ); 124 | } 125 | 126 | #[test] 127 | fn skip_val() { 128 | #[derive(StructOpt, Debug, PartialEq)] 129 | pub struct Opt { 130 | #[structopt(long, short)] 131 | number: u32, 132 | 133 | #[structopt(skip = "key")] 134 | k: String, 135 | 136 | #[structopt(skip = vec![1, 2, 3])] 137 | v: Vec, 138 | } 139 | 140 | assert_eq!( 141 | Opt::from_iter(&["test", "-n", "10"]), 142 | Opt { 143 | number: 10, 144 | k: "key".into(), 145 | v: vec![1, 2, 3] 146 | } 147 | ); 148 | } 149 | -------------------------------------------------------------------------------- /tests/special_types.rs: -------------------------------------------------------------------------------- 1 | //! Checks that types like `::std::option::Option` are not special 2 | 3 | use structopt::StructOpt; 4 | 5 | #[rustversion::since(1.37)] 6 | #[test] 7 | fn special_types_bool() { 8 | mod inner { 9 | #[allow(non_camel_case_types)] 10 | #[derive(PartialEq, Debug)] 11 | pub struct bool(pub String); 12 | 13 | impl std::str::FromStr for self::bool { 14 | type Err = String; 15 | 16 | fn from_str(s: &str) -> Result { 17 | Ok(self::bool(s.into())) 18 | } 19 | } 20 | } 21 | 22 | #[derive(StructOpt, PartialEq, Debug)] 23 | struct Opt { 24 | arg: inner::bool, 25 | } 26 | 27 | assert_eq!( 28 | Opt { 29 | arg: inner::bool("success".into()) 30 | }, 31 | Opt::from_iter(&["test", "success"]) 32 | ); 33 | } 34 | 35 | #[test] 36 | fn special_types_option() { 37 | fn parser(s: &str) -> Option { 38 | Some(s.to_string()) 39 | } 40 | 41 | #[derive(StructOpt, PartialEq, Debug)] 42 | struct Opt { 43 | #[structopt(parse(from_str = parser))] 44 | arg: ::std::option::Option, 45 | } 46 | 47 | assert_eq!( 48 | Opt { 49 | arg: Some("success".into()) 50 | }, 51 | Opt::from_iter(&["test", "success"]) 52 | ); 53 | } 54 | 55 | #[test] 56 | fn special_types_vec() { 57 | fn parser(s: &str) -> Vec { 58 | vec![s.to_string()] 59 | } 60 | 61 | #[derive(StructOpt, PartialEq, Debug)] 62 | struct Opt { 63 | #[structopt(parse(from_str = parser))] 64 | arg: ::std::vec::Vec, 65 | } 66 | 67 | assert_eq!( 68 | Opt { 69 | arg: vec!["success".into()] 70 | }, 71 | Opt::from_iter(&["test", "success"]) 72 | ); 73 | } 74 | -------------------------------------------------------------------------------- /tests/subcommands.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | mod utils; 10 | 11 | use structopt::StructOpt; 12 | use utils::*; 13 | 14 | #[derive(StructOpt, PartialEq, Debug)] 15 | enum Opt { 16 | /// Fetch stuff from GitHub 17 | Fetch { 18 | #[structopt(long)] 19 | all: bool, 20 | #[structopt(short, long)] 21 | /// Overwrite local branches. 22 | force: bool, 23 | repo: String, 24 | }, 25 | 26 | Add { 27 | #[structopt(short, long)] 28 | interactive: bool, 29 | #[structopt(short, long)] 30 | verbose: bool, 31 | }, 32 | } 33 | 34 | #[test] 35 | fn test_fetch() { 36 | assert_eq!( 37 | Opt::Fetch { 38 | all: true, 39 | force: false, 40 | repo: "origin".to_string() 41 | }, 42 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "fetch", "--all", "origin"])) 43 | ); 44 | assert_eq!( 45 | Opt::Fetch { 46 | all: false, 47 | force: true, 48 | repo: "origin".to_string() 49 | }, 50 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "fetch", "-f", "origin"])) 51 | ); 52 | } 53 | 54 | #[test] 55 | fn test_add() { 56 | assert_eq!( 57 | Opt::Add { 58 | interactive: false, 59 | verbose: false 60 | }, 61 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "add"])) 62 | ); 63 | assert_eq!( 64 | Opt::Add { 65 | interactive: true, 66 | verbose: true 67 | }, 68 | Opt::from_clap(&Opt::clap().get_matches_from(&["test", "add", "-i", "-v"])) 69 | ); 70 | } 71 | 72 | #[test] 73 | fn test_no_parse() { 74 | let result = Opt::clap().get_matches_from_safe(&["test", "badcmd", "-i", "-v"]); 75 | assert!(result.is_err()); 76 | 77 | let result = Opt::clap().get_matches_from_safe(&["test", "add", "--badoption"]); 78 | assert!(result.is_err()); 79 | 80 | let result = Opt::clap().get_matches_from_safe(&["test"]); 81 | assert!(result.is_err()); 82 | } 83 | 84 | #[derive(StructOpt, PartialEq, Debug)] 85 | enum Opt2 { 86 | DoSomething { arg: String }, 87 | } 88 | 89 | #[test] 90 | /// This test is specifically to make sure that hyphenated subcommands get 91 | /// processed correctly. 92 | fn test_hyphenated_subcommands() { 93 | assert_eq!( 94 | Opt2::DoSomething { 95 | arg: "blah".to_string() 96 | }, 97 | Opt2::from_clap(&Opt2::clap().get_matches_from(&["test", "do-something", "blah"])) 98 | ); 99 | } 100 | 101 | #[derive(StructOpt, PartialEq, Debug)] 102 | enum Opt3 { 103 | Add, 104 | Init, 105 | Fetch, 106 | } 107 | 108 | #[test] 109 | fn test_null_commands() { 110 | assert_eq!( 111 | Opt3::Add, 112 | Opt3::from_clap(&Opt3::clap().get_matches_from(&["test", "add"])) 113 | ); 114 | assert_eq!( 115 | Opt3::Init, 116 | Opt3::from_clap(&Opt3::clap().get_matches_from(&["test", "init"])) 117 | ); 118 | assert_eq!( 119 | Opt3::Fetch, 120 | Opt3::from_clap(&Opt3::clap().get_matches_from(&["test", "fetch"])) 121 | ); 122 | } 123 | 124 | #[derive(StructOpt, PartialEq, Debug)] 125 | #[structopt(about = "Not shown")] 126 | struct Add { 127 | file: String, 128 | } 129 | /// Not shown 130 | #[derive(StructOpt, PartialEq, Debug)] 131 | struct Fetch { 132 | remote: String, 133 | } 134 | #[derive(StructOpt, PartialEq, Debug)] 135 | enum Opt4 { 136 | // Not shown 137 | /// Add a file 138 | Add(Add), 139 | Init, 140 | /// download history from remote 141 | Fetch(Fetch), 142 | } 143 | 144 | #[test] 145 | fn test_tuple_commands() { 146 | assert_eq!( 147 | Opt4::Add(Add { 148 | file: "f".to_string() 149 | }), 150 | Opt4::from_clap(&Opt4::clap().get_matches_from(&["test", "add", "f"])) 151 | ); 152 | assert_eq!( 153 | Opt4::Init, 154 | Opt4::from_clap(&Opt4::clap().get_matches_from(&["test", "init"])) 155 | ); 156 | assert_eq!( 157 | Opt4::Fetch(Fetch { 158 | remote: "origin".to_string() 159 | }), 160 | Opt4::from_clap(&Opt4::clap().get_matches_from(&["test", "fetch", "origin"])) 161 | ); 162 | 163 | let output = get_long_help::(); 164 | 165 | assert!(output.contains("download history from remote")); 166 | assert!(output.contains("Add a file")); 167 | assert!(!output.contains("Not shown")); 168 | } 169 | 170 | #[test] 171 | fn enum_in_enum_subsubcommand() { 172 | #[derive(StructOpt, Debug, PartialEq)] 173 | pub enum Opt { 174 | Daemon(DaemonCommand), 175 | } 176 | 177 | #[derive(StructOpt, Debug, PartialEq)] 178 | pub enum DaemonCommand { 179 | Start, 180 | Stop, 181 | } 182 | 183 | let result = Opt::clap().get_matches_from_safe(&["test"]); 184 | assert!(result.is_err()); 185 | 186 | let result = Opt::clap().get_matches_from_safe(&["test", "daemon"]); 187 | assert!(result.is_err()); 188 | 189 | let result = Opt::from_iter(&["test", "daemon", "start"]); 190 | assert_eq!(Opt::Daemon(DaemonCommand::Start), result); 191 | } 192 | 193 | #[test] 194 | fn flatten_enum() { 195 | #[derive(StructOpt, Debug, PartialEq)] 196 | struct Opt { 197 | #[structopt(flatten)] 198 | sub_cmd: SubCmd, 199 | } 200 | #[derive(StructOpt, Debug, PartialEq)] 201 | enum SubCmd { 202 | Foo, 203 | Bar, 204 | } 205 | 206 | assert!(Opt::from_iter_safe(&["test"]).is_err()); 207 | assert_eq!( 208 | Opt::from_iter(&["test", "foo"]), 209 | Opt { 210 | sub_cmd: SubCmd::Foo 211 | } 212 | ); 213 | } 214 | 215 | #[test] 216 | fn external_subcommand() { 217 | #[derive(Debug, PartialEq, StructOpt)] 218 | struct Opt { 219 | #[structopt(subcommand)] 220 | sub: Subcommands, 221 | } 222 | 223 | #[derive(Debug, PartialEq, StructOpt)] 224 | enum Subcommands { 225 | Add, 226 | Remove, 227 | #[structopt(external_subcommand)] 228 | Other(Vec), 229 | } 230 | 231 | assert_eq!( 232 | Opt::from_iter(&["test", "add"]), 233 | Opt { 234 | sub: Subcommands::Add 235 | } 236 | ); 237 | 238 | assert_eq!( 239 | Opt::from_iter(&["test", "remove"]), 240 | Opt { 241 | sub: Subcommands::Remove 242 | } 243 | ); 244 | 245 | assert_eq!( 246 | Opt::from_iter(&["test", "git", "status"]), 247 | Opt { 248 | sub: Subcommands::Other(vec!["git".into(), "status".into()]) 249 | } 250 | ); 251 | 252 | assert!(Opt::from_iter_safe(&["test"]).is_err()); 253 | } 254 | 255 | #[test] 256 | fn external_subcommand_os_string() { 257 | use std::ffi::OsString; 258 | 259 | #[derive(Debug, PartialEq, StructOpt)] 260 | struct Opt { 261 | #[structopt(subcommand)] 262 | sub: Subcommands, 263 | } 264 | 265 | #[derive(Debug, PartialEq, StructOpt)] 266 | enum Subcommands { 267 | #[structopt(external_subcommand)] 268 | Other(Vec), 269 | } 270 | 271 | assert_eq!( 272 | Opt::from_iter(&["test", "git", "status"]), 273 | Opt { 274 | sub: Subcommands::Other(vec!["git".into(), "status".into()]) 275 | } 276 | ); 277 | 278 | assert!(Opt::from_iter_safe(&["test"]).is_err()); 279 | } 280 | 281 | #[test] 282 | fn external_subcommand_optional() { 283 | #[derive(Debug, PartialEq, StructOpt)] 284 | struct Opt { 285 | #[structopt(subcommand)] 286 | sub: Option, 287 | } 288 | 289 | #[derive(Debug, PartialEq, StructOpt)] 290 | enum Subcommands { 291 | #[structopt(external_subcommand)] 292 | Other(Vec), 293 | } 294 | 295 | assert_eq!( 296 | Opt::from_iter(&["test", "git", "status"]), 297 | Opt { 298 | sub: Some(Subcommands::Other(vec!["git".into(), "status".into()])) 299 | } 300 | ); 301 | 302 | assert_eq!(Opt::from_iter(&["test"]), Opt { sub: None }); 303 | } 304 | 305 | #[test] 306 | fn skip_subcommand() { 307 | #[derive(Debug, PartialEq, StructOpt)] 308 | struct Opt { 309 | #[structopt(subcommand)] 310 | sub: Subcommands, 311 | } 312 | 313 | #[derive(Debug, PartialEq, StructOpt)] 314 | enum Subcommands { 315 | Add, 316 | Remove, 317 | 318 | #[allow(dead_code)] 319 | #[structopt(skip)] 320 | Skip, 321 | } 322 | 323 | assert_eq!( 324 | Opt::from_iter(&["test", "add"]), 325 | Opt { 326 | sub: Subcommands::Add 327 | } 328 | ); 329 | 330 | assert_eq!( 331 | Opt::from_iter(&["test", "remove"]), 332 | Opt { 333 | sub: Subcommands::Remove 334 | } 335 | ); 336 | 337 | let res = Opt::from_iter_safe(&["test", "skip"]); 338 | assert!( 339 | matches!( 340 | res, 341 | Err(clap::Error { 342 | kind: clap::ErrorKind::UnknownArgument, 343 | .. 344 | }) 345 | ), 346 | "Unexpected result: {:?}", 347 | res 348 | ); 349 | } 350 | -------------------------------------------------------------------------------- /tests/ui/bool_default_value.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | #[structopt(name = "basic")] 13 | struct Opt { 14 | #[structopt(short, default_value = true)] 15 | b: bool, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::from_args(); 20 | println!("{:?}", opt); 21 | } 22 | -------------------------------------------------------------------------------- /tests/ui/bool_default_value.stderr: -------------------------------------------------------------------------------- 1 | error: default_value is meaningless for bool 2 | --> $DIR/bool_default_value.rs:14:24 3 | | 4 | 14 | #[structopt(short, default_value = true)] 5 | | ^^^^^^^^^^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/bool_required.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | #[structopt(name = "basic")] 13 | struct Opt { 14 | #[structopt(short, required = true)] 15 | b: bool, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::from_args(); 20 | println!("{:?}", opt); 21 | } 22 | -------------------------------------------------------------------------------- /tests/ui/bool_required.stderr: -------------------------------------------------------------------------------- 1 | error: required is meaningless for bool 2 | --> $DIR/bool_required.rs:14:24 3 | | 4 | 14 | #[structopt(short, required = true)] 5 | | ^^^^^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/enum_flatten.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | #[structopt(name = "basic")] 13 | enum Opt { 14 | #[structopt(flatten)] 15 | Variant1, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::from_args(); 20 | println!("{:?}", opt); 21 | } 22 | -------------------------------------------------------------------------------- /tests/ui/enum_flatten.stderr: -------------------------------------------------------------------------------- 1 | error: `flatten` is usable only with single-typed tuple variants 2 | --> $DIR/enum_flatten.rs:14:5 3 | | 4 | 14 | / #[structopt(flatten)] 5 | 15 | | Variant1, 6 | | |____________^ 7 | -------------------------------------------------------------------------------- /tests/ui/external_subcommand_wrong_type.rs: -------------------------------------------------------------------------------- 1 | use structopt::StructOpt; 2 | use std::ffi::CString; 3 | 4 | #[derive(StructOpt, Debug)] 5 | struct Opt { 6 | #[structopt(subcommand)] 7 | cmd: Command, 8 | } 9 | 10 | #[derive(StructOpt, Debug)] 11 | enum Command { 12 | #[structopt(external_subcommand)] 13 | Other(Vec) 14 | } 15 | 16 | fn main() { 17 | let opt = Opt::from_args(); 18 | println!("{:?}", opt); 19 | } -------------------------------------------------------------------------------- /tests/ui/external_subcommand_wrong_type.stderr: -------------------------------------------------------------------------------- 1 | error[E0308]: mismatched types 2 | --> $DIR/external_subcommand_wrong_type.rs:13:15 3 | | 4 | 13 | Other(Vec) 5 | | ^^^^^^^ expected struct `CString`, found struct `OsString` 6 | | 7 | = note: expected struct `Vec` 8 | found struct `Vec` 9 | -------------------------------------------------------------------------------- /tests/ui/flatten_and_methods.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | struct DaemonOpts { 13 | #[structopt(short)] 14 | user: String, 15 | #[structopt(short)] 16 | group: String, 17 | } 18 | 19 | #[derive(StructOpt, Debug)] 20 | #[structopt(name = "basic")] 21 | struct Opt { 22 | #[structopt(short, flatten)] 23 | opts: DaemonOpts, 24 | } 25 | 26 | fn main() { 27 | let opt = Opt::from_args(); 28 | println!("{:?}", opt); 29 | } 30 | -------------------------------------------------------------------------------- /tests/ui/flatten_and_methods.stderr: -------------------------------------------------------------------------------- 1 | error: methods are not allowed for flattened entry 2 | --> $DIR/flatten_and_methods.rs:22:24 3 | | 4 | 22 | #[structopt(short, flatten)] 5 | | ^^^^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/flatten_and_parse.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | struct DaemonOpts { 13 | #[structopt(short)] 14 | user: String, 15 | #[structopt(short)] 16 | group: String, 17 | } 18 | 19 | #[derive(StructOpt, Debug)] 20 | #[structopt(name = "basic")] 21 | struct Opt { 22 | #[structopt(flatten, parse(from_occurrences))] 23 | opts: DaemonOpts, 24 | } 25 | 26 | fn main() { 27 | let opt = Opt::from_args(); 28 | println!("{:?}", opt); 29 | } 30 | -------------------------------------------------------------------------------- /tests/ui/flatten_and_parse.stderr: -------------------------------------------------------------------------------- 1 | error: parse attribute is not allowed for flattened entry 2 | --> $DIR/flatten_and_parse.rs:22:26 3 | | 4 | 22 | #[structopt(flatten, parse(from_occurrences))] 5 | | ^^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/multiple_external_subcommand.rs: -------------------------------------------------------------------------------- 1 | use structopt::StructOpt; 2 | 3 | #[derive(StructOpt, Debug)] 4 | struct Opt { 5 | #[structopt(subcommand)] 6 | cmd: Command, 7 | } 8 | 9 | #[derive(StructOpt, Debug)] 10 | enum Command { 11 | #[structopt(external_subcommand)] 12 | Run(Vec), 13 | 14 | #[structopt(external_subcommand)] 15 | Other(Vec) 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::from_args(); 20 | println!("{:?}", opt); 21 | } 22 | -------------------------------------------------------------------------------- /tests/ui/multiple_external_subcommand.stderr: -------------------------------------------------------------------------------- 1 | error: Only one variant can be marked with `external_subcommand`, this is the second 2 | --> $DIR/multiple_external_subcommand.rs:14:17 3 | | 4 | 14 | #[structopt(external_subcommand)] 5 | | ^^^^^^^^^^^^^^^^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/non_existent_attr.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | #[structopt(name = "basic")] 13 | struct Opt { 14 | #[structopt(short, non_existing_attribute = 1)] 15 | debug: bool, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::from_args(); 20 | println!("{:?}", opt); 21 | } 22 | -------------------------------------------------------------------------------- /tests/ui/non_existent_attr.stderr: -------------------------------------------------------------------------------- 1 | error[E0599]: no method named `non_existing_attribute` found for struct `Arg` in the current scope 2 | --> $DIR/non_existent_attr.rs:14:24 3 | | 4 | 14 | #[structopt(short, non_existing_attribute = 1)] 5 | | ^^^^^^^^^^^^^^^^^^^^^^ method not found in `Arg<'_, '_>` 6 | -------------------------------------------------------------------------------- /tests/ui/opt_opt_nonpositional.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | #[structopt(name = "basic")] 13 | struct Opt { 14 | n: Option>, 15 | } 16 | 17 | fn main() { 18 | let opt = Opt::from_args(); 19 | println!("{:?}", opt); 20 | } 21 | -------------------------------------------------------------------------------- /tests/ui/opt_opt_nonpositional.stderr: -------------------------------------------------------------------------------- 1 | error: Option> type is meaningless for positional argument 2 | --> $DIR/opt_opt_nonpositional.rs:14:8 3 | | 4 | 14 | n: Option>, 5 | | ^^^^^^^^^^^^^^^^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/opt_vec_nonpositional.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | #[structopt(name = "basic")] 13 | struct Opt { 14 | n: Option>, 15 | } 16 | 17 | fn main() { 18 | let opt = Opt::from_args(); 19 | println!("{:?}", opt); 20 | } 21 | -------------------------------------------------------------------------------- /tests/ui/opt_vec_nonpositional.stderr: -------------------------------------------------------------------------------- 1 | error: Option> type is meaningless for positional argument 2 | --> $DIR/opt_vec_nonpositional.rs:14:8 3 | | 4 | 14 | n: Option>, 5 | | ^^^^^^^^^^^^^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/option_default_value.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | #[structopt(name = "basic")] 13 | struct Opt { 14 | #[structopt(short, default_value = 1)] 15 | n: Option, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::from_args(); 20 | println!("{:?}", opt); 21 | } 22 | -------------------------------------------------------------------------------- /tests/ui/option_default_value.stderr: -------------------------------------------------------------------------------- 1 | error: default_value is meaningless for Option 2 | --> $DIR/option_default_value.rs:14:24 3 | | 4 | 14 | #[structopt(short, default_value = 1)] 5 | | ^^^^^^^^^^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/option_required.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | #[structopt(name = "basic")] 13 | struct Opt { 14 | #[structopt(short, required = true)] 15 | n: Option, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::from_args(); 20 | println!("{:?}", opt); 21 | } 22 | -------------------------------------------------------------------------------- /tests/ui/option_required.stderr: -------------------------------------------------------------------------------- 1 | error: required is meaningless for Option 2 | --> $DIR/option_required.rs:14:24 3 | | 4 | 14 | #[structopt(short, required = true)] 5 | | ^^^^^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/parse_empty_try_from_os.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | #[structopt(name = "basic")] 13 | struct Opt { 14 | #[structopt(parse(try_from_os_str))] 15 | s: String, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::from_args(); 20 | println!("{:?}", opt); 21 | } 22 | -------------------------------------------------------------------------------- /tests/ui/parse_empty_try_from_os.stderr: -------------------------------------------------------------------------------- 1 | error: you must set parser for `try_from_os_str` explicitly 2 | --> $DIR/parse_empty_try_from_os.rs:14:23 3 | | 4 | 14 | #[structopt(parse(try_from_os_str))] 5 | | ^^^^^^^^^^^^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/parse_function_is_not_path.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | #[structopt(name = "basic")] 13 | struct Opt { 14 | #[structopt(parse(from_str = "2"))] 15 | s: String, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::from_args(); 20 | println!("{:?}", opt); 21 | } 22 | -------------------------------------------------------------------------------- /tests/ui/parse_function_is_not_path.stderr: -------------------------------------------------------------------------------- 1 | error: `parse` argument must be a function path 2 | --> $DIR/parse_function_is_not_path.rs:14:34 3 | | 4 | 14 | #[structopt(parse(from_str = "2"))] 5 | | ^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/parse_literal_spec.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | #[structopt(name = "basic")] 13 | struct Opt { 14 | #[structopt(parse("from_str"))] 15 | s: String, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::from_args(); 20 | println!("{:?}", opt); 21 | } 22 | -------------------------------------------------------------------------------- /tests/ui/parse_literal_spec.stderr: -------------------------------------------------------------------------------- 1 | error: parser specification must start with identifier 2 | --> $DIR/parse_literal_spec.rs:14:23 3 | | 4 | 14 | #[structopt(parse("from_str"))] 5 | | ^^^^^^^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/parse_not_zero_args.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | #[structopt(name = "basic")] 13 | struct Opt { 14 | #[structopt(parse(from_str, from_str))] 15 | s: String, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::from_args(); 20 | println!("{:?}", opt); 21 | } 22 | -------------------------------------------------------------------------------- /tests/ui/parse_not_zero_args.stderr: -------------------------------------------------------------------------------- 1 | error: `parse` must have exactly one argument 2 | --> $DIR/parse_not_zero_args.rs:14:17 3 | | 4 | 14 | #[structopt(parse(from_str, from_str))] 5 | | ^^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/positional_bool.rs: -------------------------------------------------------------------------------- 1 | use structopt::StructOpt; 2 | 3 | #[derive(StructOpt, Debug)] 4 | struct Opt { 5 | verbose: bool, 6 | } 7 | 8 | fn main() { 9 | Opt::from_args(); 10 | } -------------------------------------------------------------------------------- /tests/ui/positional_bool.stderr: -------------------------------------------------------------------------------- 1 | error: `bool` cannot be used as positional parameter with default parser 2 | 3 | = help: if you want to create a flag add `long` or `short` 4 | = help: If you really want a boolean parameter add an explicit parser, for example `parse(try_from_str)` 5 | = note: see also https://github.com/TeXitoi/structopt/tree/master/examples/true_or_false.rs 6 | 7 | --> $DIR/positional_bool.rs:5:14 8 | | 9 | 5 | verbose: bool, 10 | | ^^^^ 11 | -------------------------------------------------------------------------------- /tests/ui/raw.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | struct Opt { 13 | #[structopt(raw(case_insensitive = "true"))] 14 | s: String, 15 | } 16 | 17 | #[derive(StructOpt, Debug)] 18 | struct Opt2 { 19 | #[structopt(raw(requires_if = r#""one", "two""#))] 20 | s: String, 21 | } 22 | fn main() { 23 | let opt = Opt::from_args(); 24 | println!("{:?}", opt); 25 | } 26 | -------------------------------------------------------------------------------- /tests/ui/raw.stderr: -------------------------------------------------------------------------------- 1 | error: `#[structopt(raw(...))` attributes are removed in structopt 0.3, they are replaced with raw methods 2 | 3 | = help: if you meant to call `clap::Arg::raw()` method you should use bool literal, like `raw(true)` or `raw(false)` 4 | = note: if you need to call `clap::Arg/App::case_insensitive` method you can do it like this: #[structopt(case_insensitive = true)] 5 | 6 | --> $DIR/raw.rs:13:17 7 | | 8 | 13 | #[structopt(raw(case_insensitive = "true"))] 9 | | ^^^ 10 | 11 | error: `#[structopt(raw(...))` attributes are removed in structopt 0.3, they are replaced with raw methods 12 | 13 | = help: if you meant to call `clap::Arg::raw()` method you should use bool literal, like `raw(true)` or `raw(false)` 14 | = note: if you need to call `clap::Arg/App::requires_if` method you can do it like this: #[structopt(requires_if("one", "two"))] 15 | 16 | --> $DIR/raw.rs:19:17 17 | | 18 | 19 | #[structopt(raw(requires_if = r#""one", "two""#))] 19 | | ^^^ 20 | -------------------------------------------------------------------------------- /tests/ui/rename_all_wrong_casing.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | #[structopt(name = "basic", rename_all = "fail")] 13 | struct Opt { 14 | #[structopt(short)] 15 | s: String, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::from_args(); 20 | println!("{:?}", opt); 21 | } 22 | -------------------------------------------------------------------------------- /tests/ui/rename_all_wrong_casing.stderr: -------------------------------------------------------------------------------- 1 | error: unsupported casing: `fail` 2 | --> $DIR/rename_all_wrong_casing.rs:12:42 3 | | 4 | 12 | #[structopt(name = "basic", rename_all = "fail")] 5 | | ^^^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/skip_flatten.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | #[structopt(name = "make-cookie")] 13 | struct MakeCookie { 14 | #[structopt(short)] 15 | s: String, 16 | 17 | #[structopt(skip, flatten)] 18 | cmd: Command, 19 | } 20 | 21 | #[derive(StructOpt, Debug)] 22 | enum Command { 23 | #[structopt(name = "pound")] 24 | /// Pound acorns into flour for cookie dough. 25 | Pound { acorns: u32 }, 26 | 27 | Sparkle { 28 | #[structopt(short)] 29 | color: String, 30 | }, 31 | } 32 | 33 | impl Default for Command { 34 | fn default() -> Self { 35 | Command::Pound { acorns: 0 } 36 | } 37 | } 38 | 39 | fn main() { 40 | let opt = MakeCookie::from_args(); 41 | println!("{:?}", opt); 42 | } 43 | -------------------------------------------------------------------------------- /tests/ui/skip_flatten.stderr: -------------------------------------------------------------------------------- 1 | error: subcommand, flatten and skip cannot be used together 2 | --> $DIR/skip_flatten.rs:17:23 3 | | 4 | 17 | #[structopt(skip, flatten)] 5 | | ^^^^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/skip_subcommand.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | #[structopt(name = "make-cookie")] 13 | struct MakeCookie { 14 | #[structopt(short)] 15 | s: String, 16 | 17 | #[structopt(subcommand, skip)] 18 | cmd: Command, 19 | } 20 | 21 | #[derive(StructOpt, Debug)] 22 | enum Command { 23 | #[structopt(name = "pound")] 24 | /// Pound acorns into flour for cookie dough. 25 | Pound { acorns: u32 }, 26 | 27 | Sparkle { 28 | #[structopt(short)] 29 | color: String, 30 | }, 31 | } 32 | 33 | impl Default for Command { 34 | fn default() -> Self { 35 | Command::Pound { acorns: 0 } 36 | } 37 | } 38 | 39 | fn main() { 40 | let opt = MakeCookie::from_args(); 41 | println!("{:?}", opt); 42 | } 43 | -------------------------------------------------------------------------------- /tests/ui/skip_subcommand.stderr: -------------------------------------------------------------------------------- 1 | error: subcommand, flatten and skip cannot be used together 2 | --> $DIR/skip_subcommand.rs:17:29 3 | | 4 | 17 | #[structopt(subcommand, skip)] 5 | | ^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/skip_with_other_options.rs: -------------------------------------------------------------------------------- 1 | use structopt::StructOpt; 2 | 3 | #[derive(StructOpt, Debug)] 4 | #[structopt(name = "test")] 5 | pub struct Opt { 6 | #[structopt(long)] 7 | a: u32, 8 | #[structopt(skip, long)] 9 | b: u32, 10 | } 11 | 12 | fn main() { 13 | let opt = Opt::from_args(); 14 | println!("{:?}", opt); 15 | } 16 | -------------------------------------------------------------------------------- /tests/ui/skip_with_other_options.stderr: -------------------------------------------------------------------------------- 1 | error: methods are not allowed for skipped fields 2 | --> $DIR/skip_with_other_options.rs:8:17 3 | | 4 | 8 | #[structopt(skip, long)] 5 | | ^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/skip_without_default.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(Debug)] 12 | enum Kind { 13 | A, 14 | B, 15 | } 16 | 17 | #[derive(StructOpt, Debug)] 18 | #[structopt(name = "test")] 19 | pub struct Opt { 20 | #[structopt(short)] 21 | number: u32, 22 | #[structopt(skip)] 23 | k: Kind, 24 | } 25 | 26 | fn main() { 27 | let opt = Opt::from_args(); 28 | println!("{:?}", opt); 29 | } 30 | -------------------------------------------------------------------------------- /tests/ui/skip_without_default.stderr: -------------------------------------------------------------------------------- 1 | error[E0277]: the trait bound `Kind: Default` is not satisfied 2 | --> $DIR/skip_without_default.rs:22:17 3 | | 4 | 22 | #[structopt(skip)] 5 | | ^^^^ the trait `Default` is not implemented for `Kind` 6 | | 7 | note: required by `std::default::Default::default` 8 | -------------------------------------------------------------------------------- /tests/ui/struct_parse.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | #[structopt(name = "basic", parse(from_str))] 13 | struct Opt { 14 | #[structopt(short)] 15 | s: String, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::from_args(); 20 | println!("{:?}", opt); 21 | } 22 | -------------------------------------------------------------------------------- /tests/ui/struct_parse.stderr: -------------------------------------------------------------------------------- 1 | error: `parse` attribute is only allowed on fields 2 | --> $DIR/struct_parse.rs:12:29 3 | | 4 | 12 | #[structopt(name = "basic", parse(from_str))] 5 | | ^^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/struct_subcommand.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | #[structopt(name = "basic", subcommand)] 13 | struct Opt { 14 | #[structopt(short)] 15 | s: String, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::from_args(); 20 | println!("{:?}", opt); 21 | } 22 | -------------------------------------------------------------------------------- /tests/ui/struct_subcommand.stderr: -------------------------------------------------------------------------------- 1 | error: subcommand is only allowed on fields 2 | --> $DIR/struct_subcommand.rs:12:29 3 | | 4 | 12 | #[structopt(name = "basic", subcommand)] 5 | | ^^^^^^^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/structopt_empty_attr.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | #[structopt(name = "basic")] 13 | struct Opt { 14 | #[structopt] 15 | debug: bool, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::from_args(); 20 | println!("{:?}", opt); 21 | } 22 | 23 | -------------------------------------------------------------------------------- /tests/ui/structopt_empty_attr.stderr: -------------------------------------------------------------------------------- 1 | error: expected attribute arguments in parentheses: #[structopt(...)] 2 | --> $DIR/structopt_empty_attr.rs:14:5 3 | | 4 | 14 | #[structopt] 5 | | ^^^^^^^^^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/structopt_name_value_attr.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | #[structopt(name = "basic")] 13 | struct Opt { 14 | #[structopt = "short"] 15 | debug: bool, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::from_args(); 20 | println!("{:?}", opt); 21 | } 22 | 23 | -------------------------------------------------------------------------------- /tests/ui/structopt_name_value_attr.stderr: -------------------------------------------------------------------------------- 1 | error: expected parentheses: #[structopt(...)] 2 | --> $DIR/structopt_name_value_attr.rs:14:17 3 | | 4 | 14 | #[structopt = "short"] 5 | | ^ 6 | -------------------------------------------------------------------------------- /tests/ui/subcommand_and_flatten.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | #[structopt(name = "make-cookie")] 13 | struct MakeCookie { 14 | #[structopt(short)] 15 | s: String, 16 | 17 | #[structopt(subcommand, flatten)] 18 | cmd: Command, 19 | } 20 | 21 | #[derive(StructOpt, Debug)] 22 | enum Command { 23 | #[structopt(name = "pound")] 24 | /// Pound acorns into flour for cookie dough. 25 | Pound { acorns: u32 }, 26 | 27 | Sparkle { 28 | #[structopt(short)] 29 | color: String, 30 | }, 31 | } 32 | 33 | fn main() { 34 | let opt = MakeCookie::from_args(); 35 | println!("{:?}", opt); 36 | } 37 | -------------------------------------------------------------------------------- /tests/ui/subcommand_and_flatten.stderr: -------------------------------------------------------------------------------- 1 | error: subcommand, flatten and skip cannot be used together 2 | --> $DIR/subcommand_and_flatten.rs:17:29 3 | | 4 | 17 | #[structopt(subcommand, flatten)] 5 | | ^^^^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/subcommand_and_methods.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | #[structopt(name = "make-cookie")] 13 | struct MakeCookie { 14 | #[structopt(short)] 15 | s: String, 16 | 17 | #[structopt(subcommand, long)] 18 | cmd: Command, 19 | } 20 | 21 | #[derive(StructOpt, Debug)] 22 | enum Command { 23 | #[structopt(name = "pound")] 24 | /// Pound acorns into flour for cookie dough. 25 | Pound { acorns: u32 }, 26 | 27 | Sparkle { 28 | #[structopt(short)] 29 | color: String, 30 | }, 31 | } 32 | 33 | fn main() { 34 | let opt = MakeCookie::from_args(); 35 | println!("{:?}", opt); 36 | } 37 | -------------------------------------------------------------------------------- /tests/ui/subcommand_and_methods.stderr: -------------------------------------------------------------------------------- 1 | error: methods in attributes are not allowed for subcommand 2 | --> $DIR/subcommand_and_methods.rs:17:17 3 | | 4 | 17 | #[structopt(subcommand, long)] 5 | | ^^^^^^^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/subcommand_and_parse.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | #[structopt(name = "make-cookie")] 13 | struct MakeCookie { 14 | #[structopt(short)] 15 | s: String, 16 | 17 | #[structopt(subcommand, parse(from_occurrences))] 18 | cmd: Command, 19 | } 20 | 21 | #[derive(StructOpt, Debug)] 22 | enum Command { 23 | #[structopt(name = "pound")] 24 | /// Pound acorns into flour for cookie dough. 25 | Pound { acorns: u32 }, 26 | 27 | Sparkle { 28 | #[structopt(short)] 29 | color: String, 30 | }, 31 | } 32 | 33 | fn main() { 34 | let opt = MakeCookie::from_args(); 35 | println!("{:?}", opt); 36 | } 37 | -------------------------------------------------------------------------------- /tests/ui/subcommand_and_parse.stderr: -------------------------------------------------------------------------------- 1 | error: parse attribute is not allowed for subcommand 2 | --> $DIR/subcommand_and_parse.rs:17:29 3 | | 4 | 17 | #[structopt(subcommand, parse(from_occurrences))] 5 | | ^^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/subcommand_opt_opt.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | #[structopt(name = "make-cookie")] 13 | struct MakeCookie { 14 | #[structopt(short)] 15 | s: String, 16 | 17 | #[structopt(subcommand)] 18 | cmd: Option>, 19 | } 20 | 21 | #[derive(StructOpt, Debug)] 22 | enum Command { 23 | #[structopt(name = "pound")] 24 | /// Pound acorns into flour for cookie dough. 25 | Pound { acorns: u32 }, 26 | 27 | Sparkle { 28 | #[structopt(short)] 29 | color: String, 30 | }, 31 | } 32 | 33 | fn main() { 34 | let opt = MakeCookie::from_args(); 35 | println!("{:?}", opt); 36 | } 37 | -------------------------------------------------------------------------------- /tests/ui/subcommand_opt_opt.stderr: -------------------------------------------------------------------------------- 1 | error: Option> type is not allowed for subcommand 2 | --> $DIR/subcommand_opt_opt.rs:18:10 3 | | 4 | 18 | cmd: Option>, 5 | | ^^^^^^^^^^^^^^^^^^^^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/subcommand_opt_vec.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | #[structopt(name = "make-cookie")] 13 | struct MakeCookie { 14 | #[structopt(short)] 15 | s: String, 16 | 17 | #[structopt(subcommand)] 18 | cmd: Option>, 19 | } 20 | 21 | #[derive(StructOpt, Debug)] 22 | enum Command { 23 | #[structopt(name = "pound")] 24 | /// Pound acorns into flour for cookie dough. 25 | Pound { acorns: u32 }, 26 | 27 | Sparkle { 28 | #[structopt(short)] 29 | color: String, 30 | }, 31 | } 32 | 33 | fn main() { 34 | let opt = MakeCookie::from_args(); 35 | println!("{:?}", opt); 36 | } 37 | -------------------------------------------------------------------------------- /tests/ui/subcommand_opt_vec.stderr: -------------------------------------------------------------------------------- 1 | error: Option> type is not allowed for subcommand 2 | --> $DIR/subcommand_opt_vec.rs:18:10 3 | | 4 | 18 | cmd: Option>, 5 | | ^^^^^^^^^^^^^^^^^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/tuple_struct.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use structopt::StructOpt; 10 | 11 | #[derive(StructOpt, Debug)] 12 | #[structopt(name = "basic")] 13 | struct Opt(u32); 14 | 15 | fn main() { 16 | let opt = Opt::from_args(); 17 | println!("{:?}", opt); 18 | } 19 | -------------------------------------------------------------------------------- /tests/ui/tuple_struct.stderr: -------------------------------------------------------------------------------- 1 | error: structopt only supports non-tuple structs and enums 2 | --> $DIR/tuple_struct.rs:11:10 3 | | 4 | 11 | #[derive(StructOpt, Debug)] 5 | | ^^^^^^^^^ 6 | | 7 | = note: this error originates in the derive macro `StructOpt` (in Nightly builds, run with -Z macro-backtrace for more info) 8 | -------------------------------------------------------------------------------- /tests/utils.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused)] 2 | 3 | use structopt::StructOpt; 4 | 5 | pub fn get_help() -> String { 6 | let mut output = Vec::new(); 7 | ::clap().write_help(&mut output).unwrap(); 8 | let output = String::from_utf8(output).unwrap(); 9 | 10 | eprintln!("\n%%% HELP %%%:=====\n{}\n=====\n", output); 11 | eprintln!("\n%%% HELP (DEBUG) %%%:=====\n{:?}\n=====\n", output); 12 | 13 | output 14 | } 15 | 16 | pub fn get_long_help() -> String { 17 | let mut output = Vec::new(); 18 | ::clap() 19 | .write_long_help(&mut output) 20 | .unwrap(); 21 | let output = String::from_utf8(output).unwrap(); 22 | 23 | eprintln!("\n%%% LONG_HELP %%%:=====\n{}\n=====\n", output); 24 | eprintln!("\n%%% LONG_HELP (DEBUG) %%%:=====\n{:?}\n=====\n", output); 25 | 26 | output 27 | } 28 | 29 | pub fn get_subcommand_long_help(subcmd: &str) -> String { 30 | let output = ::clap() 31 | .get_matches_from_safe(vec!["test", subcmd, "--help"]) 32 | .expect_err("") 33 | .message; 34 | 35 | eprintln!( 36 | "\n%%% SUBCOMMAND `{}` HELP %%%:=====\n{}\n=====\n", 37 | subcmd, output 38 | ); 39 | eprintln!( 40 | "\n%%% SUBCOMMAND `{}` HELP (DEBUG) %%%:=====\n{:?}\n=====\n", 41 | subcmd, output 42 | ); 43 | 44 | output 45 | } 46 | -------------------------------------------------------------------------------- /tests/we_need_syn_full.rs: -------------------------------------------------------------------------------- 1 | // See https://github.com/TeXitoi/structopt/issues/354 2 | 3 | use structopt::StructOpt; 4 | 5 | #[test] 6 | fn we_need_syn_full() { 7 | #[allow(unused)] 8 | #[derive(Debug, StructOpt, Clone)] 9 | struct Args { 10 | #[structopt( 11 | short = "c", 12 | long = "colour", 13 | help = "Output colouring", 14 | default_value = "auto", 15 | possible_values = &["always", "auto", "never"] 16 | )] 17 | colour: String, 18 | } 19 | } 20 | --------------------------------------------------------------------------------