├── .clog.toml ├── .github ├── CONTRIBUTING.md └── ISSUE_TEMPLATE.md ├── .gitignore ├── CHANGELOG.md ├── CONTRIBUTORS.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── appveyor.yml ├── examples ├── README.md ├── after_help.rs ├── arg_enum_basic.rs ├── arg_enum_case_sensitive.rs ├── at_least_two.rs ├── basic.rs ├── deny_missing_docs.rs ├── doc_comments.rs ├── enum_in_args.rs ├── enum_tuple.rs ├── env.rs ├── example.rs ├── flatten.rs ├── git.rs ├── group.rs ├── keyvalue.rs ├── negative_flag.rs ├── no_version.rs ├── rename_all.rs ├── skip.rs ├── subcommand_aliases.rs └── true_or_false.rs ├── justfile ├── rustfmt.toml ├── src ├── derives │ ├── arg_enum.rs │ ├── attrs.rs │ ├── clap.rs │ ├── from_argmatches.rs │ ├── into_app.rs │ ├── mod.rs │ ├── parse.rs │ ├── spanned.rs │ └── ty.rs └── lib.rs └── tests ├── arg_enum_basic.rs ├── arg_enum_case_sensitive.rs ├── argument_naming.rs ├── arguments.rs ├── author_version_about.rs ├── basic.rs ├── custom-string-parsers.rs ├── deny-warnings.rs ├── doc-comments-help.rs ├── explicit_name_no_renaming.rs ├── flags.rs ├── flatten.rs ├── issues.rs ├── macro-errors.rs ├── nested-subcommands.rs ├── non_literal_attributes.rs ├── options.rs ├── privacy.rs ├── raw_bool_literal.rs ├── raw_idents.rs ├── skip.rs ├── special_types.rs ├── subcommands.rs ├── ui ├── bool_default_value.rs ├── bool_default_value.stderr ├── bool_required.rs ├── bool_required.stderr ├── clap_derive_empty_attr.rs ├── clap_derive_empty_attr.stderr ├── clap_derive_name_value_attr.rs ├── clap_derive_name_value_attr.stderr ├── flatten_and_doc.rs ├── flatten_and_doc.stderr ├── flatten_and_methods.rs ├── flatten_and_methods.stderr ├── flatten_and_parse.rs ├── flatten_and_parse.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_flatten.rs ├── struct_flatten.stderr ├── struct_parse.rs ├── struct_parse.stderr ├── struct_subcommand.rs ├── struct_subcommand.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 /.clog.toml: -------------------------------------------------------------------------------- 1 | [clog] 2 | repository = "https://github.com/kbknapp/clap_derive" 3 | outfile = "CHANGELOG.md" 4 | from-latest-tag = true 5 | 6 | [sections] 7 | Performance = ["perf"] 8 | Improvements = ["impr", "im", "imp"] 9 | Documentation = ["docs"] 10 | Deprecations = ["depr"] 11 | Examples = ["examples"] 12 | "New Settings" = ["setting", "settings"] 13 | "API Additions" = ["add", "api"] 14 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | Contributions are always welcome! And there is a multitude of ways in which you can help depending on what you like to do, or are good at. Anything from documentation, code cleanup, issue completion, new features, you name it, even filing issues is contributing and greatly appreciated! 4 | 5 | Another really great way to help is if you find an interesting, or helpful way in which to use `clap_derive`. You can either add it to the [examples/](examples) directory, or file an issue and tell me. I'm all about giving credit where credit is due :) 6 | 7 | ### Testing Code 8 | 9 | To test with all features both enabled and disabled, you can run these commands: 10 | 11 | ```sh 12 | $ cargo test 13 | ``` 14 | 15 | Alternatively, if you have [`just`](https://github.com/casey/just) installed you can run the prebuilt recipes. *Not* using `just` is perfectly fine as well, it simply bundles commands automatically. 16 | 17 | For example, to test the code, as above simply run: 18 | 19 | ```sh 20 | $ just run-tests 21 | ``` 22 | 23 | From here on, I will list the appropriate `cargo` command as well as the `just` command. 24 | 25 | Sometimes it's helpful to only run a subset of the tests, which can be done via: 26 | 27 | ```sh 28 | $ cargo test --test 29 | 30 | # Or 31 | 32 | $ just run-test 33 | ``` 34 | 35 | ### Linting Code 36 | 37 | During the CI process `clap_derive` runs against many different lints using [`clippy`](https://github.com/Manishearth/rust-clippy). In order to check if these lints pass on your own computer prior to submitting a PR you'll need a nightly compiler. 38 | 39 | In order to check the code for lints run either: 40 | 41 | ```sh 42 | $ cargo +nightly build --features lints 43 | 44 | # Or 45 | 46 | $ just lint 47 | ``` 48 | 49 | ### Commit Messages 50 | 51 | I use a [conventional](https://github.com/ajoslin/conventional-changelog/blob/a5505865ff3dd710cf757f50530e73ef0ca641da/conventions/angular.md) changelog format so I can update my changelog automatically using [clog](https://github.com/clog-tool/clog-cli) 52 | 53 | * Please format your commit subject line using the following format: `TYPE(COMPONENT): MESSAGE` where `TYPE` is one of the following: 54 | - `api` - An addition to the API 55 | - `setting` - A new `AppSettings` variant 56 | - `feat` - A new feature of an existing API 57 | - `imp` - An improvement to an existing feature/API 58 | - `perf` - A performance improvement 59 | - `docs` - Changes to documentation only 60 | - `tests` - Changes to the testing framework or tests only 61 | - `fix` - A bug fix 62 | - `refactor` - Code functionality doesn't change, but underlying structure may 63 | - `style` - Stylistic changes only, no functionality changes 64 | - `wip` - A work in progress commit (Should typically be `git rebase`'ed away) 65 | - `chore` - Catch all or things that have to do with the build system, etc 66 | - `examples` - Changes to existing example, or a new example 67 | * The `COMPONENT` is optional, and may be a single file, directory, or logical component. Parenthesis can be omitted if you are opting not to use the `COMPONENT`. 68 | 69 | ### Tests and Documentation 70 | 71 | 1. Create tests for your changes 72 | 2. **Ensure the tests are passing.** Run the tests (`cargo test`), alternatively `just run-tests` if you have `just` installed. 73 | 3. **Optional** Run the lints (`cargo +nightly build --features lints`) (requires a nightly compiler), alternatively `just lint` 74 | 4. Ensure your changes contain documentation if adding new APIs or features. 75 | 76 | ### Preparing the PR 77 | 78 | 1. `git rebase` into concise commits and remove `--fixup`s or `wip` commits (`git rebase -i HEAD~NUM` where `NUM` is number of commits back to start the rebase) 79 | 2. Push your changes back to your fork (`git push origin $your-branch`) 80 | 3. Create a pull request against `master`! (You can also create the pull request first, and we'll merge when ready. This a good way to discuss proposed changes.) 81 | 82 | ### Other ways to contribute 83 | 84 | Another really great way to help is if you find an interesting, or helpful way in which to use `clap_derive`. You can either add it to the [examples/](../examples) directory, or file an issue and tell me. I'm all about giving credit where credit is due :) 85 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 4 | 5 | ### Rust Version 6 | 7 | * Use the output of `rustc -V` 8 | 9 | ### Affected Version of clap and clap_derive 10 | 11 | * Can be found in Cargo.lock of your project (i.e. `grep clap Cargo.lock`) 12 | 13 | ### Expected Behavior Summary 14 | 15 | 16 | ### Actual Behavior Summary 17 | 18 | 19 | ### Steps to Reproduce the issue 20 | 21 | 22 | ### Sample Code or Link to Sample Code 23 | 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled files 2 | *.o 3 | *.so 4 | *.rlib 5 | *.dll 6 | 7 | # Executables 8 | *.exe 9 | 10 | # Generated by Cargo 11 | /target/ 12 | /clap-test/target/ 13 | 14 | # Cargo files 15 | Cargo.lock 16 | 17 | # Temp files 18 | .*~ 19 | 20 | # Backup files 21 | *.bak 22 | *.bk 23 | *.orig 24 | 25 | # Project files 26 | .vscode/* 27 | .idea/* 28 | clap-rs.iml 29 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # v0.2.10 (2018-06-07) 2 | 3 | * 1.21.0 is the minimum required rustc version by 4 | [@TeXitoi](https://github.com/TeXitoi) 5 | 6 | # v0.2.9 (2018-06-05) 7 | 8 | * Fix a bug when using `flatten` by 9 | [@fbenkstein](https://github.com/fbenkstein) 10 | * Update syn, quote and proc_macro2 by 11 | [@TeXitoi](https://github.com/TeXitoi) 12 | * Fix a regression when there is multiple authors by 13 | [@windwardly](https://github.com/windwardly) 14 | 15 | # v0.2.8 (2018-04-28) 16 | 17 | * Add `StructOpt::from_iter_safe()`, which returns an `Error` instead of 18 | killing the program when it fails to parse, or parses one of the 19 | short-circuiting flags. ([#98](https://github.com/TeXitoi/structopt/pull/98) 20 | by [@quodlibetor](https://github.com/quodlibetor)) 21 | * Allow users to enable `clap` features independently by 22 | [@Kerollmops](https://github.com/Kerollmops) 23 | * Fix a bug when flattening an enum 24 | ([#103](https://github.com/TeXitoi/structopt/pull/103) by 25 | [@TeXitoi](https://github.com/TeXitoi) 26 | 27 | # v0.2.7 (2018-04-12) 28 | 29 | * Add flattening, the insertion of options of another StructOpt struct 30 | into another ([#92](https://github.com/TeXitoi/structopt/pull/92)) 31 | by [@birkenfeld](https://github.com/birkenfeld) 32 | * Fail compilation when using `default_value` or `required` with 33 | `Option` ([#88](https://github.com/TeXitoi/structopt/pull/88)) by 34 | [@Kerollmops](https://github.com/Kerollmops) 35 | 36 | # v0.2.6 (2018-03-31) 37 | 38 | * Fail compilation when using `default_value` or `required` with `bool` ([#80](https://github.com/TeXitoi/structopt/issues/80)) by [@TeXitoi](https://github.com/TeXitoi) 39 | * Fix compilation with `#[deny(warnings)]` with the `!` type (https://github.com/rust-lang/rust/pull/49039#issuecomment-376398999) by [@TeXitoi](https://github.com/TeXitoi) 40 | * Improve first example in the documentation ([#82](https://github.com/TeXitoi/structopt/issues/82)) by [@TeXitoi](https://github.com/TeXitoi) 41 | 42 | # v0.2.5 (2018-03-07) 43 | 44 | * Work around breakage when `proc-macro2`'s nightly feature is enabled. ([#77](https://github.com/Texitoi/structopt/pull/77) and [proc-macro2#67](https://github.com/alexcrichton/proc-macro2/issues/67)) by [@fitzgen](https://github.com/fitzgen) 45 | 46 | # v0.2.4 (2018-02-25) 47 | 48 | * Fix compilation with `#![deny(missig_docs]` ([#74](https://github.com/TeXitoi/structopt/issues/74)) by [@TeXitoi](https://github.com/TeXitoi) 49 | * Fix [#76](https://github.com/TeXitoi/structopt/issues/76) by [@TeXitoi](https://github.com/TeXitoi) 50 | * Re-licensed to Apache-2.0/MIT by [@CAD97](https://github.com/cad97) 51 | 52 | # v0.2.3 (2018-02-16) 53 | 54 | * An empty line in a doc comment will result in a double linefeed in the generated about/help call by [@TeXitoi](https://github.com/TeXitoi) 55 | 56 | # v0.2.2 (2018-02-12) 57 | 58 | * Fix [#66](https://github.com/TeXitoi/structopt/issues/66) by [@TeXitoi](https://github.com/TeXitoi) 59 | 60 | # v0.2.1 (2018-02-11) 61 | 62 | * Fix a bug around enum tuple and the about message in the global help by [@TeXitoi](https://github.com/TeXitoi) 63 | * Fix [#65](https://github.com/TeXitoi/structopt/issues/65) by [@TeXitoi](https://github.com/TeXitoi) 64 | 65 | # v0.2.0 (2018-02-10) 66 | 67 | ## Breaking changes 68 | 69 | ### Don't special case `u64` by [@SergioBenitez](https://github.com/SergioBenitez) 70 | 71 | If you are using a `u64` in your struct to get the number of occurence of a flag, you should now add `parse(from_occurrences)` on the flag. 72 | 73 | For example 74 | ```rust 75 | #[clap(short = "v", long = "verbose")] 76 | verbose: u64, 77 | ``` 78 | must be changed by 79 | ```rust 80 | #[clap(short = "v", long = "verbose", parse(from_occurrences))] 81 | verbose: u64, 82 | ``` 83 | 84 | This feature was surprising as shown in [#30](https://github.com/TeXitoi/structopt/issues/30). Using the `parse` feature seems much more natural. 85 | 86 | ### Change the signature of `Structopt::from_clap` to take its argument by reference by [@TeXitoi](https://github.com/TeXitoi) 87 | 88 | There was no reason to take the argument by value. Most of the StructOpt users will not be impacted by this change. If you are using `StructOpt::from_clap`, just add a `&` before the argument. 89 | 90 | ### Fail if attributes are not used by [@TeXitoi](https://github.com/TeXitoi) 91 | 92 | StructOpt was quite fuzzy in its attribute parsing: it was only searching for interresting things, e. g. something like `#[clap(foo(bar))]` was accepted but not used. It now fails the compilation. 93 | 94 | You should have nothing to do here. This breaking change may highlight some missuse that can be bugs. 95 | 96 | In future versions, if there is cases that are not highlighed, they will be considerated as bugs, not breaking changes. 97 | 98 | ### Use `raw()` wrapping instead of `_raw` suffixing by [@TeXitoi](https://github.com/TeXitoi) 99 | 100 | The syntax of raw attributes is changed to improve the syntax. 101 | 102 | You have to change `foo_raw = "bar", baz_raw = "foo"` by `raw(foo = "bar", baz = "foo")` or `raw(foo = "bar"), raw(baz = "foo")`. 103 | 104 | ## New features 105 | 106 | * Add `parse(from_occurrences)` parser by [@SergioBenitez](https://github.com/SergioBenitez) 107 | * Support 1-uple enum variant as subcommand by [@TeXitoi](https://github.com/TeXitoi) 108 | * structopt-derive crate is now an implementation detail, structopt reexport the custom derive macro by [@TeXitoi](https://github.com/TeXitoi) 109 | * Add the `StructOpt::from_iter` method by [@Kerollmops](https://github.com/Kerollmops) 110 | 111 | ## Documentation 112 | 113 | * Improve doc by [@bestouff](https://github.com/bestouff) 114 | * All the documentation is now on the structopt crate by [@TeXitoi](https://github.com/TeXitoi) 115 | 116 | # v0.1.7 (2018-01-23) 117 | 118 | * Allow opting out of clap default features by [@ski-csis](https://github.com/ski-csis) 119 | 120 | # v0.1.6 (2017-11-25) 121 | 122 | * Improve documentation by [@TeXitoi](https://github.com/TeXitoi) 123 | * Fix bug [#31](https://github.com/TeXitoi/structopt/issues/31) by [@TeXitoi](https://github.com/TeXitoi) 124 | 125 | # v0.1.5 (2017-11-14) 126 | 127 | * Fix a bug with optional subsubcommand and Enum by [@TeXitoi](https://github.com/TeXitoi) 128 | 129 | # v0.1.4 (2017-11-09) 130 | 131 | * Implement custom string parser from either `&str` or `&OsStr` by [@kennytm](https://github.com/kennytm) 132 | 133 | # v0.1.3 (2017-11-01) 134 | 135 | * Improve doc by [@TeXitoi](https://github.com/TeXitoi) 136 | 137 | # v0.1.2 (2017-11-01) 138 | 139 | * Fix bugs [#24](https://github.com/TeXitoi/structopt/issues/24) and [#25](https://github.com/TeXitoi/structopt/issues/25) by [@TeXitoi](https://github.com/TeXitoi) 140 | * Support of methods with something else that a string as argument thanks to `_raw` suffix by [@Flakebi](https://github.com/Flakebi) 141 | 142 | # v0.1.1 (2017-09-22) 143 | 144 | * Better formating of multiple authors by [@killercup](https://github.com/killercup) 145 | 146 | # v0.1.0 (2017-07-17) 147 | 148 | * Subcommand support by [@williamyaoh](https://github.com/williamyaoh) 149 | 150 | # v0.0.5 (2017-06-16) 151 | 152 | * Using doc comment to populate help by [@killercup](https://github.com/killercup) 153 | 154 | # v0.0.3 (2017-02-11) 155 | 156 | * First version with flags, arguments and options support by [@TeXitoi](https://github.com/TeXitoi) 157 | -------------------------------------------------------------------------------- /CONTRIBUTORS.md: -------------------------------------------------------------------------------- 1 | # Contributors to `clap_derive` 2 | 3 | | [TeXitoi](https://github.com/TeXitoi) | [williamyaoh](https://github.com/williamyaoh) | [kbknapp](https://github.com/kbknapp) | [killercup](https://github.com/killercup) | [Kerollmops](https://github.com/Kerollmops) | [Hoverbear](https://github.com/Hoverbear) | 4 | | :----------------------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------: | 5 | | [TeXitoi](https://github.com/TeXitoi) | [williamyaoh](https://github.com/williamyaoh) | [kbknapp](https://github.com/kbknapp) | [killercup](https://github.com/killercup) | [Kerollmops](https://github.com/Kerollmops) | [Hoverbear](https://github.com/Hoverbear) | 6 | 7 | | [SergioBenitez](https://github.com/SergioBenitez) | [quodlibetor](https://github.com/quodlibetor) | [bruceadams](https://github.com/bruceadams) | [CAD97](https://github.com/CAD97) | [fbenkstein](https://github.com/fbenkstein) | [windwardly](https://github.com/windwardly) | 8 | | :----------------------------------------------------------------------------------------------------------------------------------------: | :-----------------------------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------: | :-----------------------------------------------------------------------------------------------------------------------------------: | 9 | | [SergioBenitez](https://github.com/SergioBenitez) | [quodlibetor](https://github.com/quodlibetor) | [bruceadams](https://github.com/bruceadams) | [CAD97](https://github.com/CAD97) | [fbenkstein](https://github.com/fbenkstein) | [windwardly](https://github.com/windwardly) | 10 | 11 | | [fitzgen](https://github.com/fitzgen) | [Flakebi](https://github.com/Flakebi) | [ski-csis](https://github.com/ski-csis) | [tvincent2](https://github.com/tvincent2) | [tshepang](https://github.com/tshepang) | [bestouff](https://github.com/bestouff) | 12 | | :--------------------------------------------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------------------------------------------------------: | :-----------------------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------: | 13 | | [fitzgen](https://github.com/fitzgen) | [Flakebi](https://github.com/Flakebi) | [ski-csis](https://github.com/ski-csis) | [tvincent2](https://github.com/tvincent2) | [tshepang](https://github.com/tshepang) | [bestouff](https://github.com/bestouff) | 14 | 15 | | [hcpl](https://github.com/hcpl) | [kennytm](https://github.com/kennytm) | [spease](https://github.com/spease) | [birkenfeld](https://github.com/birkenfeld) | 16 | | :-----------------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------: | 17 | | [hcpl](https://github.com/hcpl) | [kennytm](https://github.com/kennytm) | [spease](https://github.com/spease) | [birkenfeld](https://github.com/birkenfeld) | 18 | 19 | This list was generated by [mgechev/github-contributors-list](https://github.com/mgechev/github-contributors-list) 20 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "clap_derive" 3 | version = "0.3.0" 4 | edition = "2018" 5 | authors = [ 6 | "Guillaume Pinot ", 7 | "Kevin K. ", 8 | "hoverbear " 9 | ] 10 | description = "Parse command line argument by defining a struct, derive crate." 11 | documentation = "https://docs.rs/clap_derive" 12 | repository = "https://github.com/clap-rs/clap_derive" 13 | keywords = ["clap", "cli", "derive", "proc_macro", "parse"] 14 | categories = ["command-line-interface", "development-tools::procedural-macro-helpers"] 15 | license = "Apache-2.0/MIT" 16 | readme = "README.md" 17 | 18 | [lib] 19 | proc-macro = true 20 | 21 | [badges] 22 | travis-ci = { repository = "clap-rs/clap_derive" } 23 | appveyor = { repository = "https://github.com/clap-rs/clap_derive", service = "github" } 24 | 25 | [dependencies] 26 | syn = { version = "1", features = ["full"] } 27 | quote = "1" 28 | proc-macro2 = "1" 29 | heck = "0.3.0" 30 | proc-macro-error = "0.4.3" 31 | 32 | [dev-dependencies] 33 | clap = { git = "https://github.com/clap-rs/clap", branch = "master"} # ONLY FOR INITIAL DEVELOPMENT...change to real crates.io ver for rlease! 34 | trybuild = "1.0.5" 35 | rustversion = "0.1" 36 | 37 | [features] 38 | default = [] 39 | nightly = [] 40 | lints = [] 41 | debug = [] 42 | doc = [] 43 | -------------------------------------------------------------------------------- /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 | The repository has been moved to https://github.com/clap-rs/clap/tree/master/clap_derive as part of monorepo workspace. 2 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | environment: 2 | matrix: 3 | - TARGET: x86_64-pc-windows-gnu 4 | RUST_VERSION: stable 5 | - TARGET: x86_64-pc-windows-gnu 6 | RUST_VERSION: nightly 7 | 8 | install: 9 | - curl -sSf -o rustup-init.exe https://win.rustup.rs/ 10 | - rustup-init.exe -y --default-host %TARGET% --default-toolchain %RUST_VERSION% 11 | - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin 12 | - rustc -Vv 13 | - cargo -V 14 | 15 | # Building is done in the test phase, so we disable Appveyor's build phase. 16 | build: false 17 | 18 | cache: 19 | - C:\Users\appveyor\.cargo\registry 20 | - target 21 | 22 | test_script: 23 | - cargo test -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # Collection of examples "how to use `clap_derive`" 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 `clap_derive`. 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 `clap_derive`. 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 an how it interacts with `default_value`. 35 | 36 | ### [Advanced](example.rs) 37 | 38 | Somewhat complex example of usage of `clap_derive`. 39 | 40 | ### [Flatten](flatten.rs) 41 | 42 | How to use `#[clap(flatten)]` 43 | 44 | ### [Git](git.rs) 45 | 46 | Pseudo-`git` example, shows how to use subcommands and how to document them. 47 | 48 | ### [Groups](group.rs) 49 | 50 | Using `clap::Arg::group` with `clap`. 51 | 52 | ### [`key=value` pairs](keyvalue.rs) 53 | 54 | How to parse `key=value` pairs. 55 | 56 | ### [`--no-*` flags](negative_flag.rs) 57 | 58 | How to add `no-thing` flag which is `true` by default and `false` if passed. 59 | 60 | ### [No version](no_version.rs) 61 | 62 | How to completely remove version. 63 | 64 | ### [Rename all](rename_all.rs) 65 | 66 | How `#[clap(rename_all)]` works. 67 | 68 | ### [Skip](skip.rs) 69 | 70 | How to use `#[clap(skip)]`. 71 | 72 | ### [Aliases](subcommand_aliases.rs) 73 | 74 | How to use aliases 75 | 76 | ### [`true` or `false`](true_or_false.rs) 77 | 78 | How to express "`"true"` or `"false"` argument. 79 | -------------------------------------------------------------------------------- /examples/after_help.rs: -------------------------------------------------------------------------------- 1 | //! How to append a postscript to the help message generated. 2 | 3 | use clap::Clap; 4 | 5 | /// I am a program and I do things. 6 | /// 7 | /// Sometimes they even work. 8 | #[derive(Clap, Debug)] 9 | #[clap(after_help = "Beware `-d`, dragons be here")] 10 | struct Opt { 11 | /// Release the dragon. 12 | #[clap(short)] 13 | dragon: bool, 14 | } 15 | 16 | fn main() { 17 | let opt = Opt::parse(); 18 | println!("{:?}", opt); 19 | } 20 | -------------------------------------------------------------------------------- /examples/arg_enum_basic.rs: -------------------------------------------------------------------------------- 1 | // #[macro_use] 2 | // extern crate clap; 3 | 4 | // use clap::{App, Arg}; 5 | 6 | fn main() {} 7 | 8 | // #[derive(ArgEnum, Debug)] 9 | // enum ArgChoice { 10 | // Foo, 11 | // Bar, 12 | // Baz, 13 | // } 14 | 15 | // fn main() { 16 | // let matches = App::new(env!("CARGO_PKG_NAME")) 17 | // .arg( 18 | // Arg::with_name("arg") 19 | // .required(true) 20 | // .takes_value(true) 21 | // .possible_values(&ArgChoice::variants()), 22 | // ) 23 | // .get_matches(); 24 | 25 | // let t = value_t!(matches.value_of("arg"), ArgChoice).unwrap_or_else(|e| e.exit()); 26 | 27 | // println!("{:?}", t); 28 | // } 29 | -------------------------------------------------------------------------------- /examples/arg_enum_case_sensitive.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | // #[macro_use] 3 | // extern crate clap; 4 | 5 | // use clap::{App, Arg}; 6 | 7 | // #[derive(ArgEnum, Debug)] 8 | // #[case_sensitive] 9 | // enum ArgChoice { 10 | // Foo, 11 | // Bar, 12 | // Baz, 13 | // } 14 | 15 | // fn main() { 16 | // let matches = App::new(env!("CARGO_PKG_NAME")) 17 | // .arg( 18 | // Arg::with_name("arg") 19 | // .required(true) 20 | // .takes_value(true) 21 | // .possible_values(&ArgChoice::variants()), 22 | // ) 23 | // .get_matches(); 24 | 25 | // let t = value_t!(matches.value_of("arg"), ArgChoice).unwrap_or_else(|e| e.exit()); 26 | 27 | // println!("{:?}", t); 28 | // } 29 | -------------------------------------------------------------------------------- /examples/at_least_two.rs: -------------------------------------------------------------------------------- 1 | //! How to require presence of at least N values, 2 | //! like `val1 val2 ... valN ... valM`. 3 | 4 | use clap::Clap; 5 | 6 | #[derive(Clap, Debug)] 7 | struct Opt { 8 | #[clap(required = true, min_values = 2)] 9 | foos: Vec, 10 | } 11 | 12 | fn main() { 13 | let opt = Opt::parse(); 14 | println!("{:?}", opt); 15 | } 16 | -------------------------------------------------------------------------------- /examples/basic.rs: -------------------------------------------------------------------------------- 1 | //! A somewhat comprehensive example of a typical `StructOpt` usage.use 2 | 3 | use clap::Clap; 4 | use std::path::PathBuf; 5 | 6 | /// A basic example 7 | #[derive(Clap, Debug)] 8 | #[clap(name = "basic")] 9 | struct Opt { 10 | // A flag, true if used in the command line. Note doc comment will 11 | // be used for the help message of the flag. The name of the 12 | // argument will be, by default, based on the name of the field. 13 | /// Activate debug mode 14 | #[clap(short, long)] 15 | debug: bool, 16 | 17 | // The number of occurrences of the `v/verbose` flag 18 | /// Verbose mode (-v, -vv, -vvv, etc.) 19 | #[clap(short, long, parse(from_occurrences))] 20 | verbose: u8, 21 | 22 | /// Set speed 23 | #[clap(short, long, default_value = "42")] 24 | speed: f64, 25 | 26 | /// Output file 27 | #[clap(short, long, parse(from_os_str))] 28 | output: PathBuf, 29 | 30 | // the long option will be translated by default to kebab case, 31 | // i.e. `--nb-cars`. 32 | /// Number of cars 33 | #[clap(short = "c", long)] 34 | nb_cars: Option, 35 | 36 | /// admin_level to consider 37 | #[clap(short, long)] 38 | level: Vec, 39 | 40 | /// Files to process 41 | #[clap(name = "FILE", parse(from_os_str))] 42 | files: Vec, 43 | } 44 | 45 | fn main() { 46 | let opt = Opt::parse(); 47 | println!("{:#?}", opt); 48 | } 49 | -------------------------------------------------------------------------------- /examples/deny_missing_docs.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) , 2 | // Kevin Knapp (@kbknapp) , and 3 | // Andrew Hobden (@hoverbear) 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | // 11 | // This work was derived from Structopt (https://github.com/TeXitoi/structopt) 12 | // commit#ea76fa1b1b273e65e3b0b1046643715b49bec51f which is licensed under the 13 | // MIT/Apache 2.0 license. 14 | 15 | //! A test to check that clap_derive compiles with deny(missing_docs) 16 | 17 | #![deny(missing_docs)] 18 | 19 | use clap::Clap; 20 | 21 | /// The options 22 | #[derive(Clap, Debug, PartialEq)] 23 | pub struct Opt { 24 | #[clap(short)] 25 | verbose: bool, 26 | #[clap(subcommand)] 27 | cmd: Option, 28 | } 29 | 30 | /// Some subcommands 31 | #[derive(Clap, Debug, PartialEq)] 32 | pub enum Cmd { 33 | /// command A 34 | A, 35 | /// command B 36 | B { 37 | /// Alice? 38 | #[clap(short)] 39 | alice: bool, 40 | }, 41 | /// command C 42 | C(COpt), 43 | } 44 | 45 | /// The options for C 46 | #[derive(Clap, Debug, PartialEq)] 47 | pub struct COpt { 48 | #[clap(short)] 49 | bob: bool, 50 | } 51 | 52 | fn main() { 53 | println!("{:?}", Opt::parse()); 54 | } 55 | -------------------------------------------------------------------------------- /examples/doc_comments.rs: -------------------------------------------------------------------------------- 1 | //! How to use doc comments in place of `help/long_help`. 2 | 3 | use clap::Clap; 4 | 5 | /// A basic example for the usage of doc comments as replacement 6 | /// of the arguments `help`, `long_help`, `about` and `long_about`. 7 | #[derive(Clap, Debug)] 8 | #[clap(name = "basic")] 9 | struct Opt { 10 | /// Just use doc comments to replace `help`, `long_help`, 11 | /// `about` or `long_about` input. 12 | #[clap(short, long)] 13 | first_flag: bool, 14 | 15 | /// Split between `help` and `long_help`. 16 | /// 17 | /// In the previous case clap is going to present 18 | /// the whole comment both as text for the `help` and the 19 | /// `long_help` argument. 20 | /// 21 | /// But if the doc comment is formatted like this example 22 | /// -- with an empty second line splitting the heading and 23 | /// the rest of the comment -- only the first line is used 24 | /// as `help` argument. The `long_help` argument will still 25 | /// contain the whole comment. 26 | /// 27 | /// ## Attention 28 | /// 29 | /// Any formatting next to empty lines that could be used 30 | /// inside a doc comment is currently not preserved. If 31 | /// lists or other well formatted content is required it is 32 | /// necessary to use the related clap argument with a 33 | /// raw string as shown on the `third_flag` description. 34 | #[clap(short, long)] 35 | second_flag: bool, 36 | 37 | #[clap( 38 | short, 39 | long, 40 | long_help = r"This is a raw string. 41 | 42 | It can be used to pass well formatted content (e.g. lists or source 43 | code) in the description: 44 | 45 | - first example list entry 46 | - second example list entry 47 | " 48 | )] 49 | third_flag: bool, 50 | 51 | #[clap(subcommand)] 52 | sub_command: SubCommand, 53 | } 54 | 55 | #[derive(Clap, Debug)] 56 | #[clap()] 57 | enum SubCommand { 58 | /// The same rules described previously for flags. Are 59 | /// also true for in regards of sub-commands. 60 | First, 61 | 62 | /// Applicable for both `about` an `help`. 63 | /// 64 | /// The formatting rules described in the comment of the 65 | /// `second_flag` also apply to the description of 66 | /// sub-commands which is normally given through the `about` 67 | /// and `long_about` arguments. 68 | Second, 69 | } 70 | 71 | fn main() { 72 | let opt = Opt::parse(); 73 | println!("{:?}", opt); 74 | } 75 | -------------------------------------------------------------------------------- /examples/enum_in_args.rs: -------------------------------------------------------------------------------- 1 | //! How to use `arg_enum!` with `StructOpt`. 2 | // TODO: make it work 3 | fn main() {} 4 | // use clap::Clap; 5 | 6 | // arg_enum! { 7 | // #[derive(Debug)] 8 | // enum Baz { 9 | // Foo, 10 | // Bar, 11 | // FooBar 12 | // } 13 | // } 14 | 15 | // #[derive(Clap, Debug)] 16 | // struct Opt { 17 | // /// Important argument. 18 | // #[clap(possible_values = &Baz::variants(), case_insensitive = true)] 19 | // i: Baz, 20 | // } 21 | 22 | // fn main() { 23 | // let opt = Opt::parse(); 24 | // println!("{:?}", opt); 25 | // } 26 | -------------------------------------------------------------------------------- /examples/enum_tuple.rs: -------------------------------------------------------------------------------- 1 | //! How to extract subcommands' args into external structs. 2 | 3 | use clap::Clap; 4 | 5 | #[derive(Debug, Clap)] 6 | pub struct Foo { 7 | pub bar: Option, 8 | } 9 | 10 | #[derive(Debug, Clap)] 11 | pub enum Command { 12 | #[clap(name = "foo")] 13 | Foo(Foo), 14 | } 15 | 16 | #[derive(Debug, Clap)] 17 | #[clap(name = "classify")] 18 | pub struct ApplicationArguments { 19 | #[clap(subcommand)] 20 | pub command: Command, 21 | } 22 | 23 | fn main() { 24 | let opt = ApplicationArguments::parse(); 25 | println!("{:?}", opt); 26 | } 27 | -------------------------------------------------------------------------------- /examples/env.rs: -------------------------------------------------------------------------------- 1 | //! How to use environment variable fallback an how it 2 | //! interacts with `default_value`. 3 | 4 | use clap::Clap; 5 | 6 | /// Example for allowing to specify options via environment variables. 7 | #[derive(Clap, Debug)] 8 | #[clap(name = "env")] 9 | struct Opt { 10 | // Use `env` to enable specifying the option with an environment 11 | // variable. Command line arguments take precedence over env. 12 | /// URL for the API server 13 | #[clap(long, env = "API_URL")] 14 | api_url: String, 15 | 16 | // The default value is used if neither argument nor environment 17 | // variable is specified. 18 | /// Number of retries 19 | #[clap(long, env = "RETRIES", default_value = "5")] 20 | retries: u32, 21 | } 22 | 23 | fn main() { 24 | let opt = Opt::parse(); 25 | println!("{:#?}", opt); 26 | } 27 | -------------------------------------------------------------------------------- /examples/example.rs: -------------------------------------------------------------------------------- 1 | //! Somewhat complex example of usage of structopt. 2 | 3 | use clap::Clap; 4 | 5 | #[derive(Clap, Debug)] 6 | #[clap(name = "example")] 7 | /// An example of clap_derive usage. 8 | struct Opt { 9 | // A flag, true if used in the command line. 10 | #[clap(short, long)] 11 | /// Activate debug mode 12 | debug: bool, 13 | 14 | // An argument of type float, with a default value. 15 | #[clap(short, long, default_value = "42")] 16 | /// Set speed 17 | speed: f64, 18 | 19 | // Needed parameter, the first on the command line. 20 | /// Input file 21 | input: String, 22 | 23 | // An optional parameter, will be `None` if not present on the 24 | // command line. 25 | /// Output file, stdout if not present 26 | output: Option, 27 | 28 | // An optional parameter with optional value, will be `None` if 29 | // not present on the command line, will be `Some(None)` if no 30 | // argument is provided (i.e. `--log`) and will be 31 | // `Some(Some(String))` if argument is provided (e.g. `--log 32 | // log.txt`). 33 | #[clap(long)] 34 | #[allow(clippy::option_option)] 35 | /// Log file, stdout if no file, no logging if not present 36 | log: Option>, 37 | 38 | // An optional list of values, will be `None` if not present on 39 | // the command line, will be `Some(vec![])` if no argument is 40 | // provided (i.e. `--optv`) and will be `Some(Some(String))` if 41 | // argument list is provided (e.g. `--optv a b c`). 42 | #[clap(long)] 43 | optv: Option>, 44 | 45 | // Skipped option: it won't be parsed and will be filled with the 46 | // default value for its type (in this case it'll be an empty string). 47 | #[clap(skip)] 48 | skipped: String, 49 | } 50 | 51 | fn main() { 52 | let opt = Opt::parse(); 53 | println!("{:?}", opt); 54 | } 55 | -------------------------------------------------------------------------------- /examples/flatten.rs: -------------------------------------------------------------------------------- 1 | //! How to use flattening. 2 | 3 | use clap::Clap; 4 | 5 | #[derive(Clap, Debug)] 6 | struct Cmdline { 7 | /// switch verbosity on 8 | #[clap(short)] 9 | verbose: bool, 10 | 11 | #[clap(flatten)] 12 | daemon_opts: DaemonOpts, 13 | } 14 | 15 | #[derive(Clap, Debug)] 16 | struct DaemonOpts { 17 | /// daemon user 18 | #[clap(short)] 19 | user: String, 20 | 21 | /// daemon group 22 | #[clap(short)] 23 | group: String, 24 | } 25 | 26 | fn main() { 27 | let opt = Cmdline::parse(); 28 | println!("{:?}", opt); 29 | } 30 | -------------------------------------------------------------------------------- /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 | use clap::Clap; 7 | 8 | #[derive(Clap, Debug)] 9 | #[clap(name = "git")] 10 | /// the stupid content tracker 11 | enum Opt { 12 | /// fetch branches from remote repository 13 | Fetch { 14 | #[clap(long)] 15 | dry_run: bool, 16 | #[clap(long)] 17 | all: bool, 18 | #[clap(default_value = "origin")] 19 | repository: String, 20 | }, 21 | #[clap(override_help = "add files to the staging area")] 22 | Add { 23 | #[clap(short)] 24 | interactive: bool, 25 | #[clap(short)] 26 | all: bool, 27 | files: Vec, 28 | }, 29 | } 30 | 31 | fn main() { 32 | let matches = Opt::parse(); 33 | 34 | println!("{:?}", matches); 35 | } 36 | -------------------------------------------------------------------------------- /examples/group.rs: -------------------------------------------------------------------------------- 1 | //! How to use `clap::Arg::group` 2 | 3 | use clap::{ArgGroup, Clap}; 4 | 5 | #[derive(Clap, Debug)] 6 | #[clap(group = ArgGroup::with_name("verb").required(true))] 7 | struct Opt { 8 | /// Set a custom HTTP verb 9 | #[clap(long, group = "verb")] 10 | method: Option, 11 | /// HTTP GET 12 | #[clap(long, group = "verb")] 13 | get: bool, 14 | /// HTTP HEAD 15 | #[clap(long, group = "verb")] 16 | head: bool, 17 | /// HTTP POST 18 | #[clap(long, group = "verb")] 19 | post: bool, 20 | /// HTTP PUT 21 | #[clap(long, group = "verb")] 22 | put: bool, 23 | /// HTTP DELETE 24 | #[clap(long, group = "verb")] 25 | delete: bool, 26 | } 27 | 28 | fn main() { 29 | let opt = Opt::parse(); 30 | println!("{:?}", opt); 31 | } 32 | -------------------------------------------------------------------------------- /examples/keyvalue.rs: -------------------------------------------------------------------------------- 1 | //! How to parse "key=value" pairs with structopt. 2 | 3 | use clap::Clap; 4 | use std::error::Error; 5 | 6 | /// Parse a single key-value pair 7 | fn parse_key_val(s: &str) -> Result<(T, U), Box> 8 | where 9 | T: std::str::FromStr, 10 | T::Err: Error + 'static, 11 | U: std::str::FromStr, 12 | U::Err: Error + 'static, 13 | { 14 | let pos = s 15 | .find('=') 16 | .ok_or_else(|| format!("invalid KEY=value: no `=` found in `{}`", s))?; 17 | Ok((s[..pos].parse()?, s[pos + 1..].parse()?)) 18 | } 19 | 20 | #[derive(Clap, Debug)] 21 | struct Opt { 22 | // number_of_values = 1 forces the user to repeat the -D option for each key-value pair: 23 | // my_program -D a=1 -D b=2 24 | // Without number_of_values = 1 you can do: 25 | // my_program -D a=1 b=2 26 | // but this makes adding an argument after the values impossible: 27 | // my_program -D a=1 -D b=2 my_input_file 28 | // becomes invalid. 29 | #[clap(short = "D", parse(try_from_str = parse_key_val), number_of_values = 1)] 30 | defines: Vec<(String, i32)>, 31 | } 32 | 33 | fn main() { 34 | let opt = Opt::parse(); 35 | println!("{:?}", opt); 36 | } 37 | -------------------------------------------------------------------------------- /examples/negative_flag.rs: -------------------------------------------------------------------------------- 1 | //! How to add `no-thing` flag which is `true` by default and 2 | //! `false` if passed. 3 | 4 | use clap::Clap; 5 | 6 | #[derive(Debug, Clap)] 7 | struct Opt { 8 | #[clap(long = "no-verbose", parse(from_flag = std::ops::Not::not))] 9 | verbose: bool, 10 | } 11 | 12 | fn main() { 13 | let cmd = Opt::parse(); 14 | println!("{:#?}", cmd); 15 | } 16 | -------------------------------------------------------------------------------- /examples/no_version.rs: -------------------------------------------------------------------------------- 1 | //! How to completely remove version. 2 | 3 | use clap::{AppSettings, Clap}; 4 | 5 | #[derive(Clap, Debug)] 6 | #[clap( 7 | name = "no_version", 8 | no_version, 9 | global_setting = AppSettings::DisableVersion 10 | )] 11 | struct Opt {} 12 | 13 | fn main() { 14 | let opt = Opt::parse(); 15 | println!("{:?}", opt); 16 | } 17 | -------------------------------------------------------------------------------- /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 | use clap::Clap; 22 | 23 | #[derive(Clap, Debug)] 24 | #[clap(name = "rename_all", rename_all = "screaming_snake_case")] 25 | enum Opt { 26 | // This subcommand will be named `FIRST_COMMAND`. As the command doesn't 27 | // override the initial casing style, ... 28 | /// A screaming loud first command. Only use if necessary. 29 | FirstCommand { 30 | // this flag will be available as `--FOO` and `-F`. 31 | /// This flag will even scream louder. 32 | #[clap(long, short)] 33 | foo: bool, 34 | }, 35 | 36 | // As we override the casing style for this variant the related subcommand 37 | // will be named `SecondCommand`. 38 | /// Not nearly as loud as the first command. 39 | #[clap(rename_all = "pascal_case")] 40 | SecondCommand { 41 | // We can also override it again on a single field. 42 | /// Nice quiet flag. No one is annoyed. 43 | #[clap(rename_all = "snake_case", long)] 44 | bar_option: bool, 45 | 46 | // Renaming will not be propagated into subcommand flagged enums. If 47 | // a non default casing style is required it must be defined on the 48 | // enum itself. 49 | #[clap(subcommand)] 50 | cmds: Subcommands, 51 | 52 | // or flattened structs. 53 | #[clap(flatten)] 54 | options: BonusOptions, 55 | }, 56 | } 57 | 58 | #[derive(Clap, Debug)] 59 | enum Subcommands { 60 | // This one will be available as `first-subcommand`. 61 | FirstSubcommand, 62 | } 63 | 64 | #[derive(Clap, Debug)] 65 | struct BonusOptions { 66 | // And this one will be available as `baz-option`. 67 | #[clap(long)] 68 | baz_option: bool, 69 | } 70 | 71 | fn main() { 72 | let opt = Opt::parse(); 73 | println!("{:?}", opt); 74 | } 75 | -------------------------------------------------------------------------------- /examples/skip.rs: -------------------------------------------------------------------------------- 1 | //! How to use `#[structopt(skip)]` 2 | 3 | use clap::Clap; 4 | 5 | #[derive(Clap, Debug, PartialEq)] 6 | pub struct Opt { 7 | #[clap(long, short)] 8 | number: u32, 9 | #[clap(skip)] 10 | k: Kind, 11 | #[clap(skip)] 12 | v: Vec, 13 | 14 | #[clap(skip = Kind::A)] 15 | k2: Kind, 16 | #[clap(skip = vec![1, 2, 3])] 17 | v2: Vec, 18 | #[clap(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::parse_from(&["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 | use clap::{AppSettings, Clap}; 4 | 5 | #[derive(Clap, Debug)] 6 | // https://docs.rs/clap/2/clap/enum.AppSettings.html#variant.InferSubcommands 7 | #[clap(setting = AppSettings::InferSubcommands)] 8 | enum Opt { 9 | // https://docs.rs/clap/2/clap/struct.App.html#method.alias 10 | #[clap(alias = "foobar")] 11 | Foo, 12 | // https://docs.rs/clap/2/clap/struct.App.html#method.aliases 13 | #[clap(aliases = &["baz", "fizz"])] 14 | Bar, 15 | } 16 | 17 | fn main() { 18 | let opt = Opt::parse(); 19 | println!("{:?}", opt); 20 | } 21 | -------------------------------------------------------------------------------- /examples/true_or_false.rs: -------------------------------------------------------------------------------- 1 | //! How to parse `--foo=true --bar=false` and turn them into bool. 2 | 3 | use clap::Clap; 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(Clap, 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 | #[clap(long, parse(try_from_str))] 19 | foo: bool, 20 | 21 | // Of course, this could be done with an explicit parser function. 22 | #[clap(long, parse(try_from_str = true_or_false))] 23 | bar: bool, 24 | 25 | // `bool` can be positional only with explicit `parse(...)` annotation 26 | #[clap(long, parse(try_from_str))] 27 | boom: bool, 28 | } 29 | 30 | fn main() { 31 | assert_eq!( 32 | Opt::parse_from(&["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::try_parse_from(&["test", "--foo=beauty"]).is_err()); 41 | } 42 | -------------------------------------------------------------------------------- /justfile: -------------------------------------------------------------------------------- 1 | 2 | @update-contributors: 3 | echo 'Removing old CONTRIBUTORS.md' 4 | mv CONTRIBUTORS.md CONTRIBUTORS.md.bak 5 | echo 'Downloading a list of new contributors' 6 | echo "the following is a list of contributors:" > CONTRIBUTORS.md 7 | echo "" >> CONTRIBUTORS.md 8 | echo "" >> CONTRIBUTORS.md 9 | githubcontrib --owner kbknapp --repo clap_derive --sha master --cols 6 --format md --showlogin true --sortBy contributions --sortOrder desc >> CONTRIBUTORS.md 10 | echo "" >> CONTRIBUTORS.md 11 | echo "" >> CONTRIBUTORS.md 12 | echo "This list was generated by [mgechev/github-contributors-list](https://github.com/mgechev/github-contributors-list)" >> CONTRIBUTORS.md 13 | rm CONTRIBUTORS.md.bak 14 | 15 | run-test TESTG TEST="": 16 | cargo test --test {{TESTG}} -- {{TEST}} 17 | 18 | debug TESTG TEST="": 19 | cargo test --test {{TESTG}} --features debug -- {{TEST}} 20 | 21 | run-tests: 22 | cargo test 23 | 24 | @bench: nightly 25 | cargo bench && just remove-nightly 26 | 27 | nightly: 28 | rustup override add nightly 29 | 30 | remove-nightly: 31 | rustup override remove 32 | 33 | @lint: nightly 34 | cargo build --features lints && just remove-nightly 35 | 36 | clean: 37 | cargo clean 38 | find . -type f -name "*.orig" -exec rm {} \; 39 | find . -type f -name "*.bk" -exec rm {} \; 40 | find . -type f -name ".*~" -exec rm {} \; 41 | 42 | top-errors NUM="95": 43 | @cargo check 2>&1 | head -n {{NUM}} 44 | 45 | count-errors: 46 | @cargo check 2>&1 | grep -e '^error' | wc -l 47 | 48 | find-errors: 49 | @cargo check 2>&1 | grep --only-matching -e '-->[^:]*' | sort | uniq -c | sort -nr 50 | 51 | count-warnings: 52 | @cargo check 2>&1 | grep -e '^warning' | wc -l 53 | 54 | find-warnings: 55 | @cargo check 2>&1 | grep -A1 -e 'warning' | grep --only-matching -e '-->[^:]*' | sort | uniq -c | sort -nr 56 | 57 | @update-todo: 58 | ./etc/update-todo.sh 59 | 60 | @count-failures: 61 | ./etc/count-tests.sh 62 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | format_strings = false 2 | fn_single_line = true 3 | -------------------------------------------------------------------------------- /src/derives/arg_enum.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) , 2 | // Kevin Knapp (@kbknapp) , and 3 | // Andrew Hobden (@hoverbear) 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | use proc_macro2; 11 | // use quote; 12 | use syn; 13 | // use syn::punctuated; 14 | // use syn::token; 15 | 16 | pub fn derive_arg_enum(_ast: &syn::DeriveInput) -> proc_macro2::TokenStream { 17 | unimplemented!() 18 | 19 | // let from_str_block = impl_from_str(ast)?; 20 | // let variants_block = impl_variants(ast)?; 21 | 22 | // quote! { 23 | // #from_str_block 24 | // #variants_block 25 | // } 26 | } 27 | 28 | /* 29 | fn impl_from_str(ast: &syn::DeriveInput) -> proc_macro2::TokenStream { 30 | let ident = &ast.ident; 31 | let is_case_sensitive = ast.attrs.iter().any(|v| v.name() == "case_sensitive"); 32 | let variants = variants(ast)?; 33 | 34 | let strings = variants 35 | .iter() 36 | .map(|ref variant| String::from(variant.ident.as_ref())) 37 | .collect::>(); 38 | 39 | // All of these need to be iterators. 40 | let ident_slice = [ident.clone()]; 41 | let idents = ident_slice.iter().cycle(); 42 | 43 | let for_error_message = strings.clone(); 44 | 45 | let condition_function_slice = [match is_case_sensitive { 46 | true => quote! { str::eq }, 47 | false => quote! { ::std::ascii::AsciiExt::eq_ignore_ascii_case }, 48 | }]; 49 | let condition_function = condition_function_slice.iter().cycle(); 50 | 51 | Ok(quote! { 52 | impl ::std::str::FromStr for #ident { 53 | type Err = String; 54 | 55 | fn from_str(input: &str) -> ::std::result::Result { 56 | match input { 57 | #(val if #condition_function(val, #strings) => Ok(#idents::#variants),)* 58 | _ => Err({ 59 | let v = #for_error_message; 60 | format!("valid values: {}", 61 | v.join(" ,")) 62 | }), 63 | } 64 | } 65 | } 66 | }) 67 | } 68 | 69 | fn impl_variants(ast: &syn::DeriveInput) -> proc_macro2::TokenStream { 70 | let ident = &ast.ident; 71 | let variants = variants(ast)? 72 | .iter() 73 | .map(|ref variant| String::from(variant.ident.as_ref())) 74 | .collect::>(); 75 | let length = variants.len(); 76 | 77 | Ok(quote! { 78 | impl #ident { 79 | fn variants() -> [&'static str; #length] { 80 | #variants 81 | } 82 | } 83 | }) 84 | } 85 | 86 | fn variants(ast: &syn::DeriveInput) -> &punctuated::Punctuated { 87 | use syn::Data::*; 88 | 89 | match ast.data { 90 | Enum(ref data) => data.variants, 91 | _ => panic!("Only enums are supported for deriving the ArgEnum trait"), 92 | } 93 | } 94 | */ 95 | -------------------------------------------------------------------------------- /src/derives/from_argmatches.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) , 2 | // Kevin Knapp (@kbknapp) , and 3 | // Andrew Hobden (@hoverbear) 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | // 11 | // This work was derived from Structopt (https://github.com/TeXitoi/structopt) 12 | // commit#ea76fa1b1b273e65e3b0b1046643715b49bec51f which is licensed under the 13 | // MIT/Apache 2.0 license. 14 | use std::env; 15 | 16 | use proc_macro2; 17 | use syn; 18 | use syn::punctuated; 19 | use syn::spanned::Spanned as _; 20 | use syn::token; 21 | 22 | use super::{spanned::Sp, sub_type, Attrs, Kind, Name, ParserKind, Ty, DEFAULT_CASING}; 23 | 24 | pub fn derive_from_argmatches(input: &syn::DeriveInput) -> proc_macro2::TokenStream { 25 | use syn::Data::*; 26 | 27 | let struct_name = &input.ident; 28 | let inner_impl = match input.data { 29 | Struct(syn::DataStruct { 30 | fields: syn::Fields::Named(ref fields), 31 | .. 32 | }) => { 33 | let name = env::var("CARGO_PKG_NAME") 34 | .ok() 35 | .unwrap_or_else(String::default); 36 | 37 | let attrs = Attrs::from_struct( 38 | proc_macro2::Span::call_site(), 39 | &input.attrs, 40 | Name::Assigned(syn::LitStr::new(&name, proc_macro2::Span::call_site())), 41 | Sp::call_site(DEFAULT_CASING), 42 | ); 43 | 44 | gen_from_argmatches_impl_for_struct(struct_name, &fields.named, &attrs) 45 | } 46 | // Enum(ref e) => clap_for_enum_impl(struct_name, &e.variants, &input.attrs), 47 | _ => panic!("clap_derive only supports non-tuple structs"), // and enums"), 48 | }; 49 | 50 | quote!(#inner_impl) 51 | } 52 | 53 | pub fn gen_from_argmatches_impl_for_struct( 54 | name: &syn::Ident, 55 | fields: &punctuated::Punctuated, 56 | parent_attribute: &Attrs, 57 | ) -> proc_macro2::TokenStream { 58 | let from_argmatches_fn = gen_from_argmatches_fn_for_struct(name, fields, parent_attribute); 59 | 60 | quote! { 61 | impl ::clap::FromArgMatches for #name { 62 | #from_argmatches_fn 63 | } 64 | 65 | impl From<::clap::ArgMatches> for #name { 66 | fn from(m: ::clap::ArgMatches) -> Self { 67 | use ::clap::FromArgMatches; 68 | ::from_argmatches(&m) 69 | } 70 | } 71 | 72 | // @TODO impl TryFrom once stable 73 | } 74 | } 75 | 76 | pub fn gen_from_argmatches_fn_for_struct( 77 | struct_name: &syn::Ident, 78 | fields: &punctuated::Punctuated, 79 | parent_attribute: &Attrs, 80 | ) -> proc_macro2::TokenStream { 81 | let field_block = gen_constructor(fields, parent_attribute); 82 | 83 | quote! { 84 | fn from_argmatches(matches: &::clap::ArgMatches) -> Self { 85 | #struct_name #field_block 86 | } 87 | } 88 | } 89 | 90 | pub fn gen_constructor( 91 | fields: &punctuated::Punctuated, 92 | parent_attribute: &Attrs, 93 | ) -> proc_macro2::TokenStream { 94 | let fields = fields.iter().map(|field| { 95 | let attrs = Attrs::from_field(field, parent_attribute.casing()); 96 | let field_name = field.ident.as_ref().unwrap(); 97 | let kind = attrs.kind(); 98 | match &*attrs.kind() { 99 | Kind::Subcommand(ty) => { 100 | let subcmd_type = match (**ty, sub_type(&field.ty)) { 101 | (Ty::Option, Some(sub_type)) => sub_type, 102 | _ => &field.ty, 103 | }; 104 | let unwrapper = match **ty { 105 | Ty::Option => quote!(), 106 | _ => quote_spanned!( ty.span()=> .unwrap() ), 107 | }; 108 | quote_spanned! { kind.span()=> 109 | #field_name: <#subcmd_type>::from_subcommand(matches.subcommand())#unwrapper 110 | } 111 | } 112 | 113 | Kind::FlattenStruct => quote_spanned! { kind.span()=> 114 | #field_name: ::clap::FromArgMatches::from_argmatches(matches) 115 | }, 116 | 117 | Kind::Skip(val) => match val { 118 | None => quote_spanned!(kind.span()=> #field_name: Default::default()), 119 | Some(val) => quote_spanned!(kind.span()=> #field_name: (#val).into()), 120 | }, 121 | 122 | Kind::Arg(ty) => { 123 | use self::ParserKind::*; 124 | 125 | let parser = attrs.parser(); 126 | let func = &parser.func; 127 | let span = parser.kind.span(); 128 | let (value_of, values_of, parse) = match *parser.kind { 129 | FromStr => ( 130 | quote_spanned!(span=> value_of), 131 | quote_spanned!(span=> values_of), 132 | func.clone(), 133 | ), 134 | TryFromStr => ( 135 | quote_spanned!(span=> value_of), 136 | quote_spanned!(span=> values_of), 137 | quote_spanned!(func.span()=> |s| #func(s).unwrap()), 138 | ), 139 | FromOsStr => ( 140 | quote_spanned!(span=> value_of_os), 141 | quote_spanned!(span=> values_of_os), 142 | func.clone(), 143 | ), 144 | TryFromOsStr => ( 145 | quote_spanned!(span=> value_of_os), 146 | quote_spanned!(span=> values_of_os), 147 | quote_spanned!(func.span()=> |s| #func(s).unwrap()), 148 | ), 149 | FromOccurrences => ( 150 | quote_spanned!(span=> occurrences_of), 151 | quote!(), 152 | func.clone(), 153 | ), 154 | FromFlag => (quote!(), quote!(), func.clone()), 155 | }; 156 | 157 | let flag = *attrs.parser().kind == ParserKind::FromFlag; 158 | let occurrences = *attrs.parser().kind == ParserKind::FromOccurrences; 159 | let name = attrs.cased_name(); 160 | let field_value = match **ty { 161 | Ty::Bool => quote_spanned! { ty.span()=> 162 | matches.is_present(#name) 163 | }, 164 | 165 | Ty::Option => quote_spanned! { ty.span()=> 166 | matches.#value_of(#name) 167 | .map(#parse) 168 | }, 169 | 170 | Ty::OptionOption => quote_spanned! { ty.span()=> 171 | if matches.is_present(#name) { 172 | Some(matches.#value_of(#name).map(#parse)) 173 | } else { 174 | None 175 | } 176 | }, 177 | 178 | Ty::OptionVec => quote_spanned! { ty.span()=> 179 | if matches.is_present(#name) { 180 | Some(matches.#values_of(#name) 181 | .map(|v| v.map(#parse).collect()) 182 | .unwrap_or_else(Vec::new)) 183 | } else { 184 | None 185 | } 186 | }, 187 | 188 | Ty::Vec => quote_spanned! { ty.span()=> 189 | matches.#values_of(#name) 190 | .map(|v| v.map(#parse).collect()) 191 | .unwrap_or_else(Vec::new) 192 | }, 193 | 194 | Ty::Other if occurrences => quote_spanned! { ty.span()=> 195 | #parse(matches.#value_of(#name)) 196 | }, 197 | 198 | Ty::Other if flag => quote_spanned! { ty.span()=> 199 | #parse(matches.is_present(#name)) 200 | }, 201 | 202 | Ty::Other => quote_spanned! { ty.span()=> 203 | matches.#value_of(#name) 204 | .map(#parse) 205 | .unwrap() 206 | }, 207 | }; 208 | 209 | quote_spanned!(field.span()=> #field_name: #field_value ) 210 | } 211 | } 212 | }); 213 | 214 | quote! {{ 215 | #( #fields ),* 216 | }} 217 | } 218 | 219 | pub fn gen_from_argmatches_impl_for_enum(name: &syn::Ident) -> proc_macro2::TokenStream { 220 | quote! { 221 | impl ::clap::FromArgMatches for #name { 222 | fn from_argmatches(matches: &::clap::ArgMatches) -> Self { 223 | <#name>::from_subcommand(matches.subcommand()) 224 | .unwrap() 225 | } 226 | } 227 | 228 | impl From<::clap::ArgMatches> for #name { 229 | fn from(m: ::clap::ArgMatches) -> Self { 230 | use ::clap::FromArgMatches; 231 | ::from_argmatches(&m) 232 | } 233 | } 234 | 235 | // @TODO: impl TryFrom once stable 236 | } 237 | } 238 | -------------------------------------------------------------------------------- /src/derives/into_app.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) , 2 | // Kevin Knapp (@kbknapp) , and 3 | // Andrew Hobden (@hoverbear) 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | // 11 | // This work was derived from Structopt (https://github.com/TeXitoi/structopt) 12 | // commit#ea76fa1b1b273e65e3b0b1046643715b49bec51f which is licensed under the 13 | // MIT/Apache 2.0 license. 14 | use std::env; 15 | 16 | use proc_macro2; 17 | use syn; 18 | 19 | use super::{spanned::Sp, Attrs, GenOutput, Name, DEFAULT_CASING}; 20 | 21 | pub fn derive_into_app(input: &syn::DeriveInput) -> proc_macro2::TokenStream { 22 | use syn::Data::*; 23 | 24 | let struct_name = &input.ident; 25 | let inner_impl = match input.data { 26 | Struct(syn::DataStruct { .. }) => { 27 | gen_into_app_impl_for_struct(struct_name, &input.attrs).tokens 28 | } 29 | // @TODO impl into_app for enums? 30 | // Enum(ref e) => clap_for_enum_impl(struct_name, &e.variants, &input.attrs), 31 | _ => panic!("clap_derive only supports non-tuple structs"), // and enums"), 32 | }; 33 | 34 | quote!(#inner_impl) 35 | } 36 | 37 | pub fn gen_into_app_impl_for_struct(name: &syn::Ident, attrs: &[syn::Attribute]) -> GenOutput { 38 | let into_app_fn = gen_into_app_fn_for_struct(attrs); 39 | let into_app_fn_tokens = into_app_fn.tokens; 40 | 41 | let tokens = quote! { 42 | impl ::clap::IntoApp for #name { 43 | #into_app_fn_tokens 44 | } 45 | 46 | impl<'b> Into<::clap::App<'b>> for #name { 47 | fn into(self) -> ::clap::App<'b> { 48 | use ::clap::IntoApp; 49 | <#name as ::clap::IntoApp>::into_app() 50 | } 51 | } 52 | }; 53 | 54 | GenOutput { 55 | tokens, 56 | attrs: into_app_fn.attrs, 57 | } 58 | } 59 | 60 | pub fn gen_into_app_fn_for_struct(struct_attrs: &[syn::Attribute]) -> GenOutput { 61 | let gen = gen_app_builder(struct_attrs); 62 | let app_tokens = gen.tokens; 63 | 64 | let tokens = quote! { 65 | fn into_app<'b>() -> ::clap::App<'b> { 66 | Self::augment_app(#app_tokens) 67 | } 68 | }; 69 | 70 | GenOutput { 71 | tokens, 72 | attrs: gen.attrs, 73 | } 74 | } 75 | 76 | pub fn gen_app_builder(attrs: &[syn::Attribute]) -> GenOutput { 77 | let name = env::var("CARGO_PKG_NAME").ok().unwrap_or_default(); 78 | 79 | let attrs = Attrs::from_struct( 80 | proc_macro2::Span::call_site(), 81 | attrs, 82 | Name::Assigned(syn::LitStr::new(&name, proc_macro2::Span::call_site())), 83 | Sp::call_site(DEFAULT_CASING), 84 | ); 85 | let tokens = { 86 | let name = attrs.cased_name(); 87 | quote!(::clap::App::new(#name)) 88 | }; 89 | 90 | GenOutput { tokens, attrs } 91 | } 92 | 93 | pub fn gen_into_app_impl_for_enum(name: &syn::Ident, attrs: &[syn::Attribute]) -> GenOutput { 94 | let into_app_fn = gen_into_app_fn_for_enum(attrs); 95 | let into_app_fn_tokens = into_app_fn.tokens; 96 | 97 | let tokens = quote! { 98 | impl ::clap::IntoApp for #name { 99 | #into_app_fn_tokens 100 | } 101 | 102 | impl<'b> Into<::clap::App<'b>> for #name { 103 | fn into(self) -> ::clap::App<'b> { 104 | use ::clap::IntoApp; 105 | <#name as ::clap::IntoApp>::into_app() 106 | } 107 | } 108 | }; 109 | 110 | GenOutput { 111 | tokens, 112 | attrs: into_app_fn.attrs, 113 | } 114 | } 115 | 116 | pub fn gen_into_app_fn_for_enum(enum_attrs: &[syn::Attribute]) -> GenOutput { 117 | let gen = gen_app_builder(enum_attrs); 118 | let app_tokens = gen.tokens; 119 | 120 | let tokens = quote! { 121 | fn into_app<'b>() -> ::clap::App<'b> { 122 | let app = #app_tokens 123 | .setting(::clap::AppSettings::SubcommandRequiredElseHelp); 124 | Self::augment_app(app) 125 | } 126 | }; 127 | 128 | GenOutput { 129 | tokens, 130 | attrs: gen.attrs, 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /src/derives/mod.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) , 2 | // Kevin Knapp (@kbknapp) , and 3 | // Andrew Hobden (@hoverbear) 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | // 11 | // This work was derived from Structopt (https://github.com/TeXitoi/structopt) 12 | // commit#ea76fa1b1b273e65e3b0b1046643715b49bec51f which is licensed under the 13 | // MIT/Apache 2.0 license. 14 | use syn; 15 | 16 | pub mod arg_enum; 17 | pub mod attrs; 18 | pub mod parse; 19 | pub mod spanned; 20 | pub mod ty; 21 | mod clap; 22 | mod from_argmatches; 23 | mod into_app; 24 | 25 | pub use self::arg_enum::derive_arg_enum; 26 | pub use self::attrs::{Attrs, Kind, Name, Parser, ParserKind, CasingStyle, GenOutput, DEFAULT_CASING}; 27 | pub use self::ty::{sub_type, Ty}; 28 | pub use self::clap::derive_clap; 29 | pub use self::from_argmatches::derive_from_argmatches; 30 | pub use self::into_app::derive_into_app; 31 | -------------------------------------------------------------------------------- /src/derives/parse.rs: -------------------------------------------------------------------------------- 1 | use std::iter::FromIterator; 2 | 3 | use proc_macro2::TokenStream; 4 | use proc_macro_error::{abort, ResultExt}; 5 | use syn::{ 6 | self, parenthesized, 7 | parse::{Parse, ParseBuffer, ParseStream}, 8 | parse2, 9 | punctuated::Punctuated, 10 | spanned::Spanned, 11 | Attribute, Expr, ExprLit, Ident, Lit, LitBool, LitStr, Token, 12 | }; 13 | 14 | pub struct ClapAttributes { 15 | pub paren_token: syn::token::Paren, 16 | pub attrs: Punctuated, 17 | } 18 | 19 | impl Parse for ClapAttributes { 20 | fn parse(input: ParseStream) -> syn::Result { 21 | let content; 22 | let paren_token = parenthesized!(content in input); 23 | let attrs = content.parse_terminated(ClapAttr::parse)?; 24 | 25 | Ok(ClapAttributes { paren_token, attrs }) 26 | } 27 | } 28 | 29 | pub enum ClapAttr { 30 | // single-identifier attributes 31 | Short(Ident), 32 | Long(Ident), 33 | Flatten(Ident), 34 | Subcommand(Ident), 35 | NoVersion(Ident), 36 | 37 | // ident [= "string literal"] 38 | About(Ident, Option), 39 | Author(Ident, Option), 40 | 41 | // ident = "string literal" 42 | Version(Ident, LitStr), 43 | RenameAll(Ident, LitStr), 44 | NameLitStr(Ident, LitStr), 45 | 46 | // parse(parser_kind [= parser_func]) 47 | Parse(Ident, ParserSpec), 48 | 49 | // ident [= arbitrary_expr] 50 | Skip(Ident, Option), 51 | 52 | // ident = arbitrary_expr 53 | NameExpr(Ident, Expr), 54 | 55 | // ident(arbitrary_expr,*) 56 | MethodCall(Ident, Vec), 57 | } 58 | 59 | impl Parse for ClapAttr { 60 | fn parse(input: ParseStream) -> syn::Result { 61 | use self::ClapAttr::*; 62 | 63 | let name: Ident = input.parse()?; 64 | let name_str = name.to_string(); 65 | 66 | if input.peek(Token![=]) { 67 | // `name = value` attributes. 68 | let assign_token = input.parse::()?; // skip '=' 69 | 70 | if input.peek(LitStr) { 71 | let lit: LitStr = input.parse()?; 72 | let lit_str = lit.value(); 73 | 74 | let check_empty_lit = |s| { 75 | if lit_str.is_empty() { 76 | abort!( 77 | lit.span(), 78 | "`#[clap({} = \"\")` is deprecated, \ 79 | now it's default behavior", 80 | s 81 | ); 82 | } 83 | }; 84 | 85 | match &*name_str.to_string() { 86 | "rename_all" => Ok(RenameAll(name, lit)), 87 | 88 | "version" => { 89 | check_empty_lit("version"); 90 | Ok(Version(name, lit)) 91 | } 92 | 93 | "author" => { 94 | check_empty_lit("author"); 95 | Ok(Author(name, Some(lit))) 96 | } 97 | 98 | "about" => { 99 | check_empty_lit("about"); 100 | Ok(About(name, Some(lit))) 101 | } 102 | 103 | "skip" => { 104 | let expr = ExprLit { 105 | attrs: vec![], 106 | lit: Lit::Str(lit), 107 | }; 108 | let expr = Expr::Lit(expr); 109 | Ok(Skip(name, Some(expr))) 110 | } 111 | 112 | _ => Ok(NameLitStr(name, lit)), 113 | } 114 | } else { 115 | match input.parse::() { 116 | Ok(expr) => { 117 | if name_str == "skip" { 118 | Ok(Skip(name, Some(expr))) 119 | } else { 120 | Ok(NameExpr(name, expr)) 121 | } 122 | } 123 | 124 | Err(_) => abort! { 125 | assign_token.span(), 126 | "expected `string literal` or `expression` after `=`" 127 | }, 128 | } 129 | } 130 | } else if input.peek(syn::token::Paren) { 131 | // `name(...)` attributes. 132 | let nested; 133 | parenthesized!(nested in input); 134 | 135 | match name_str.as_ref() { 136 | "parse" => { 137 | let parser_specs: Punctuated = 138 | nested.parse_terminated(ParserSpec::parse)?; 139 | 140 | if parser_specs.len() == 1 { 141 | Ok(Parse(name, parser_specs[0].clone())) 142 | } else { 143 | abort!(name.span(), "parse must have exactly one argument") 144 | } 145 | } 146 | 147 | "raw" => match nested.parse::() { 148 | Ok(bool_token) => { 149 | let expr = ExprLit { 150 | attrs: vec![], 151 | lit: Lit::Bool(bool_token), 152 | }; 153 | let expr = Expr::Lit(expr); 154 | Ok(MethodCall(name, vec![expr])) 155 | } 156 | 157 | Err(_) => { 158 | abort!(name.span(), 159 | "`#[clap(raw(...))` attributes are removed, \ 160 | they are replaced with raw methods"; 161 | help = "if you meant to call `clap::Arg::raw()` method \ 162 | you should use bool literal, like `raw(true)` or `raw(false)`"; 163 | note = raw_method_suggestion(nested); 164 | ); 165 | } 166 | }, 167 | 168 | _ => { 169 | let method_args: Punctuated<_, Token![,]> = 170 | nested.parse_terminated(Expr::parse)?; 171 | Ok(MethodCall(name, Vec::from_iter(method_args))) 172 | } 173 | } 174 | } else { 175 | // Attributes represented with a sole identifier. 176 | match name_str.as_ref() { 177 | "long" => Ok(Long(name)), 178 | "short" => Ok(Short(name)), 179 | "flatten" => Ok(Flatten(name)), 180 | "subcommand" => Ok(Subcommand(name)), 181 | "no_version" => Ok(NoVersion(name)), 182 | 183 | "about" => (Ok(About(name, None))), 184 | "author" => (Ok(Author(name, None))), 185 | 186 | "skip" => Ok(Skip(name, None)), 187 | 188 | "version" => abort!( 189 | name.span(), 190 | "#[clap(version)] is invalid attribute, \ 191 | clap_derive inherits version from Cargo.toml by default, \ 192 | no attribute needed" 193 | ), 194 | 195 | _ => abort!(name.span(), "unexpected attribute: {}", name_str), 196 | } 197 | } 198 | } 199 | } 200 | 201 | #[derive(Clone)] 202 | pub struct ParserSpec { 203 | pub kind: Ident, 204 | pub eq_token: Option, 205 | pub parse_func: Option, 206 | } 207 | 208 | impl Parse for ParserSpec { 209 | fn parse(input: ParseStream<'_>) -> syn::Result { 210 | let kind = input 211 | .parse() 212 | .map_err(|_| input.error("parser specification must start with identifier"))?; 213 | let eq_token = input.parse()?; 214 | let parse_func = match eq_token { 215 | None => None, 216 | Some(_) => Some(input.parse()?), 217 | }; 218 | Ok(ParserSpec { 219 | kind, 220 | eq_token, 221 | parse_func, 222 | }) 223 | } 224 | } 225 | 226 | fn raw_method_suggestion(ts: ParseBuffer) -> String { 227 | let do_parse = move || -> Result<(Ident, TokenStream), syn::Error> { 228 | let name = ts.parse()?; 229 | let _eq: Token![=] = ts.parse()?; 230 | let val: LitStr = ts.parse()?; 231 | Ok((name, syn::parse_str(&val.value())?)) 232 | }; 233 | if let Ok((name, val)) = do_parse() { 234 | let val = val.to_string().replace(" ", "").replace(",", ", "); 235 | format!( 236 | "if you need to call `clap::Arg/App::{}` method you \ 237 | can do it like this: #[clap({}({}))]", 238 | name, name, val 239 | ) 240 | } else { 241 | "if you need to call some method from `clap::Arg/App` \ 242 | you should use raw method, see \ 243 | https://docs.rs/structopt/0.3/structopt/#raw-methods" 244 | .into() 245 | } 246 | } 247 | 248 | pub fn parse_clap_attributes(all_attrs: &[Attribute]) -> Vec { 249 | all_attrs 250 | .iter() 251 | .filter(|attr| attr.path.is_ident("clap")) 252 | .flat_map(|attr| { 253 | let attrs: ClapAttributes = parse2(attr.tokens.clone()) 254 | .map_err(|e| match &*e.to_string() { 255 | // this error message is misleading and points to Span::call_site() 256 | // so we patch it with something meaningful 257 | "unexpected end of input, expected parentheses" => { 258 | let span = attr.path.span(); 259 | let patch_msg = "expected parentheses after `clap`"; 260 | syn::Error::new(span, patch_msg) 261 | } 262 | _ => e, 263 | }) 264 | .unwrap_or_abort(); 265 | attrs.attrs 266 | }) 267 | .collect() 268 | } 269 | -------------------------------------------------------------------------------- /src/derives/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 Sp { 31 | pub fn as_ident(&self) -> Ident { 32 | Ident::new(&self.to_string(), self.span) 33 | } 34 | 35 | pub fn as_lit(&self) -> LitStr { 36 | LitStr::new(&self.to_string(), self.span) 37 | } 38 | } 39 | 40 | impl Deref for Sp { 41 | type Target = T; 42 | 43 | fn deref(&self) -> &T { 44 | &self.val 45 | } 46 | } 47 | 48 | impl DerefMut for Sp { 49 | fn deref_mut(&mut self) -> &mut T { 50 | &mut self.val 51 | } 52 | } 53 | 54 | impl From for Sp { 55 | fn from(ident: Ident) -> Self { 56 | Sp { 57 | val: ident.to_string(), 58 | span: ident.span(), 59 | } 60 | } 61 | } 62 | 63 | impl From for Sp { 64 | fn from(lit: LitStr) -> Self { 65 | Sp { 66 | val: lit.value(), 67 | span: lit.span(), 68 | } 69 | } 70 | } 71 | 72 | impl<'a> From> for Sp { 73 | fn from(sp: Sp<&'a str>) -> Self { 74 | Sp::new(sp.val.into(), sp.span) 75 | } 76 | } 77 | 78 | impl PartialEq for Sp { 79 | fn eq(&self, other: &Sp) -> bool { 80 | self.val == other.val 81 | } 82 | } 83 | 84 | impl> AsRef for Sp { 85 | fn as_ref(&self) -> &str { 86 | self.val.as_ref() 87 | } 88 | } 89 | 90 | impl ToTokens for Sp { 91 | fn to_tokens(&self, stream: &mut TokenStream) { 92 | // this is the simplest way out of correct ones to change span on 93 | // arbitrary token tree I can come up with 94 | let tt = self.val.to_token_stream().into_iter().map(|mut tt| { 95 | tt.set_span(self.span.clone()); 96 | tt 97 | }); 98 | 99 | stream.extend(tt); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/derives/ty.rs: -------------------------------------------------------------------------------- 1 | //! Special types handling 2 | 3 | use super::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 self::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 | only_last_segment(ty) 67 | .filter(|segment| f(segment)) 68 | .and_then(|segment| { 69 | if let AngleBracketed(args) = &segment.arguments { 70 | only_one(args.args.iter()).and_then(|genneric| { 71 | if let GenericArgument::Type(ty) = genneric { 72 | Some(ty) 73 | } else { 74 | None 75 | } 76 | }) 77 | } else { 78 | None 79 | } 80 | }) 81 | } 82 | 83 | fn subty_if_name<'a>(ty: &'a syn::Type, name: &str) -> Option<&'a syn::Type> { 84 | subty_if(ty, |seg| seg.ident == name) 85 | } 86 | 87 | fn is_simple_ty(ty: &syn::Type, name: &str) -> bool { 88 | only_last_segment(ty) 89 | .map(|segment| { 90 | if let PathArguments::None = segment.arguments { 91 | segment.ident == name 92 | } else { 93 | false 94 | } 95 | }) 96 | .unwrap_or(false) 97 | } 98 | 99 | fn is_generic_ty(ty: &syn::Type, name: &str) -> bool { 100 | subty_if_name(ty, name).is_some() 101 | } 102 | 103 | fn only_one(mut iter: I) -> Option 104 | where 105 | I: Iterator, 106 | { 107 | iter.next().filter(|_| iter.next().is_none()) 108 | } 109 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) , 2 | // Kevin Knapp (@kbknapp) , and 3 | // Andrew Hobden (@hoverbear) 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | // 11 | // This work was derived from Structopt (https://github.com/TeXitoi/structopt) 12 | // commit#ea76fa1b1b273e65e3b0b1046643715b49bec51f which is licensed under the 13 | // MIT/Apache 2.0 license. 14 | 15 | //! This crate is custom derive for clap. It should not be used 16 | //! directly. See [clap documentation](https://docs.rs/clap) 17 | //! for the usage of `#[derive(Clap)]`. 18 | #![recursion_limit = "256"] 19 | 20 | extern crate proc_macro; 21 | extern crate syn; 22 | #[macro_use] 23 | extern crate quote; 24 | extern crate heck; 25 | extern crate proc_macro2; 26 | extern crate proc_macro_error; 27 | 28 | use proc_macro_error::proc_macro_error; 29 | 30 | mod derives; 31 | 32 | // /// It is required to have this seperate and specificly defined. 33 | // #[proc_macro_derive(ArgEnum, attributes(case_sensitive))] 34 | // pub fn arg_enum(input: proc_macro::TokenStream) -> proc_macro::TokenStream { 35 | // let input: syn::DeriveInput = syn::parse(input).unwrap(); 36 | // derives::derive_arg_enum(&input).into() 37 | // } 38 | 39 | /// Generates the `Clap` impl. 40 | #[proc_macro_derive(Clap, attributes(clap))] 41 | #[proc_macro_error] 42 | pub fn clap(input: proc_macro::TokenStream) -> proc_macro::TokenStream { 43 | let input: syn::DeriveInput = syn::parse(input).unwrap(); 44 | derives::derive_clap(&input).into() 45 | } 46 | 47 | /// Generates the `IntoApp` impl. 48 | #[proc_macro_derive(IntoApp, attributes(clap))] 49 | #[proc_macro_error] 50 | pub fn into_app(input: proc_macro::TokenStream) -> proc_macro::TokenStream { 51 | let input: syn::DeriveInput = syn::parse(input).unwrap(); 52 | derives::derive_into_app(&input).into() 53 | } 54 | 55 | /// Generates the `FromArgMatches` impl. 56 | #[proc_macro_derive(FromArgMatches)] 57 | #[proc_macro_error] 58 | pub fn from_argmatches(input: proc_macro::TokenStream) -> proc_macro::TokenStream { 59 | let input: syn::DeriveInput = syn::parse(input).unwrap(); 60 | derives::derive_from_argmatches(&input).into() 61 | } 62 | -------------------------------------------------------------------------------- /tests/arg_enum_basic.rs: -------------------------------------------------------------------------------- 1 | // // Copyright 2018 Guillaume Pinot (@TeXitoi) , 2 | // // Kevin Knapp (@kbknapp) , and 3 | // // Andrew Hobden (@hoverbear) 4 | // // 5 | // // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // // , at your 8 | // // option. This file may not be copied, modified, or distributed 9 | // // except according to those terms. 10 | // #[macro_use] 11 | // extern crate clap; 12 | // #[macro_use] 13 | // extern crate clap_derive; 14 | 15 | // use clap::{App, Arg}; 16 | 17 | // #[derive(ArgEnum, Debug, PartialEq)] 18 | // enum ArgChoice { 19 | // Foo, 20 | // Bar, 21 | // Baz, 22 | // } 23 | 24 | // #[test] 25 | // fn when_lowercase() { 26 | // let matches = App::new(env!("CARGO_PKG_NAME")) 27 | // .arg( 28 | // Arg::with_name("arg") 29 | // .required(true) 30 | // .takes_value(true) 31 | // .possible_values(&ArgChoice::variants()), 32 | // ) 33 | // .try_get_matches_from(vec!["", "foo"]) 34 | // .unwrap(); 35 | // let t = value_t!(matches.value_of("arg"), ArgChoice); 36 | // assert!(t.is_ok()); 37 | // assert_eq!(t.unwrap(), ArgChoice::Foo); 38 | // } 39 | 40 | // #[test] 41 | // fn when_capitalized() { 42 | // let matches = App::new(env!("CARGO_PKG_NAME")) 43 | // .arg( 44 | // Arg::with_name("arg") 45 | // .required(true) 46 | // .takes_value(true) 47 | // .possible_values(&ArgChoice::variants()), 48 | // ) 49 | // .try_get_matches_from(vec!["", "Foo"]) 50 | // .unwrap(); 51 | // let t = value_t!(matches.value_of("arg"), ArgChoice); 52 | // assert!(t.is_ok()); 53 | // assert_eq!(t.unwrap(), ArgChoice::Foo); 54 | // } 55 | -------------------------------------------------------------------------------- /tests/arg_enum_case_sensitive.rs: -------------------------------------------------------------------------------- 1 | // // Copyright 2018 Guillaume Pinot (@TeXitoi) , 2 | // // Kevin Knapp (@kbknapp) , and 3 | // // Andrew Hobden (@hoverbear) 4 | // // 5 | // // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // // , at your 8 | // // option. This file may not be copied, modified, or distributed 9 | // // except according to those terms. 10 | // #[macro_use] 11 | // extern crate clap; 12 | 13 | // use clap::{App, Arg, ArgEnum}; 14 | 15 | // #[derive(ArgEnum, Debug, PartialEq)] 16 | // #[case_sensitive] 17 | // enum ArgChoice { 18 | // Foo, 19 | // Bar, 20 | // Baz, 21 | // } 22 | 23 | // #[test] 24 | // fn when_lowercase() { 25 | // let matches = App::new(env!("CARGO_PKG_NAME")) 26 | // .arg( 27 | // Arg::with_name("arg") 28 | // .required(true) 29 | // .takes_value(true) 30 | // .possible_values(&ArgChoice::variants()), 31 | // ) 32 | // .try_get_matches_from(vec!["", "foo"]); // We expect this to fail. 33 | // assert!(matches.is_err()); 34 | // assert_eq!(matches.unwrap_err().kind, clap::ErrorKind::InvalidValue); 35 | // } 36 | 37 | // #[test] 38 | // fn when_capitalized() { 39 | // let matches = App::new(env!("CARGO_PKG_NAME")) 40 | // .arg( 41 | // Arg::with_name("arg") 42 | // .required(true) 43 | // .takes_value(true) 44 | // .possible_values(&ArgChoice::variants()), 45 | // ) 46 | // .try_get_matches_from(vec!["", "Foo"]) 47 | // .unwrap(); 48 | // let t = value_t!(matches.value_of("arg"), ArgChoice); 49 | // assert!(t.is_ok()); 50 | // assert_eq!(t.unwrap(), ArgChoice::Foo); 51 | // } 52 | -------------------------------------------------------------------------------- /tests/argument_naming.rs: -------------------------------------------------------------------------------- 1 | use clap::Clap; 2 | 3 | #[test] 4 | fn test_single_word_enum_variant_is_default_renamed_into_kebab_case() { 5 | #[derive(Clap, Debug, PartialEq)] 6 | enum Opt { 7 | Command { foo: u32 }, 8 | } 9 | 10 | assert_eq!( 11 | Opt::Command { foo: 0 }, 12 | Opt::parse_from(&["test", "command", "0"]) 13 | ); 14 | } 15 | 16 | #[test] 17 | fn test_multi_word_enum_variant_is_renamed() { 18 | #[derive(Clap, Debug, PartialEq)] 19 | enum Opt { 20 | FirstCommand { foo: u32 }, 21 | } 22 | 23 | assert_eq!( 24 | Opt::FirstCommand { foo: 0 }, 25 | Opt::parse_from(&["test", "first-command", "0"]) 26 | ); 27 | } 28 | 29 | #[test] 30 | fn test_standalone_long_generates_kebab_case() { 31 | #[derive(Clap, Debug, PartialEq)] 32 | #[allow(non_snake_case)] 33 | struct Opt { 34 | #[clap(long)] 35 | FOO_OPTION: bool, 36 | } 37 | 38 | assert_eq!( 39 | Opt { FOO_OPTION: true }, 40 | Opt::parse_from(&["test", "--foo-option"]) 41 | ); 42 | } 43 | 44 | #[test] 45 | fn test_custom_long_overwrites_default_name() { 46 | #[derive(Clap, Debug, PartialEq)] 47 | struct Opt { 48 | #[clap(long = "foo")] 49 | foo_option: bool, 50 | } 51 | 52 | assert_eq!( 53 | Opt { foo_option: true }, 54 | Opt::parse_from(&["test", "--foo"]) 55 | ); 56 | } 57 | 58 | #[test] 59 | fn test_standalone_long_uses_previous_defined_custom_name() { 60 | #[derive(Clap, Debug, PartialEq)] 61 | struct Opt { 62 | #[clap(name = "foo", long)] 63 | foo_option: bool, 64 | } 65 | 66 | assert_eq!( 67 | Opt { foo_option: true }, 68 | Opt::parse_from(&["test", "--foo"]) 69 | ); 70 | } 71 | 72 | #[test] 73 | fn test_standalone_long_ignores_afterwards_defined_custom_name() { 74 | #[derive(Clap, Debug, PartialEq)] 75 | struct Opt { 76 | #[clap(long, name = "foo")] 77 | foo_option: bool, 78 | } 79 | 80 | assert_eq!( 81 | Opt { foo_option: true }, 82 | Opt::parse_from(&["test", "--foo-option"]) 83 | ); 84 | } 85 | 86 | #[test] 87 | fn test_standalone_short_generates_kebab_case() { 88 | #[derive(Clap, Debug, PartialEq)] 89 | #[allow(non_snake_case)] 90 | struct Opt { 91 | #[clap(short)] 92 | FOO_OPTION: bool, 93 | } 94 | 95 | assert_eq!(Opt { FOO_OPTION: true }, Opt::parse_from(&["test", "-f"])); 96 | } 97 | 98 | #[test] 99 | fn test_custom_short_overwrites_default_name() { 100 | #[derive(Clap, Debug, PartialEq)] 101 | struct Opt { 102 | #[clap(short = "o")] 103 | foo_option: bool, 104 | } 105 | 106 | assert_eq!(Opt { foo_option: true }, Opt::parse_from(&["test", "-o"])); 107 | } 108 | 109 | #[test] 110 | fn test_standalone_short_uses_previous_defined_custom_name() { 111 | #[derive(Clap, Debug, PartialEq)] 112 | struct Opt { 113 | #[clap(name = "option", short)] 114 | foo_option: bool, 115 | } 116 | 117 | assert_eq!(Opt { foo_option: true }, Opt::parse_from(&["test", "-o"])); 118 | } 119 | 120 | #[test] 121 | fn test_standalone_short_ignores_afterwards_defined_custom_name() { 122 | #[derive(Clap, Debug, PartialEq)] 123 | struct Opt { 124 | #[clap(short, name = "option")] 125 | foo_option: bool, 126 | } 127 | 128 | assert_eq!(Opt { foo_option: true }, Opt::parse_from(&["test", "-f"])); 129 | } 130 | 131 | #[test] 132 | fn test_standalone_long_uses_previous_defined_casing() { 133 | #[derive(Clap, Debug, PartialEq)] 134 | struct Opt { 135 | #[clap(rename_all = "screaming_snake", long)] 136 | foo_option: bool, 137 | } 138 | 139 | assert_eq!( 140 | Opt { foo_option: true }, 141 | Opt::parse_from(&["test", "--FOO_OPTION"]) 142 | ); 143 | } 144 | 145 | #[test] 146 | fn test_standalone_short_uses_previous_defined_casing() { 147 | #[derive(Clap, Debug, PartialEq)] 148 | struct Opt { 149 | #[clap(rename_all = "screaming_snake", short)] 150 | foo_option: bool, 151 | } 152 | 153 | assert_eq!(Opt { foo_option: true }, Opt::parse_from(&["test", "-F"])); 154 | } 155 | 156 | #[test] 157 | fn test_standalone_long_works_with_verbatim_casing() { 158 | #[derive(Clap, Debug, PartialEq)] 159 | #[allow(non_snake_case)] 160 | struct Opt { 161 | #[clap(rename_all = "verbatim", long)] 162 | _fOO_oPtiON: bool, 163 | } 164 | 165 | assert_eq!( 166 | Opt { _fOO_oPtiON: true }, 167 | Opt::parse_from(&["test", "--_fOO_oPtiON"]) 168 | ); 169 | } 170 | 171 | #[test] 172 | fn test_standalone_short_works_with_verbatim_casing() { 173 | #[derive(Clap, Debug, PartialEq)] 174 | struct Opt { 175 | #[clap(rename_all = "verbatim", short)] 176 | _foo: bool, 177 | } 178 | 179 | assert_eq!(Opt { _foo: true }, Opt::parse_from(&["test", "-_"])); 180 | } 181 | 182 | #[test] 183 | fn test_rename_all_is_propagated_from_struct_to_fields() { 184 | #[derive(Clap, Debug, PartialEq)] 185 | #[clap(rename_all = "screaming_snake")] 186 | struct Opt { 187 | #[clap(long)] 188 | foo: bool, 189 | } 190 | 191 | assert_eq!(Opt { foo: true }, Opt::parse_from(&["test", "--FOO"])); 192 | } 193 | 194 | #[test] 195 | fn test_rename_all_is_not_propagated_from_struct_into_flattened() { 196 | #[derive(Clap, Debug, PartialEq)] 197 | #[clap(rename_all = "screaming_snake")] 198 | struct Opt { 199 | #[clap(flatten)] 200 | foo: Foo, 201 | } 202 | 203 | #[derive(Clap, Debug, PartialEq)] 204 | struct Foo { 205 | #[clap(long)] 206 | foo: bool, 207 | } 208 | 209 | assert_eq!( 210 | Opt { 211 | foo: Foo { foo: true } 212 | }, 213 | Opt::parse_from(&["test", "--foo"]) 214 | ); 215 | } 216 | 217 | #[test] 218 | fn test_rename_all_is_not_propagated_from_struct_into_subcommand() { 219 | #[derive(Clap, Debug, PartialEq)] 220 | #[clap(rename_all = "screaming_snake")] 221 | struct Opt { 222 | #[clap(subcommand)] 223 | foo: Foo, 224 | } 225 | 226 | #[derive(Clap, Debug, PartialEq)] 227 | enum Foo { 228 | Command { 229 | #[clap(long)] 230 | foo: bool, 231 | }, 232 | } 233 | 234 | assert_eq!( 235 | Opt { 236 | foo: Foo::Command { foo: true } 237 | }, 238 | Opt::parse_from(&["test", "command", "--foo"]) 239 | ); 240 | } 241 | 242 | #[test] 243 | fn test_rename_all_is_propagated_from_enum_to_variants_and_their_fields() { 244 | #[derive(Clap, Debug, PartialEq)] 245 | #[clap(rename_all = "screaming_snake")] 246 | enum Opt { 247 | FirstVariant, 248 | SecondVariant { 249 | #[clap(long)] 250 | foo: bool, 251 | }, 252 | } 253 | 254 | assert_eq!( 255 | Opt::FirstVariant, 256 | Opt::parse_from(&["test", "FIRST_VARIANT"]) 257 | ); 258 | 259 | assert_eq!( 260 | Opt::SecondVariant { foo: true }, 261 | Opt::parse_from(&["test", "SECOND_VARIANT", "--FOO"]) 262 | ); 263 | } 264 | 265 | #[test] 266 | fn test_rename_all_is_propagation_can_be_overridden() { 267 | #[derive(Clap, Debug, PartialEq)] 268 | #[clap(rename_all = "screaming_snake")] 269 | enum Opt { 270 | #[clap(rename_all = "kebab_case")] 271 | FirstVariant { 272 | #[clap(long)] 273 | foo_option: bool, 274 | }, 275 | SecondVariant { 276 | #[clap(rename_all = "kebab_case", long)] 277 | foo_option: bool, 278 | }, 279 | } 280 | 281 | assert_eq!( 282 | Opt::FirstVariant { foo_option: true }, 283 | Opt::parse_from(&["test", "first-variant", "--foo-option"]) 284 | ); 285 | 286 | assert_eq!( 287 | Opt::SecondVariant { foo_option: true }, 288 | Opt::parse_from(&["test", "SECOND_VARIANT", "--foo-option"]) 289 | ); 290 | } 291 | -------------------------------------------------------------------------------- /tests/arguments.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) , 2 | // Kevin Knapp (@kbknapp) , and 3 | // Andrew Hobden (@hoverbear) 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | // 11 | // This work was derived from Structopt (https://github.com/TeXitoi/structopt) 12 | // commit#ea76fa1b1b273e65e3b0b1046643715b49bec51f which is licensed under the 13 | // MIT/Apache 2.0 license. 14 | 15 | use clap::Clap; 16 | 17 | #[test] 18 | fn required_argument() { 19 | #[derive(Clap, PartialEq, Debug)] 20 | struct Opt { 21 | arg: i32, 22 | } 23 | assert_eq!(Opt { arg: 42 }, Opt::parse_from(&["test", "42"])); 24 | assert!(Opt::try_parse_from(&["test"]).is_err()); 25 | assert!(Opt::try_parse_from(&["test", "42", "24"]).is_err()); 26 | } 27 | 28 | #[test] 29 | fn optional_argument() { 30 | #[derive(Clap, PartialEq, Debug)] 31 | struct Opt { 32 | arg: Option, 33 | } 34 | assert_eq!(Opt { arg: Some(42) }, Opt::parse_from(&["test", "42"])); 35 | assert_eq!(Opt { arg: None }, Opt::parse_from(&["test"])); 36 | assert!(Opt::try_parse_from(&["test", "42", "24"]).is_err()); 37 | } 38 | 39 | #[test] 40 | fn argument_with_default() { 41 | #[derive(Clap, PartialEq, Debug)] 42 | struct Opt { 43 | #[clap(default_value = "42")] 44 | arg: i32, 45 | } 46 | assert_eq!(Opt { arg: 24 }, Opt::parse_from(&["test", "24"])); 47 | assert_eq!(Opt { arg: 42 }, Opt::parse_from(&["test"])); 48 | assert!(Opt::try_parse_from(&["test", "42", "24"]).is_err()); 49 | } 50 | 51 | #[test] 52 | fn arguments() { 53 | #[derive(Clap, PartialEq, Debug)] 54 | struct Opt { 55 | arg: Vec, 56 | } 57 | assert_eq!(Opt { arg: vec![24] }, Opt::parse_from(&["test", "24"])); 58 | assert_eq!(Opt { arg: vec![] }, Opt::parse_from(&["test"])); 59 | assert_eq!( 60 | Opt { arg: vec![24, 42] }, 61 | Opt::parse_from(&["test", "24", "42"]) 62 | ); 63 | } 64 | 65 | #[test] 66 | fn arguments_safe() { 67 | #[derive(Clap, PartialEq, Debug)] 68 | struct Opt { 69 | arg: Vec, 70 | } 71 | assert_eq!( 72 | Opt { arg: vec![24] }, 73 | Opt::try_parse_from(&["test", "24"]).unwrap() 74 | ); 75 | assert_eq!(Opt { arg: vec![] }, Opt::try_parse_from(&["test"]).unwrap()); 76 | assert_eq!( 77 | Opt { arg: vec![24, 42] }, 78 | Opt::try_parse_from(&["test", "24", "42"]).unwrap() 79 | ); 80 | 81 | assert_eq!( 82 | clap::ErrorKind::ValueValidation, 83 | Opt::try_parse_from(&["test", "NOPE"]).err().unwrap().kind 84 | ); 85 | } 86 | -------------------------------------------------------------------------------- /tests/author_version_about.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) , 2 | // Kevin Knapp (@kbknapp) , and 3 | // Andrew Hobden (@hoverbear) 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | // 11 | // This work was derived from Structopt (https://github.com/TeXitoi/structopt) 12 | // commit#ea76fa1b1b273e65e3b0b1046643715b49bec51f which is licensed under the 13 | // MIT/Apache 2.0 license. 14 | 15 | mod utils; 16 | 17 | use clap::Clap; 18 | use utils::*; 19 | 20 | #[test] 21 | fn no_author_version_about() { 22 | #[derive(Clap, PartialEq, Debug)] 23 | #[clap(name = "foo", no_version)] 24 | struct Opt {} 25 | 26 | let output = get_long_help::(); 27 | assert!(output.starts_with("foo \n\nUSAGE:")); 28 | } 29 | 30 | #[test] 31 | fn use_env() { 32 | #[derive(Clap, PartialEq, Debug)] 33 | #[clap(author, about)] 34 | struct Opt {} 35 | 36 | let output = get_long_help::(); 37 | assert!(output.starts_with("clap_derive")); 38 | assert!(output.contains("Guillaume Pinot , Kevin K. ")); 39 | assert!(output.contains("Parse command line argument by defining a struct, derive crate")); 40 | } 41 | 42 | #[test] 43 | fn explicit_version_not_str() { 44 | const VERSION: &str = "custom version"; 45 | 46 | #[derive(Clap)] 47 | #[clap(version = VERSION)] 48 | pub struct Opt {} 49 | 50 | let output = get_long_help::(); 51 | assert!(output.contains("custom version")); 52 | } 53 | -------------------------------------------------------------------------------- /tests/basic.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) , 2 | // Kevin Knapp (@kbknapp) , and 3 | // Andrew Hobden (@hoverbear) 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | // 11 | // This work was derived from Structopt (https://github.com/TeXitoi/structopt) 12 | // commit#ea76fa1b1b273e65e3b0b1046643715b49bec51f which is licensed under the 13 | // MIT/Apache 2.0 license. 14 | 15 | use clap::Clap; 16 | 17 | #[test] 18 | fn basic() { 19 | #[derive(Clap, PartialEq, Debug)] 20 | struct Opt { 21 | #[clap(short = "a", long = "arg")] 22 | arg: Vec, 23 | } 24 | assert_eq!(Opt { arg: vec![24] }, Opt::parse_from(&["test", "-a24"])); 25 | assert_eq!(Opt { arg: vec![] }, Opt::parse_from(&["test"])); 26 | assert_eq!( 27 | Opt { arg: vec![24, 42] }, 28 | Opt::parse_from(&["test", "-a24", "--arg", "42"]) 29 | ); 30 | } 31 | -------------------------------------------------------------------------------- /tests/custom-string-parsers.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) , 2 | // Kevin Knapp (@kbknapp) , and 3 | // Andrew Hobden (@hoverbear) 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | // 11 | // This work was derived from Structopt (https://github.com/TeXitoi/structopt) 12 | // commit#ea76fa1b1b273e65e3b0b1046643715b49bec51f which is licensed under the 13 | // MIT/Apache 2.0 license. 14 | 15 | use clap::Clap; 16 | 17 | use std::ffi::{CString, OsStr, OsString}; 18 | use std::num::ParseIntError; 19 | use std::path::PathBuf; 20 | 21 | #[derive(Clap, PartialEq, Debug)] 22 | struct PathOpt { 23 | #[clap(short, long, parse(from_os_str))] 24 | path: PathBuf, 25 | 26 | #[clap(short, default_value = "../", parse(from_os_str))] 27 | default_path: PathBuf, 28 | 29 | #[clap(short, parse(from_os_str))] 30 | vector_path: Vec, 31 | 32 | #[clap(short, parse(from_os_str))] 33 | option_path_1: Option, 34 | 35 | #[clap(short = "q", parse(from_os_str))] 36 | option_path_2: Option, 37 | } 38 | 39 | #[test] 40 | fn test_path_opt_simple() { 41 | assert_eq!( 42 | PathOpt { 43 | path: PathBuf::from("/usr/bin"), 44 | default_path: PathBuf::from("../"), 45 | vector_path: vec![ 46 | PathBuf::from("/a/b/c"), 47 | PathBuf::from("/d/e/f"), 48 | PathBuf::from("/g/h/i"), 49 | ], 50 | option_path_1: None, 51 | option_path_2: Some(PathBuf::from("j.zip")), 52 | }, 53 | PathOpt::parse_from(&[ 54 | "test", "-p", "/usr/bin", "-v", "/a/b/c", "-v", "/d/e/f", "-v", "/g/h/i", "-q", 55 | "j.zip", 56 | ]) 57 | ); 58 | } 59 | 60 | fn parse_hex(input: &str) -> Result { 61 | u64::from_str_radix(input, 16) 62 | } 63 | 64 | #[derive(Clap, PartialEq, Debug)] 65 | struct HexOpt { 66 | #[clap(short, parse(try_from_str = parse_hex))] 67 | number: u64, 68 | } 69 | 70 | #[test] 71 | fn test_parse_hex() { 72 | assert_eq!( 73 | HexOpt { number: 5 }, 74 | HexOpt::parse_from(&["test", "-n", "5"]) 75 | ); 76 | assert_eq!( 77 | HexOpt { number: 0xabcdef }, 78 | HexOpt::parse_from(&["test", "-n", "abcdef"]) 79 | ); 80 | 81 | let err = HexOpt::try_parse_from(&["test", "-n", "gg"]).unwrap_err(); 82 | assert!(err.message.contains("invalid digit found in string"), err); 83 | } 84 | 85 | fn custom_parser_1(_: &str) -> &'static str { 86 | "A" 87 | } 88 | fn custom_parser_2(_: &str) -> Result<&'static str, u32> { 89 | Ok("B") 90 | } 91 | fn custom_parser_3(_: &OsStr) -> &'static str { 92 | "C" 93 | } 94 | fn custom_parser_4(_: &OsStr) -> Result<&'static str, String> { 95 | Ok("D") 96 | } 97 | 98 | #[derive(Clap, PartialEq, Debug)] 99 | struct NoOpOpt { 100 | #[clap(short, parse(from_str = custom_parser_1))] 101 | a: &'static str, 102 | #[clap(short, parse(try_from_str = custom_parser_2))] 103 | b: &'static str, 104 | #[clap(short, parse(from_os_str = custom_parser_3))] 105 | c: &'static str, 106 | #[clap(short, parse(try_from_os_str = custom_parser_4))] 107 | d: &'static str, 108 | } 109 | 110 | #[test] 111 | fn test_every_custom_parser() { 112 | assert_eq!( 113 | NoOpOpt { 114 | a: "A", 115 | b: "B", 116 | c: "C", 117 | d: "D" 118 | }, 119 | NoOpOpt::parse_from(&["test", "-a=?", "-b=?", "-c=?", "-d=?"]) 120 | ); 121 | } 122 | 123 | // Note: can't use `Vec` directly, as clap would instead look for 124 | // conversion function from `&str` to `u8`. 125 | type Bytes = Vec; 126 | 127 | #[derive(Clap, PartialEq, Debug)] 128 | struct DefaultedOpt { 129 | #[clap(short, parse(from_str))] 130 | bytes: Bytes, 131 | 132 | #[clap(short, parse(try_from_str))] 133 | integer: u64, 134 | 135 | #[clap(short, parse(from_os_str))] 136 | path: PathBuf, 137 | } 138 | 139 | #[test] 140 | fn test_parser_with_default_value() { 141 | assert_eq!( 142 | DefaultedOpt { 143 | bytes: b"E\xc2\xb2=p\xc2\xb2c\xc2\xb2+m\xc2\xb2c\xe2\x81\xb4".to_vec(), 144 | integer: 9000, 145 | path: PathBuf::from("src/lib.rs"), 146 | }, 147 | DefaultedOpt::parse_from(&[ 148 | "test", 149 | "-b", 150 | "E²=p²c²+m²c⁴", 151 | "-i", 152 | "9000", 153 | "-p", 154 | "src/lib.rs", 155 | ]) 156 | ); 157 | } 158 | 159 | #[derive(PartialEq, Debug)] 160 | struct Foo(u8); 161 | 162 | fn foo(value: u64) -> Foo { 163 | Foo(value as u8) 164 | } 165 | 166 | #[derive(Clap, PartialEq, Debug)] 167 | struct Occurrences { 168 | #[clap(short, long, parse(from_occurrences))] 169 | signed: i32, 170 | 171 | #[clap(short, parse(from_occurrences))] 172 | little_signed: i8, 173 | 174 | #[clap(short, parse(from_occurrences))] 175 | unsigned: usize, 176 | 177 | #[clap(short = "r", parse(from_occurrences))] 178 | little_unsigned: u8, 179 | 180 | #[clap(short, long, parse(from_occurrences = foo))] 181 | custom: Foo, 182 | } 183 | 184 | #[test] 185 | fn test_parser_occurrences() { 186 | assert_eq!( 187 | Occurrences { 188 | signed: 3, 189 | little_signed: 1, 190 | unsigned: 0, 191 | little_unsigned: 4, 192 | custom: Foo(5), 193 | }, 194 | Occurrences::parse_from(&[ 195 | "test", "-s", "--signed", "--signed", "-l", "-rrrr", "-cccc", "--custom", 196 | ]) 197 | ); 198 | } 199 | 200 | #[test] 201 | fn test_custom_bool() { 202 | fn parse_bool(s: &str) -> Result { 203 | match s { 204 | "true" => Ok(true), 205 | "false" => Ok(false), 206 | _ => Err(format!("invalid bool {}", s)), 207 | } 208 | } 209 | #[derive(Clap, PartialEq, Debug)] 210 | struct Opt { 211 | #[clap(short, parse(try_from_str = parse_bool))] 212 | debug: bool, 213 | #[clap( 214 | short, 215 | default_value = "false", 216 | parse(try_from_str = parse_bool) 217 | )] 218 | verbose: bool, 219 | #[clap(short, parse(try_from_str = parse_bool))] 220 | tribool: Option, 221 | #[clap(short, parse(try_from_str = parse_bool))] 222 | bitset: Vec, 223 | } 224 | 225 | assert!(Opt::try_parse_from(&["test"]).is_err()); 226 | assert!(Opt::try_parse_from(&["test", "-d"]).is_err()); 227 | assert!(Opt::try_parse_from(&["test", "-dfoo"]).is_err()); 228 | assert_eq!( 229 | Opt { 230 | debug: false, 231 | verbose: false, 232 | tribool: None, 233 | bitset: vec![], 234 | }, 235 | Opt::parse_from(&["test", "-dfalse"]) 236 | ); 237 | assert_eq!( 238 | Opt { 239 | debug: true, 240 | verbose: false, 241 | tribool: None, 242 | bitset: vec![], 243 | }, 244 | Opt::parse_from(&["test", "-dtrue"]) 245 | ); 246 | assert_eq!( 247 | Opt { 248 | debug: true, 249 | verbose: false, 250 | tribool: None, 251 | bitset: vec![], 252 | }, 253 | Opt::parse_from(&["test", "-dtrue", "-vfalse"]) 254 | ); 255 | assert_eq!( 256 | Opt { 257 | debug: true, 258 | verbose: true, 259 | tribool: None, 260 | bitset: vec![], 261 | }, 262 | Opt::parse_from(&["test", "-dtrue", "-vtrue"]) 263 | ); 264 | assert_eq!( 265 | Opt { 266 | debug: true, 267 | verbose: false, 268 | tribool: Some(false), 269 | bitset: vec![], 270 | }, 271 | Opt::parse_from(&["test", "-dtrue", "-tfalse"]) 272 | ); 273 | assert_eq!( 274 | Opt { 275 | debug: true, 276 | verbose: false, 277 | tribool: Some(true), 278 | bitset: vec![], 279 | }, 280 | Opt::parse_from(&["test", "-dtrue", "-ttrue"]) 281 | ); 282 | assert_eq!( 283 | Opt { 284 | debug: true, 285 | verbose: false, 286 | tribool: None, 287 | bitset: vec![false, true, false, false], 288 | }, 289 | Opt::parse_from(&["test", "-dtrue", "-bfalse", "-btrue", "-bfalse", "-bfalse"]) 290 | ); 291 | } 292 | 293 | #[test] 294 | fn test_cstring() { 295 | use clap::IntoApp; 296 | 297 | #[derive(Clap)] 298 | struct Opt { 299 | #[clap(parse(try_from_str = CString::new))] 300 | c_string: CString, 301 | } 302 | 303 | assert!(Opt::try_parse_from(&["test"]).is_err()); 304 | assert_eq!( 305 | Opt::parse_from(&["test", "bla"]).c_string.to_bytes(), 306 | b"bla" 307 | ); 308 | assert!(Opt::try_parse_from(&["test", "bla\0bla"]).is_err()); 309 | } 310 | -------------------------------------------------------------------------------- /tests/deny-warnings.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) , 2 | // Kevin Knapp (@kbknapp) , and 3 | // Andrew Hobden (@hoverbear) 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | // 11 | // This work was derived from Structopt (https://github.com/TeXitoi/structopt) 12 | // commit#ea76fa1b1b273e65e3b0b1046643715b49bec51f which is licensed under the 13 | // MIT/Apache 2.0 license. 14 | 15 | #![deny(warnings)] 16 | 17 | extern crate clap; 18 | 19 | use clap::Clap; 20 | 21 | fn try_str(s: &str) -> Result { 22 | Ok(s.into()) 23 | } 24 | 25 | #[test] 26 | fn warning_never_struct() { 27 | #[derive(Debug, PartialEq, Clap)] 28 | struct Opt { 29 | #[clap(parse(try_from_str = try_str))] 30 | s: String, 31 | } 32 | assert_eq!( 33 | Opt { 34 | s: "foo".to_string() 35 | }, 36 | Opt::parse_from(&["test", "foo"]) 37 | ); 38 | } 39 | 40 | #[test] 41 | fn warning_never_enum() { 42 | #[derive(Debug, PartialEq, Clap)] 43 | enum Opt { 44 | Foo { 45 | #[clap(parse(try_from_str = try_str))] 46 | s: String, 47 | }, 48 | } 49 | assert_eq!( 50 | Opt::Foo { 51 | s: "foo".to_string() 52 | }, 53 | Opt::parse_from(&["test", "foo", "foo"]) 54 | ); 55 | } 56 | -------------------------------------------------------------------------------- /tests/doc-comments-help.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) , 2 | // Kevin Knapp (@kbknapp) , and 3 | // Andrew Hobden (@hoverbear) 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | // 11 | // This work was derived from Structopt (https://github.com/TeXitoi/structopt) 12 | // commit#ea76fa1b1b273e65e3b0b1046643715b49bec51f which is licensed under the 13 | // MIT/Apache 2.0 license. 14 | 15 | mod utils; 16 | 17 | use clap::Clap; 18 | use utils::*; 19 | 20 | #[test] 21 | fn doc_comments() { 22 | /// Lorem ipsum 23 | #[derive(Clap, PartialEq, Debug)] 24 | struct LoremIpsum { 25 | /// Fooify a bar 26 | /// and a baz 27 | #[clap(short, long)] 28 | foo: bool, 29 | } 30 | 31 | let help = get_long_help::(); 32 | assert!(help.contains("Lorem ipsum")); 33 | assert!(help.contains("Fooify a bar and a baz")); 34 | } 35 | 36 | #[test] 37 | fn help_is_better_than_comments() { 38 | /// Lorem ipsum 39 | #[derive(Clap, PartialEq, Debug)] 40 | #[clap(name = "lorem-ipsum", about = "Dolor sit amet")] 41 | struct LoremIpsum { 42 | /// Fooify a bar 43 | #[clap(short, long, help = "DO NOT PASS A BAR UNDER ANY CIRCUMSTANCES")] 44 | foo: bool, 45 | } 46 | 47 | let help = get_long_help::(); 48 | assert!(help.contains("Dolor sit amet")); 49 | assert!(!help.contains("Lorem ipsum")); 50 | assert!(help.contains("DO NOT PASS A BAR")); 51 | } 52 | 53 | #[test] 54 | fn empty_line_in_doc_comment_is_double_linefeed() { 55 | /// Foo. 56 | /// 57 | /// Bar 58 | #[derive(Clap, PartialEq, Debug)] 59 | #[clap(name = "lorem-ipsum", no_version)] 60 | struct LoremIpsum {} 61 | 62 | let help = get_long_help::(); 63 | assert!(help.starts_with("lorem-ipsum \nFoo.\n\nBar\n\nUSAGE:")); 64 | } 65 | 66 | #[test] 67 | fn field_long_doc_comment_both_help_long_help() { 68 | /// Lorem ipsumclap 69 | #[derive(Clap, PartialEq, Debug)] 70 | #[clap(name = "lorem-ipsum", about = "Dolor sit amet")] 71 | struct LoremIpsum { 72 | /// DO NOT PASS A BAR UNDER ANY CIRCUMSTANCES. 73 | /// 74 | /// Or something else 75 | #[clap(long)] 76 | foo: bool, 77 | } 78 | 79 | let short_help = get_help::(); 80 | let long_help = get_long_help::(); 81 | 82 | assert!(short_help.contains("CIRCUMSTANCES")); 83 | assert!(!short_help.contains("CIRCUMSTANCES.")); 84 | assert!(!short_help.contains("Or something else")); 85 | assert!(long_help.contains("DO NOT PASS A BAR UNDER ANY CIRCUMSTANCES")); 86 | assert!(long_help.contains("Or something else")); 87 | } 88 | 89 | #[test] 90 | fn top_long_doc_comment_both_help_long_help() { 91 | /// Lorem ipsumclap 92 | #[derive(Clap, Debug)] 93 | #[clap(name = "lorem-ipsum", about = "Dolor sit amet")] 94 | struct LoremIpsum { 95 | #[clap(subcommand)] 96 | foo: SubCommand, 97 | } 98 | 99 | #[derive(Clap, Debug)] 100 | pub enum SubCommand { 101 | /// DO NOT PASS A BAR UNDER ANY CIRCUMSTANCES 102 | /// 103 | /// Or something else 104 | Foo { 105 | #[clap(help = "foo")] 106 | bars: Vec, 107 | }, 108 | } 109 | 110 | let short_help = get_help::(); 111 | let long_help = get_subcommand_long_help::("foo"); 112 | 113 | assert!(!short_help.contains("Or something else")); 114 | assert!(long_help.contains("DO NOT PASS A BAR UNDER ANY CIRCUMSTANCES")); 115 | assert!(long_help.contains("Or something else")); 116 | } 117 | -------------------------------------------------------------------------------- /tests/explicit_name_no_renaming.rs: -------------------------------------------------------------------------------- 1 | mod utils; 2 | 3 | use clap::Clap; 4 | use utils::*; 5 | 6 | #[test] 7 | fn explicit_short_long_no_rename() { 8 | #[derive(Clap, PartialEq, Debug)] 9 | struct Opt { 10 | #[clap(short = ".", long = ".foo")] 11 | foo: Vec, 12 | } 13 | 14 | assert_eq!( 15 | Opt { 16 | foo: vec!["short".into(), "long".into()] 17 | }, 18 | Opt::parse_from(&["test", "-.", "short", "--.foo", "long"]) 19 | ); 20 | } 21 | 22 | #[test] 23 | fn explicit_name_no_rename() { 24 | #[derive(Clap, PartialEq, Debug)] 25 | struct Opt { 26 | #[clap(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 | // Kevin Knapp (@kbknapp) , and 3 | // Andrew Hobden (@hoverbear) 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | // 11 | // This work was derived from Structopt (https://github.com/TeXitoi/structopt) 12 | // commit#ea76fa1b1b273e65e3b0b1046643715b49bec51f which is licensed under the 13 | // MIT/Apache 2.0 license. 14 | 15 | use clap::Clap; 16 | 17 | #[test] 18 | fn unique_flag() { 19 | #[derive(Clap, PartialEq, Debug)] 20 | struct Opt { 21 | #[clap(short, long)] 22 | alice: bool, 23 | } 24 | 25 | assert_eq!(Opt { alice: false }, Opt::parse_from(&["test"])); 26 | assert_eq!(Opt { alice: true }, Opt::parse_from(&["test", "-a"])); 27 | assert_eq!(Opt { alice: true }, Opt::parse_from(&["test", "--alice"])); 28 | assert!(Opt::try_parse_from(&["test", "-i"]).is_err()); 29 | assert!(Opt::try_parse_from(&["test", "-a", "foo"]).is_err()); 30 | assert!(Opt::try_parse_from(&["test", "-a", "-a"]).is_err()); 31 | assert!(Opt::try_parse_from(&["test", "-a", "--alice"]).is_err()); 32 | } 33 | 34 | #[test] 35 | fn multiple_flag() { 36 | #[derive(Clap, PartialEq, Debug)] 37 | struct Opt { 38 | #[clap(short, long, parse(from_occurrences))] 39 | alice: u64, 40 | #[clap(short, long, parse(from_occurrences))] 41 | bob: u8, 42 | } 43 | 44 | assert_eq!(Opt { alice: 0, bob: 0 }, Opt::parse_from(&["test"])); 45 | assert_eq!(Opt { alice: 1, bob: 0 }, Opt::parse_from(&["test", "-a"])); 46 | assert_eq!( 47 | Opt { alice: 2, bob: 0 }, 48 | Opt::parse_from(&["test", "-a", "-a"]) 49 | ); 50 | assert_eq!( 51 | Opt { alice: 2, bob: 2 }, 52 | Opt::parse_from(&["test", "-a", "--alice", "-bb"]) 53 | ); 54 | assert_eq!( 55 | Opt { alice: 3, bob: 1 }, 56 | Opt::parse_from(&["test", "-aaa", "--bob"]) 57 | ); 58 | assert!(Opt::try_parse_from(&["test", "-i"]).is_err()); 59 | assert!(Opt::try_parse_from(&["test", "-a", "foo"]).is_err()); 60 | } 61 | 62 | fn parse_from_flag(b: bool) -> std::sync::atomic::AtomicBool { 63 | std::sync::atomic::AtomicBool::new(b) 64 | } 65 | 66 | #[test] 67 | fn non_bool_flags() { 68 | #[derive(Clap, Debug)] 69 | struct Opt { 70 | #[clap(short, long, parse(from_flag = parse_from_flag))] 71 | alice: std::sync::atomic::AtomicBool, 72 | #[clap(short, long, parse(from_flag))] 73 | bob: std::sync::atomic::AtomicBool, 74 | } 75 | 76 | let falsey = Opt::parse_from(&["test"]); 77 | assert!(!falsey.alice.load(std::sync::atomic::Ordering::Relaxed)); 78 | assert!(!falsey.bob.load(std::sync::atomic::Ordering::Relaxed)); 79 | 80 | let alice = Opt::parse_from(&["test", "-a"]); 81 | assert!(alice.alice.load(std::sync::atomic::Ordering::Relaxed)); 82 | assert!(!alice.bob.load(std::sync::atomic::Ordering::Relaxed)); 83 | 84 | let bob = Opt::parse_from(&["test", "-b"]); 85 | assert!(!bob.alice.load(std::sync::atomic::Ordering::Relaxed)); 86 | assert!(bob.bob.load(std::sync::atomic::Ordering::Relaxed)); 87 | 88 | let both = Opt::parse_from(&["test", "-b", "-a"]); 89 | assert!(both.alice.load(std::sync::atomic::Ordering::Relaxed)); 90 | assert!(both.bob.load(std::sync::atomic::Ordering::Relaxed)); 91 | } 92 | 93 | #[test] 94 | fn combined_flags() { 95 | #[derive(Clap, PartialEq, Debug)] 96 | struct Opt { 97 | #[clap(short, long)] 98 | alice: bool, 99 | #[clap(short, long, parse(from_occurrences))] 100 | bob: u64, 101 | } 102 | 103 | assert_eq!( 104 | Opt { 105 | alice: false, 106 | bob: 0 107 | }, 108 | Opt::parse_from(&["test"]) 109 | ); 110 | assert_eq!( 111 | Opt { 112 | alice: true, 113 | bob: 0 114 | }, 115 | Opt::parse_from(&["test", "-a"]) 116 | ); 117 | assert_eq!( 118 | Opt { 119 | alice: true, 120 | bob: 0 121 | }, 122 | Opt::parse_from(&["test", "-a"]) 123 | ); 124 | assert_eq!( 125 | Opt { 126 | alice: false, 127 | bob: 1 128 | }, 129 | Opt::parse_from(&["test", "-b"]) 130 | ); 131 | assert_eq!( 132 | Opt { 133 | alice: true, 134 | bob: 1 135 | }, 136 | Opt::parse_from(&["test", "--alice", "--bob"]) 137 | ); 138 | assert_eq!( 139 | Opt { 140 | alice: true, 141 | bob: 4 142 | }, 143 | Opt::parse_from(&["test", "-bb", "-a", "-bb"]) 144 | ); 145 | } 146 | -------------------------------------------------------------------------------- /tests/flatten.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) , 2 | // Kevin Knapp (@kbknapp) , and 3 | // Andrew Hobden (@hoverbear) 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | // 11 | // This work was derived from Structopt (https://github.com/TeXitoi/structopt) 12 | // commit#ea76fa1b1b273e65e3b0b1046643715b49bec51f which is licensed under the 13 | // MIT/Apache 2.0 license. 14 | 15 | use clap::Clap; 16 | 17 | #[test] 18 | fn flatten() { 19 | #[derive(Clap, PartialEq, Debug)] 20 | struct Common { 21 | arg: i32, 22 | } 23 | 24 | #[derive(Clap, PartialEq, Debug)] 25 | struct Opt { 26 | #[clap(flatten)] 27 | common: Common, 28 | } 29 | assert_eq!( 30 | Opt { 31 | common: Common { arg: 42 } 32 | }, 33 | Opt::parse_from(&["test", "42"]) 34 | ); 35 | assert!(Opt::try_parse_from(&["test"]).is_err()); 36 | assert!(Opt::try_parse_from(&["test", "42", "24"]).is_err()); 37 | } 38 | 39 | #[test] 40 | #[should_panic] 41 | fn flatten_twice() { 42 | #[derive(Clap, PartialEq, Debug)] 43 | struct Common { 44 | arg: i32, 45 | } 46 | 47 | #[derive(Clap, PartialEq, Debug)] 48 | struct Opt { 49 | #[clap(flatten)] 50 | c1: Common, 51 | // Defines "arg" twice, so this should not work. 52 | #[clap(flatten)] 53 | c2: Common, 54 | } 55 | Opt::parse_from(&["test", "42", "43"]); 56 | } 57 | 58 | #[test] 59 | fn flatten_in_subcommand() { 60 | #[derive(Clap, PartialEq, Debug)] 61 | struct Common { 62 | arg: i32, 63 | } 64 | 65 | #[derive(Clap, PartialEq, Debug)] 66 | struct Add { 67 | #[clap(short)] 68 | interactive: bool, 69 | #[clap(flatten)] 70 | common: Common, 71 | } 72 | 73 | #[derive(Clap, PartialEq, Debug)] 74 | enum Opt { 75 | Fetch { 76 | #[clap(short)] 77 | all: bool, 78 | #[clap(flatten)] 79 | common: Common, 80 | }, 81 | 82 | Add(Add), 83 | } 84 | 85 | assert_eq!( 86 | Opt::Fetch { 87 | all: false, 88 | common: Common { arg: 42 } 89 | }, 90 | Opt::parse_from(&["test", "fetch", "42"]) 91 | ); 92 | assert_eq!( 93 | Opt::Add(Add { 94 | interactive: true, 95 | common: Common { arg: 43 } 96 | }), 97 | Opt::parse_from(&["test", "add", "-i", "43"]) 98 | ); 99 | } 100 | -------------------------------------------------------------------------------- /tests/issues.rs: -------------------------------------------------------------------------------- 1 | // https://github.com/TeXitoi/structopt/issues/151 2 | // https://github.com/TeXitoi/structopt/issues/289 3 | 4 | #[test] 5 | fn issue_151() { 6 | use clap::{ArgGroup, Clap, IntoApp}; 7 | 8 | #[derive(Clap, Debug)] 9 | #[clap(group = ArgGroup::with_name("verb").required(true).multiple(true))] 10 | struct Opt { 11 | #[clap(long, group = "verb")] 12 | foo: bool, 13 | #[clap(long, group = "verb")] 14 | bar: bool, 15 | } 16 | 17 | #[derive(Debug, Clap)] 18 | struct Cli { 19 | #[clap(flatten)] 20 | a: Opt, 21 | } 22 | 23 | assert!(Cli::try_parse_from(&["test"]).is_err()); 24 | assert!(Cli::try_parse_from(&["test", "--foo"]).is_ok()); 25 | assert!(Cli::try_parse_from(&["test", "--bar"]).is_ok()); 26 | assert!(Cli::try_parse_from(&["test", "--zebra"]).is_err()); 27 | } 28 | 29 | #[test] 30 | fn issue_289() { 31 | use clap::{AppSettings, Clap, IntoApp}; 32 | 33 | #[derive(Clap)] 34 | #[clap(setting = AppSettings::InferSubcommands)] 35 | enum Args { 36 | SomeCommand(SubSubCommand), 37 | AnotherCommand, 38 | } 39 | 40 | #[derive(Clap)] 41 | #[clap(setting = AppSettings::InferSubcommands)] 42 | enum SubSubCommand { 43 | TestCommand, 44 | } 45 | 46 | assert!(Args::try_parse_from(&["test", "some-command", "test-command"]).is_ok()); 47 | assert!(Args::try_parse_from(&["test", "some", "test-command"]).is_ok()); 48 | assert!(Args::try_parse_from(&["test", "some-command", "test"]).is_ok()); 49 | assert!(Args::try_parse_from(&["test", "some", "test"]).is_ok()); 50 | } 51 | -------------------------------------------------------------------------------- /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.39)), 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 | // Kevin Knapp (@kbknapp) , and 3 | // Andrew Hobden (@hoverbear) 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | // 11 | // This work was derived from Structopt (https://github.com/TeXitoi/structopt) 12 | // commit#ea76fa1b1b273e65e3b0b1046643715b49bec51f which is licensed under the 13 | // MIT/Apache 2.0 license. 14 | 15 | use clap::Clap; 16 | 17 | #[derive(Clap, PartialEq, Debug)] 18 | struct Opt { 19 | #[clap(short, long)] 20 | force: bool, 21 | #[clap(short, long, parse(from_occurrences))] 22 | verbose: u64, 23 | #[clap(subcommand)] 24 | cmd: Sub, 25 | } 26 | 27 | #[derive(Clap, PartialEq, Debug)] 28 | enum Sub { 29 | Fetch {}, 30 | Add {}, 31 | } 32 | 33 | #[derive(Clap, PartialEq, Debug)] 34 | struct Opt2 { 35 | #[clap(short, long)] 36 | force: bool, 37 | #[clap(short, long, parse(from_occurrences))] 38 | verbose: u64, 39 | #[clap(subcommand)] 40 | cmd: Option, 41 | } 42 | 43 | #[test] 44 | fn test_no_cmd() { 45 | let result = Opt::try_parse_from(&["test"]); 46 | assert!(result.is_err()); 47 | 48 | assert_eq!( 49 | Opt2 { 50 | force: false, 51 | verbose: 0, 52 | cmd: None 53 | }, 54 | Opt2::parse_from(&["test"]) 55 | ); 56 | } 57 | 58 | #[test] 59 | fn test_fetch() { 60 | assert_eq!( 61 | Opt { 62 | force: false, 63 | verbose: 3, 64 | cmd: Sub::Fetch {} 65 | }, 66 | Opt::parse_from(&["test", "-vvv", "fetch"]) 67 | ); 68 | assert_eq!( 69 | Opt { 70 | force: true, 71 | verbose: 0, 72 | cmd: Sub::Fetch {} 73 | }, 74 | Opt::parse_from(&["test", "--force", "fetch"]) 75 | ); 76 | } 77 | 78 | #[test] 79 | fn test_add() { 80 | assert_eq!( 81 | Opt { 82 | force: false, 83 | verbose: 0, 84 | cmd: Sub::Add {} 85 | }, 86 | Opt::parse_from(&["test", "add"]) 87 | ); 88 | assert_eq!( 89 | Opt { 90 | force: false, 91 | verbose: 2, 92 | cmd: Sub::Add {} 93 | }, 94 | Opt::parse_from(&["test", "-vv", "add"]) 95 | ); 96 | } 97 | 98 | #[test] 99 | fn test_badinput() { 100 | let result = Opt::try_parse_from(&["test", "badcmd"]); 101 | assert!(result.is_err()); 102 | let result = Opt::try_parse_from(&["test", "add", "--verbose"]); 103 | assert!(result.is_err()); 104 | let result = Opt::try_parse_from(&["test", "--badopt", "add"]); 105 | assert!(result.is_err()); 106 | let result = Opt::try_parse_from(&["test", "add", "--badopt"]); 107 | assert!(result.is_err()); 108 | } 109 | 110 | #[derive(Clap, PartialEq, Debug)] 111 | struct Opt3 { 112 | #[clap(short, long)] 113 | all: bool, 114 | #[clap(subcommand)] 115 | cmd: Sub2, 116 | } 117 | 118 | #[derive(Clap, PartialEq, Debug)] 119 | enum Sub2 { 120 | Foo { 121 | file: String, 122 | #[clap(subcommand)] 123 | cmd: Sub3, 124 | }, 125 | Bar {}, 126 | } 127 | 128 | #[derive(Clap, PartialEq, Debug)] 129 | enum Sub3 { 130 | Baz {}, 131 | Quux {}, 132 | } 133 | 134 | #[test] 135 | fn test_subsubcommand() { 136 | assert_eq!( 137 | Opt3 { 138 | all: true, 139 | cmd: Sub2::Foo { 140 | file: "lib.rs".to_string(), 141 | cmd: Sub3::Quux {} 142 | } 143 | }, 144 | Opt3::parse_from(&["test", "--all", "foo", "lib.rs", "quux"]) 145 | ); 146 | } 147 | 148 | #[derive(Clap, PartialEq, Debug)] 149 | enum SubSubCmdWithOption { 150 | Remote { 151 | #[clap(subcommand)] 152 | cmd: Option, 153 | }, 154 | Stash { 155 | #[clap(subcommand)] 156 | cmd: Stash, 157 | }, 158 | } 159 | #[derive(Clap, PartialEq, Debug)] 160 | enum Remote { 161 | Add { name: String, url: String }, 162 | Remove { name: String }, 163 | } 164 | 165 | #[derive(Clap, PartialEq, Debug)] 166 | enum Stash { 167 | Save, 168 | Pop, 169 | } 170 | 171 | #[test] 172 | fn sub_sub_cmd_with_option() { 173 | fn make(args: &[&str]) -> Option { 174 | use clap::{FromArgMatches, IntoApp}; 175 | 176 | SubSubCmdWithOption::try_parse_from(args).ok() 177 | } 178 | assert_eq!( 179 | Some(SubSubCmdWithOption::Remote { cmd: None }), 180 | make(&["", "remote"]) 181 | ); 182 | assert_eq!( 183 | Some(SubSubCmdWithOption::Remote { 184 | cmd: Some(Remote::Add { 185 | name: "origin".into(), 186 | url: "http".into() 187 | }) 188 | }), 189 | make(&["", "remote", "add", "origin", "http"]) 190 | ); 191 | assert_eq!( 192 | Some(SubSubCmdWithOption::Stash { cmd: Stash::Save }), 193 | make(&["", "stash", "save"]) 194 | ); 195 | assert_eq!(None, make(&["", "stash"])); 196 | } 197 | -------------------------------------------------------------------------------- /tests/non_literal_attributes.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) , 2 | // Kevin Knapp (@kbknapp) , and 3 | // Andrew Hobden (@hoverbear) 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | // 11 | // This work was derived from Structopt (https://github.com/TeXitoi/structopt) 12 | // commit#ea76fa1b1b273e65e3b0b1046643715b49bec51f which is licensed under the 13 | // MIT/Apache 2.0 license. 14 | 15 | use clap::{AppSettings, Clap}; 16 | use std::num::ParseIntError; 17 | 18 | pub const DISPLAY_ORDER: usize = 2; 19 | 20 | // Check if the global settings compile 21 | #[derive(Clap, Debug, PartialEq, Eq)] 22 | #[clap(global_setting = AppSettings::ColoredHelp)] 23 | struct Opt { 24 | #[clap( 25 | long = "x", 26 | display_order = DISPLAY_ORDER, 27 | next_line_help = true, 28 | default_value = "0", 29 | require_equals = true 30 | )] 31 | x: i32, 32 | 33 | #[clap(short = "l", long = "level", aliases = &["set-level", "lvl"])] 34 | level: String, 35 | 36 | #[clap(long("values"))] 37 | values: Vec, 38 | 39 | #[clap(name = "FILE", requires_if("FILE", "values"))] 40 | files: Vec, 41 | } 42 | 43 | #[test] 44 | fn test_slice() { 45 | assert_eq!( 46 | Opt { 47 | x: 0, 48 | level: "1".to_string(), 49 | files: Vec::new(), 50 | values: vec![], 51 | }, 52 | Opt::parse_from(&["test", "-l", "1"]) 53 | ); 54 | assert_eq!( 55 | Opt { 56 | x: 0, 57 | level: "1".to_string(), 58 | files: Vec::new(), 59 | values: vec![], 60 | }, 61 | Opt::parse_from(&["test", "--level", "1"]) 62 | ); 63 | assert_eq!( 64 | Opt { 65 | x: 0, 66 | level: "1".to_string(), 67 | files: Vec::new(), 68 | values: vec![], 69 | }, 70 | Opt::parse_from(&["test", "--set-level", "1"]) 71 | ); 72 | assert_eq!( 73 | Opt { 74 | x: 0, 75 | level: "1".to_string(), 76 | files: Vec::new(), 77 | values: vec![], 78 | }, 79 | Opt::parse_from(&["test", "--lvl", "1"]) 80 | ); 81 | } 82 | 83 | #[test] 84 | fn test_multi_args() { 85 | assert_eq!( 86 | Opt { 87 | x: 0, 88 | level: "1".to_string(), 89 | files: vec!["file".to_string()], 90 | values: vec![], 91 | }, 92 | Opt::parse_from(&["test", "-l", "1", "file"]) 93 | ); 94 | assert_eq!( 95 | Opt { 96 | x: 0, 97 | level: "1".to_string(), 98 | files: vec!["FILE".to_string()], 99 | values: vec![1], 100 | }, 101 | Opt::parse_from(&["test", "-l", "1", "--values", "1", "--", "FILE"]) 102 | ); 103 | } 104 | 105 | #[test] 106 | fn test_multi_args_fail() { 107 | let result = Opt::try_parse_from(&["test", "-l", "1", "--", "FILE"]); 108 | assert!(result.is_err()); 109 | } 110 | 111 | #[test] 112 | fn test_bool() { 113 | assert_eq!( 114 | Opt { 115 | x: 1, 116 | level: "1".to_string(), 117 | files: vec![], 118 | values: vec![], 119 | }, 120 | Opt::parse_from(&["test", "-l", "1", "--x=1"]) 121 | ); 122 | let result = Opt::try_parse_from(&["test", "-l", "1", "--x", "1"]); 123 | assert!(result.is_err()); 124 | } 125 | 126 | fn parse_hex(input: &str) -> Result { 127 | u64::from_str_radix(input, 16) 128 | } 129 | 130 | #[derive(Clap, PartialEq, Debug)] 131 | struct HexOpt { 132 | #[clap(short = "n", parse(try_from_str = parse_hex))] 133 | number: u64, 134 | } 135 | 136 | #[test] 137 | fn test_parse_hex_function_path() { 138 | assert_eq!( 139 | HexOpt { number: 5 }, 140 | HexOpt::parse_from(&["test", "-n", "5"]) 141 | ); 142 | assert_eq!( 143 | HexOpt { number: 0xabcdef }, 144 | HexOpt::parse_from(&["test", "-n", "abcdef"]) 145 | ); 146 | 147 | let err = HexOpt::try_parse_from(&["test", "-n", "gg"]).unwrap_err(); 148 | assert!(err.message.contains("invalid digit found in string"), err); 149 | } 150 | -------------------------------------------------------------------------------- /tests/options.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) , 2 | // Kevin Knapp (@kbknapp) , and 3 | // Andrew Hobden (@hoverbear) 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | // 11 | // This work was derived from Structopt (https://github.com/TeXitoi/structopt) 12 | // commit#ea76fa1b1b273e65e3b0b1046643715b49bec51f which is licensed under the 13 | // MIT/Apache 2.0 license. 14 | 15 | use clap::Clap; 16 | 17 | #[test] 18 | fn required_option() { 19 | #[derive(Clap, PartialEq, Debug)] 20 | struct Opt { 21 | #[clap(short, long)] 22 | arg: i32, 23 | } 24 | assert_eq!(Opt { arg: 42 }, Opt::parse_from(&["test", "-a42"])); 25 | assert_eq!(Opt { arg: 42 }, Opt::parse_from(&["test", "-a", "42"])); 26 | assert_eq!(Opt { arg: 42 }, Opt::parse_from(&["test", "--arg", "42"])); 27 | assert!(Opt::try_parse_from(&["test"]).is_err()); 28 | assert!(Opt::try_parse_from(&["test", "-a42", "-a24"]).is_err()); 29 | } 30 | 31 | #[test] 32 | fn optional_option() { 33 | #[derive(Clap, PartialEq, Debug)] 34 | struct Opt { 35 | #[clap(short)] 36 | arg: Option, 37 | } 38 | assert_eq!(Opt { arg: Some(42) }, Opt::parse_from(&["test", "-a42"])); 39 | assert_eq!(Opt { arg: None }, Opt::parse_from(&["test"])); 40 | assert!(Opt::try_parse_from(&["test", "-a42", "-a24"]).is_err()); 41 | } 42 | 43 | #[test] 44 | fn option_with_default() { 45 | #[derive(Clap, PartialEq, Debug)] 46 | struct Opt { 47 | #[clap(short, default_value = "42")] 48 | arg: i32, 49 | } 50 | assert_eq!(Opt { arg: 24 }, Opt::parse_from(&["test", "-a24"])); 51 | assert_eq!(Opt { arg: 42 }, Opt::parse_from(&["test"])); 52 | assert!(Opt::try_parse_from(&["test", "-a42", "-a24"]).is_err()); 53 | } 54 | 55 | #[test] 56 | fn option_with_raw_default() { 57 | #[derive(Clap, PartialEq, Debug)] 58 | struct Opt { 59 | #[clap(short, default_value = "42")] 60 | arg: i32, 61 | } 62 | assert_eq!(Opt { arg: 24 }, Opt::parse_from(&["test", "-a24"])); 63 | assert_eq!(Opt { arg: 42 }, Opt::parse_from(&["test"])); 64 | assert!(Opt::try_parse_from(&["test", "-a42", "-a24"]).is_err()); 65 | } 66 | 67 | #[test] 68 | fn options() { 69 | #[derive(Clap, PartialEq, Debug)] 70 | struct Opt { 71 | #[clap(short, long)] 72 | arg: Vec, 73 | } 74 | assert_eq!(Opt { arg: vec![24] }, Opt::parse_from(&["test", "-a24"])); 75 | assert_eq!(Opt { arg: vec![] }, Opt::parse_from(&["test"])); 76 | assert_eq!( 77 | Opt { arg: vec![24, 42] }, 78 | Opt::parse_from(&["test", "-a24", "--arg", "42"]) 79 | ); 80 | } 81 | 82 | #[test] 83 | fn default_value() { 84 | #[derive(Clap, PartialEq, Debug)] 85 | struct Opt { 86 | #[clap(short, default_value = "test")] 87 | arg: String, 88 | } 89 | assert_eq!(Opt { arg: "test".into() }, Opt::parse_from(&["test"])); 90 | assert_eq!( 91 | Opt { arg: "foo".into() }, 92 | Opt::parse_from(&["test", "-afoo"]) 93 | ); 94 | } 95 | 96 | #[test] 97 | fn option_from_str() { 98 | #[derive(Debug, PartialEq)] 99 | struct A; 100 | 101 | impl<'a> From<&'a str> for A { 102 | fn from(_: &str) -> A { 103 | A 104 | } 105 | } 106 | 107 | #[derive(Debug, Clap, PartialEq)] 108 | struct Opt { 109 | #[clap(parse(from_str))] 110 | a: Option, 111 | } 112 | 113 | assert_eq!(Opt { a: None }, Opt::parse_from(&["test"])); 114 | assert_eq!(Opt { a: Some(A) }, Opt::parse_from(&["test", "foo"])); 115 | } 116 | 117 | #[test] 118 | fn optional_argument_for_optional_option() { 119 | use clap::IntoApp; 120 | 121 | #[derive(Clap, PartialEq, Debug)] 122 | struct Opt { 123 | #[clap(short)] 124 | #[allow(clippy::option_option)] 125 | arg: Option>, 126 | } 127 | assert_eq!( 128 | Opt { 129 | arg: Some(Some(42)) 130 | }, 131 | Opt::parse_from(&["test", "-a42"]) 132 | ); 133 | assert_eq!(Opt { arg: Some(None) }, Opt::parse_from(&["test", "-a"])); 134 | assert_eq!(Opt { arg: None }, Opt::parse_from(&["test"])); 135 | assert!(Opt::try_parse_from(&["test", "-a42", "-a24"]).is_err()); 136 | } 137 | 138 | #[test] 139 | fn two_option_options() { 140 | #[derive(Clap, PartialEq, Debug)] 141 | struct Opt { 142 | #[clap(short)] 143 | arg: Option>, 144 | 145 | #[clap(long)] 146 | field: Option>, 147 | } 148 | assert_eq!( 149 | Opt { 150 | arg: Some(Some(42)), 151 | field: Some(Some("f".into())) 152 | }, 153 | Opt::parse_from(&["test", "-a42", "--field", "f"]) 154 | ); 155 | assert_eq!( 156 | Opt { 157 | arg: Some(Some(42)), 158 | field: Some(None) 159 | }, 160 | Opt::parse_from(&["test", "-a42", "--field"]) 161 | ); 162 | assert_eq!( 163 | Opt { 164 | arg: Some(None), 165 | field: Some(None) 166 | }, 167 | Opt::parse_from(&["test", "-a", "--field"]) 168 | ); 169 | assert_eq!( 170 | Opt { 171 | arg: Some(None), 172 | field: Some(Some("f".into())) 173 | }, 174 | Opt::parse_from(&["test", "-a", "--field", "f"]) 175 | ); 176 | assert_eq!( 177 | Opt { 178 | arg: None, 179 | field: Some(None) 180 | }, 181 | Opt::parse_from(&["test", "--field"]) 182 | ); 183 | assert_eq!( 184 | Opt { 185 | arg: None, 186 | field: None 187 | }, 188 | Opt::parse_from(&["test"]) 189 | ); 190 | } 191 | 192 | #[test] 193 | fn optional_vec() { 194 | #[derive(Clap, PartialEq, Debug)] 195 | struct Opt { 196 | #[clap(short)] 197 | arg: Option>, 198 | } 199 | assert_eq!( 200 | Opt { arg: Some(vec![1]) }, 201 | Opt::parse_from(&["test", "-a", "1"]) 202 | ); 203 | 204 | assert_eq!( 205 | Opt { 206 | arg: Some(vec![1, 2]) 207 | }, 208 | Opt::parse_from(&["test", "-a1", "-a2"]) 209 | ); 210 | 211 | assert_eq!( 212 | Opt { 213 | arg: Some(vec![1, 2]) 214 | }, 215 | Opt::parse_from(&["test", "-a1", "-a2", "-a"]) 216 | ); 217 | 218 | assert_eq!( 219 | Opt { 220 | arg: Some(vec![1, 2]) 221 | }, 222 | Opt::parse_from(&["test", "-a1", "-a", "-a2"]) 223 | ); 224 | 225 | assert_eq!( 226 | Opt { 227 | arg: Some(vec![1, 2]) 228 | }, 229 | Opt::parse_from(&["test", "-a", "1", "2"]) 230 | ); 231 | 232 | assert_eq!( 233 | Opt { 234 | arg: Some(vec![1, 2, 3]) 235 | }, 236 | Opt::parse_from(&["test", "-a", "1", "2", "-a", "3"]) 237 | ); 238 | 239 | assert_eq!(Opt { arg: Some(vec![]) }, Opt::parse_from(&["test", "-a"])); 240 | 241 | assert_eq!( 242 | Opt { arg: Some(vec![]) }, 243 | Opt::parse_from(&["test", "-a", "-a"]) 244 | ); 245 | 246 | assert_eq!(Opt { arg: None }, Opt::parse_from(&["test"])); 247 | } 248 | 249 | #[test] 250 | fn two_optional_vecs() { 251 | #[derive(Clap, PartialEq, Debug)] 252 | struct Opt { 253 | #[clap(short)] 254 | arg: Option>, 255 | 256 | #[clap(short)] 257 | b: Option>, 258 | } 259 | 260 | assert_eq!( 261 | Opt { 262 | arg: Some(vec![1]), 263 | b: Some(vec![]) 264 | }, 265 | Opt::parse_from(&["test", "-a", "1", "-b"]) 266 | ); 267 | 268 | assert_eq!( 269 | Opt { 270 | arg: Some(vec![1]), 271 | b: Some(vec![]) 272 | }, 273 | Opt::parse_from(&["test", "-a", "-b", "-a1"]) 274 | ); 275 | 276 | assert_eq!( 277 | Opt { 278 | arg: Some(vec![1, 2]), 279 | b: Some(vec![1, 2]) 280 | }, 281 | Opt::parse_from(&["test", "-a1", "-a2", "-b1", "-b2"]) 282 | ); 283 | 284 | assert_eq!(Opt { arg: None, b: None }, Opt::parse_from(&["test"])); 285 | } 286 | -------------------------------------------------------------------------------- /tests/privacy.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) , 2 | // Kevin Knapp (@kbknapp) , and 3 | // Andrew Hobden (@hoverbear) 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | // 11 | // This work was derived from Structopt (https://github.com/TeXitoi/structopt) 12 | // commit#ea76fa1b1b273e65e3b0b1046643715b49bec51f which is licensed under the 13 | // MIT/Apache 2.0 license. 14 | 15 | mod options { 16 | use clap::Clap; 17 | 18 | #[derive(Debug, Clap)] 19 | pub struct Options { 20 | #[clap(subcommand)] 21 | pub subcommand: super::subcommands::SubCommand, 22 | } 23 | } 24 | 25 | mod subcommands { 26 | use clap::Clap; 27 | 28 | #[derive(Debug, Clap)] 29 | pub enum SubCommand { 30 | /// foo 31 | Foo { 32 | /// foo 33 | bars: Vec, 34 | }, 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /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 clap::Clap; 10 | 11 | #[test] 12 | fn raw_bool_literal() { 13 | #[derive(Clap, Debug, PartialEq)] 14 | #[clap(no_version, name = "raw_bool")] 15 | struct Opt { 16 | #[clap(raw(false))] 17 | a: String, 18 | #[clap(raw(true))] 19 | b: String, 20 | } 21 | 22 | assert_eq!( 23 | Opt { 24 | a: "one".into(), 25 | b: "--help".into() 26 | }, 27 | Opt::parse_from(&["test", "one", "--", "--help"]) 28 | ); 29 | } 30 | -------------------------------------------------------------------------------- /tests/raw_idents.rs: -------------------------------------------------------------------------------- 1 | use clap::Clap; 2 | 3 | #[test] 4 | fn raw_idents() { 5 | #[derive(Clap, Debug, PartialEq)] 6 | struct Opt { 7 | #[clap(short, long)] 8 | r#type: Vec, 9 | } 10 | 11 | assert_eq!( 12 | Opt { 13 | r#type: vec!["long".into(), "short".into()] 14 | }, 15 | Opt::parse_from(&["test", "--type", "long", "-t", "short"]) 16 | ); 17 | } 18 | -------------------------------------------------------------------------------- /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 clap::Clap; 10 | 11 | #[test] 12 | fn skip_1() { 13 | #[derive(Clap, Debug, PartialEq)] 14 | struct Opt { 15 | #[clap(short)] 16 | x: u32, 17 | #[clap(skip)] 18 | s: u32, 19 | } 20 | 21 | assert!(Opt::try_parse_from(&["test", "-x", "10", "20"]).is_err()); 22 | assert_eq!( 23 | Opt::parse_from(&["test", "-x", "10"]), 24 | Opt { 25 | x: 10, 26 | s: 0, // default 27 | } 28 | ); 29 | } 30 | 31 | #[test] 32 | fn skip_2() { 33 | #[derive(Clap, Debug, PartialEq)] 34 | struct Opt { 35 | #[clap(short)] 36 | x: u32, 37 | #[clap(skip)] 38 | ss: String, 39 | #[clap(skip)] 40 | sn: u8, 41 | y: u32, 42 | #[clap(skip)] 43 | sz: u16, 44 | t: u32, 45 | } 46 | 47 | assert_eq!( 48 | Opt::parse_from(&["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(Clap, Debug, PartialEq)] 76 | pub struct Opt { 77 | #[clap(long, short)] 78 | number: u32, 79 | #[clap(skip)] 80 | k: Kind, 81 | #[clap(skip)] 82 | v: Vec, 83 | } 84 | 85 | assert_eq!( 86 | Opt::parse_from(&["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(Clap, Debug, PartialEq)] 98 | pub struct Opt { 99 | #[clap(skip, help = "internal_stuff")] 100 | a: u32, 101 | 102 | #[clap(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 | #[clap(skip)] 109 | c: u32, 110 | 111 | #[clap(short, parse(try_from_str))] 112 | n: u32, 113 | } 114 | 115 | assert_eq!( 116 | Opt::parse_from(&["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(Clap, Debug, PartialEq)] 129 | pub struct Opt { 130 | #[clap(long, short)] 131 | number: u32, 132 | 133 | #[clap(skip = "key")] 134 | k: String, 135 | 136 | #[clap(skip = vec![1, 2, 3])] 137 | v: Vec, 138 | } 139 | 140 | assert_eq!( 141 | Opt::parse_from(&["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 clap::Clap; 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(Clap, 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::parse_from(&["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(Clap, PartialEq, Debug)] 42 | struct Opt { 43 | #[clap(parse(from_str = parser))] 44 | arg: ::std::option::Option, 45 | } 46 | 47 | assert_eq!( 48 | Opt { 49 | arg: Some("success".into()) 50 | }, 51 | Opt::parse_from(&["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(Clap, PartialEq, Debug)] 62 | struct Opt { 63 | #[clap(parse(from_str = parser))] 64 | arg: ::std::vec::Vec, 65 | } 66 | 67 | assert_eq!( 68 | Opt { 69 | arg: vec!["success".into()] 70 | }, 71 | Opt::parse_from(&["test", "success"]) 72 | ); 73 | } 74 | -------------------------------------------------------------------------------- /tests/subcommands.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Guillaume Pinot (@TeXitoi) , 2 | // Kevin Knapp (@kbknapp) , and 3 | // Andrew Hobden (@hoverbear) 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | // 11 | // This work was derived from Structopt (https://github.com/TeXitoi/structopt) 12 | // commit#ea76fa1b1b273e65e3b0b1046643715b49bec51f which is licensed under the 13 | // MIT/Apache 2.0 license. 14 | 15 | mod utils; 16 | 17 | use clap::Clap; 18 | use utils::*; 19 | 20 | #[derive(Clap, PartialEq, Debug)] 21 | enum Opt { 22 | /// Fetch stuff from GitHub 23 | Fetch { 24 | #[clap(long)] 25 | all: bool, 26 | #[clap(short, long)] 27 | /// Overwrite local branches. 28 | force: bool, 29 | repo: String, 30 | }, 31 | 32 | Add { 33 | #[clap(short, long)] 34 | interactive: bool, 35 | #[clap(short, long)] 36 | verbose: bool, 37 | }, 38 | } 39 | 40 | #[test] 41 | fn test_fetch() { 42 | assert_eq!( 43 | Opt::Fetch { 44 | all: true, 45 | force: false, 46 | repo: "origin".to_string() 47 | }, 48 | Opt::parse_from(&["test", "fetch", "--all", "origin"]) 49 | ); 50 | assert_eq!( 51 | Opt::Fetch { 52 | all: false, 53 | force: true, 54 | repo: "origin".to_string() 55 | }, 56 | Opt::parse_from(&["test", "fetch", "-f", "origin"]) 57 | ); 58 | } 59 | 60 | #[test] 61 | fn test_add() { 62 | assert_eq!( 63 | Opt::Add { 64 | interactive: false, 65 | verbose: false 66 | }, 67 | Opt::parse_from(&["test", "add"]) 68 | ); 69 | assert_eq!( 70 | Opt::Add { 71 | interactive: true, 72 | verbose: true 73 | }, 74 | Opt::parse_from(&["test", "add", "-i", "-v"]) 75 | ); 76 | } 77 | 78 | #[test] 79 | fn test_no_parse() { 80 | let result = Opt::try_parse_from(&["test", "badcmd", "-i", "-v"]); 81 | assert!(result.is_err()); 82 | 83 | let result = Opt::try_parse_from(&["test", "add", "--badoption"]); 84 | assert!(result.is_err()); 85 | 86 | let result = Opt::try_parse_from(&["test"]); 87 | assert!(result.is_err()); 88 | } 89 | 90 | #[derive(Clap, PartialEq, Debug)] 91 | enum Opt2 { 92 | DoSomething { arg: String }, 93 | } 94 | 95 | #[test] 96 | /// This test is specifically to make sure that hyphenated subcommands get 97 | /// processed correctly. 98 | fn test_hyphenated_subcommands() { 99 | assert_eq!( 100 | Opt2::DoSomething { 101 | arg: "blah".to_string() 102 | }, 103 | Opt2::parse_from(&["test", "do-something", "blah"]) 104 | ); 105 | } 106 | 107 | #[derive(Clap, PartialEq, Debug)] 108 | enum Opt3 { 109 | Add, 110 | Init, 111 | Fetch, 112 | } 113 | 114 | #[test] 115 | fn test_null_commands() { 116 | assert_eq!(Opt3::Add, Opt3::parse_from(&["test", "add"])); 117 | assert_eq!(Opt3::Init, Opt3::parse_from(&["test", "init"])); 118 | assert_eq!(Opt3::Fetch, Opt3::parse_from(&["test", "fetch"])); 119 | } 120 | 121 | #[derive(Clap, PartialEq, Debug)] 122 | #[clap(about = "Not shown")] 123 | struct Add { 124 | file: String, 125 | } 126 | /// Not shown 127 | #[derive(Clap, PartialEq, Debug)] 128 | struct Fetch { 129 | remote: String, 130 | } 131 | #[derive(Clap, PartialEq, Debug)] 132 | enum Opt4 { 133 | // Not shown 134 | /// Add a file 135 | Add(Add), 136 | Init, 137 | /// download history from remote 138 | Fetch(Fetch), 139 | } 140 | 141 | #[test] 142 | fn test_tuple_commands() { 143 | use clap::IntoApp; 144 | 145 | assert_eq!( 146 | Opt4::Add(Add { 147 | file: "f".to_string() 148 | }), 149 | Opt4::parse_from(&["test", "add", "f"]) 150 | ); 151 | assert_eq!(Opt4::Init, Opt4::parse_from(&["test", "init"])); 152 | assert_eq!( 153 | Opt4::Fetch(Fetch { 154 | remote: "origin".to_string() 155 | }), 156 | Opt4::parse_from(&["test", "fetch", "origin"]) 157 | ); 158 | 159 | let output = get_long_help::(); 160 | 161 | assert!(output.contains("download history from remote")); 162 | assert!(output.contains("Add a file")); 163 | assert!(!output.contains("Not shown")); 164 | } 165 | 166 | #[test] 167 | fn enum_in_enum_subsubcommand() { 168 | #[derive(Clap, Debug, PartialEq)] 169 | pub enum Opt { 170 | Daemon(DaemonCommand), 171 | } 172 | 173 | #[derive(Clap, Debug, PartialEq)] 174 | pub enum DaemonCommand { 175 | Start, 176 | Stop, 177 | } 178 | 179 | let result = Opt::try_parse_from(&["test"]); 180 | assert!(result.is_err()); 181 | 182 | let result = Opt::try_parse_from(&["test", "daemon"]); 183 | assert!(result.is_err()); 184 | 185 | let result = Opt::parse_from(&["test", "daemon", "start"]); 186 | assert_eq!(Opt::Daemon(DaemonCommand::Start), result); 187 | } 188 | 189 | #[test] 190 | fn flatten_enum() { 191 | #[derive(Clap, Debug, PartialEq)] 192 | struct Opt { 193 | #[clap(flatten)] 194 | sub_cmd: SubCmd, 195 | } 196 | #[derive(Clap, Debug, PartialEq)] 197 | enum SubCmd { 198 | Foo, 199 | Bar, 200 | } 201 | 202 | assert!(Opt::try_parse_from(&["test"]).is_err()); 203 | assert_eq!( 204 | Opt::parse_from(&["test", "foo"]), 205 | Opt { 206 | sub_cmd: SubCmd::Foo 207 | } 208 | ); 209 | } 210 | -------------------------------------------------------------------------------- /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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | #[clap(name = "basic")] 13 | struct Opt { 14 | #[clap(short, default_value = true)] 15 | b: bool, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::parse(); 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:19 3 | | 4 | 14 | #[clap(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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | #[clap(name = "basic")] 13 | struct Opt { 14 | #[clap(short, required = true)] 15 | b: bool, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::parse(); 20 | println!("{:?}", opt); 21 | } 22 | -------------------------------------------------------------------------------- /tests/ui/bool_required.stderr: -------------------------------------------------------------------------------- 1 | error: required is meaningless for bool 2 | --> $DIR/bool_required.rs:14:19 3 | | 4 | 14 | #[clap(short, required = true)] 5 | | ^^^^^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/clap_derive_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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | #[clap(name = "basic")] 13 | struct Opt { 14 | #[clap] 15 | debug: bool, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::parse(); 20 | println!("{:?}", opt); 21 | } 22 | 23 | -------------------------------------------------------------------------------- /tests/ui/clap_derive_empty_attr.stderr: -------------------------------------------------------------------------------- 1 | error: expected parentheses after `clap` 2 | --> $DIR/clap_derive_empty_attr.rs:14:7 3 | | 4 | 14 | #[clap] 5 | | ^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/clap_derive_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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | #[clap(name = "basic")] 13 | struct Opt { 14 | #[clap = "short"] 15 | debug: bool, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::parse(); 20 | println!("{:?}", opt); 21 | } 22 | 23 | -------------------------------------------------------------------------------- /tests/ui/clap_derive_name_value_attr.stderr: -------------------------------------------------------------------------------- 1 | error: expected parentheses 2 | --> $DIR/clap_derive_name_value_attr.rs:14:12 3 | | 4 | 14 | #[clap = "short"] 5 | | ^ 6 | -------------------------------------------------------------------------------- /tests/ui/flatten_and_doc.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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | struct DaemonOpts { 13 | #[clap(short)] 14 | user: String, 15 | #[clap(short)] 16 | group: String, 17 | } 18 | 19 | #[derive(Clap, Debug)] 20 | #[clap(name = "basic")] 21 | struct Opt { 22 | /// Opts. 23 | #[clap(flatten)] 24 | opts: DaemonOpts, 25 | } 26 | 27 | fn main() { 28 | let opt = Opt::parse(); 29 | println!("{:?}", opt); 30 | } 31 | -------------------------------------------------------------------------------- /tests/ui/flatten_and_doc.stderr: -------------------------------------------------------------------------------- 1 | error: methods and doc comments are not allowed for flattened entry 2 | --> $DIR/flatten_and_doc.rs:23:12 3 | | 4 | 23 | #[clap(flatten)] 5 | | ^^^^^^^ 6 | -------------------------------------------------------------------------------- /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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | struct DaemonOpts { 13 | #[clap(short)] 14 | user: String, 15 | #[clap(short)] 16 | group: String, 17 | } 18 | 19 | #[derive(Clap, Debug)] 20 | #[clap(name = "basic")] 21 | struct Opt { 22 | #[clap(short, flatten)] 23 | opts: DaemonOpts, 24 | } 25 | 26 | fn main() { 27 | let opt = Opt::parse(); 28 | println!("{:?}", opt); 29 | } 30 | -------------------------------------------------------------------------------- /tests/ui/flatten_and_methods.stderr: -------------------------------------------------------------------------------- 1 | error: methods and doc comments are not allowed for flattened entry 2 | --> $DIR/flatten_and_methods.rs:22:19 3 | | 4 | 22 | #[clap(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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | struct DaemonOpts { 13 | #[clap(short)] 14 | user: String, 15 | #[clap(short)] 16 | group: String, 17 | } 18 | 19 | #[derive(Clap, Debug)] 20 | #[clap(name = "basic")] 21 | struct Opt { 22 | #[clap(flatten, parse(from_occurrences))] 23 | opts: DaemonOpts, 24 | } 25 | 26 | fn main() { 27 | let opt = Opt::parse(); 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:21 3 | | 4 | 22 | #[clap(flatten, parse(from_occurrences))] 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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | #[clap(name = "basic")] 13 | struct Opt { 14 | #[clap(short, non_existing_attribute = 1)] 15 | debug: bool, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::parse(); 20 | println!("{:?}", opt); 21 | } 22 | -------------------------------------------------------------------------------- /tests/ui/non_existent_attr.stderr: -------------------------------------------------------------------------------- 1 | error[E0599]: no method named `non_existing_attribute` found for type `clap::build::arg::Arg<'_>` in the current scope 2 | --> $DIR/non_existent_attr.rs:14:19 3 | | 4 | 14 | #[clap(short, non_existing_attribute = 1)] 5 | | ^^^^^^^^^^^^^^^^^^^^^^ method not found in `clap::build::arg::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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | #[clap(name = "basic")] 13 | struct Opt { 14 | n: Option>, 15 | } 16 | 17 | fn main() { 18 | let opt = Opt::parse(); 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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | #[clap(name = "basic")] 13 | struct Opt { 14 | n: Option>, 15 | } 16 | 17 | fn main() { 18 | let opt = Opt::parse(); 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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | #[clap(name = "basic")] 13 | struct Opt { 14 | #[clap(short, default_value = 1)] 15 | n: Option, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::parse(); 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:19 3 | | 4 | 14 | #[clap(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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | #[clap(name = "basic")] 13 | struct Opt { 14 | #[clap(short, required = true)] 15 | n: Option, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::parse(); 20 | println!("{:?}", opt); 21 | } 22 | -------------------------------------------------------------------------------- /tests/ui/option_required.stderr: -------------------------------------------------------------------------------- 1 | error: required is meaningless for Option 2 | --> $DIR/option_required.rs:14:19 3 | | 4 | 14 | #[clap(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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | #[clap(name = "basic")] 13 | struct Opt { 14 | #[clap(parse(try_from_os_str))] 15 | s: String, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::parse(); 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:18 3 | | 4 | 14 | #[clap(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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | #[clap(name = "basic")] 13 | struct Opt { 14 | #[clap(parse(from_str = "2"))] 15 | s: String, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::parse(); 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:29 3 | | 4 | 14 | #[clap(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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | #[clap(name = "basic")] 13 | struct Opt { 14 | #[clap(parse("from_str"))] 15 | s: String, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::parse(); 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:18 3 | | 4 | 14 | #[clap(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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | #[clap(name = "basic")] 13 | struct Opt { 14 | #[clap(parse(from_str, from_str))] 15 | s: String, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::parse(); 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:12 3 | | 4 | 14 | #[clap(parse(from_str, from_str))] 5 | | ^^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/positional_bool.rs: -------------------------------------------------------------------------------- 1 | use clap::Clap; 2 | 3 | #[derive(Clap, Debug)] 4 | struct Opt { 5 | verbose: bool, 6 | } 7 | 8 | fn main() { 9 | Opt::parse(); 10 | } 11 | -------------------------------------------------------------------------------- /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/clap-rs/clap_derive/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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | struct Opt { 13 | #[clap(raw(case_insensitive = "true"))] 14 | s: String, 15 | } 16 | 17 | fn main() { 18 | let opt = Opt::parse(); 19 | println!("{:?}", opt); 20 | } 21 | -------------------------------------------------------------------------------- /tests/ui/raw.stderr: -------------------------------------------------------------------------------- 1 | error: `#[clap(raw(...))` attributes are removed, 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: #[clap(case_insensitive(true))] 5 | 6 | --> $DIR/raw.rs:13:12 7 | | 8 | 13 | #[clap(raw(case_insensitive = "true"))] 9 | | ^^^ 10 | -------------------------------------------------------------------------------- /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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | #[clap(name = "basic", rename_all = "fail")] 13 | struct Opt { 14 | #[clap(short)] 15 | s: String, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::parse(); 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:37 3 | | 4 | 12 | #[clap(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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | #[clap(name = "make-cookie")] 13 | struct MakeCookie { 14 | #[clap(short)] 15 | s: String, 16 | 17 | #[clap(skip, flatten)] 18 | cmd: Command, 19 | } 20 | 21 | #[derive(Clap, Debug)] 22 | enum Command { 23 | #[clap(name = "pound")] 24 | /// Pound acorns into flour for cookie dough. 25 | Pound { acorns: u32 }, 26 | 27 | Sparkle { 28 | #[clap(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::parse(); 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:18 3 | | 4 | 17 | #[clap(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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | #[clap(name = "make-cookie")] 13 | struct MakeCookie { 14 | #[clap(short)] 15 | s: String, 16 | 17 | #[clap(subcommand, skip)] 18 | cmd: Command, 19 | } 20 | 21 | #[derive(Clap, Debug)] 22 | enum Command { 23 | #[clap(name = "pound")] 24 | /// Pound acorns into flour for cookie dough. 25 | Pound { acorns: u32 }, 26 | 27 | Sparkle { 28 | #[clap(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::parse(); 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:24 3 | | 4 | 17 | #[clap(subcommand, skip)] 5 | | ^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/skip_with_other_options.rs: -------------------------------------------------------------------------------- 1 | use clap::Clap; 2 | 3 | #[derive(Clap, Debug)] 4 | #[clap(name = "test")] 5 | pub struct Opt { 6 | #[clap(long)] 7 | a: u32, 8 | #[clap(skip, long)] 9 | b: u32, 10 | } 11 | 12 | fn main() { 13 | let opt = Opt::parse(); 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:12 3 | | 4 | 8 | #[clap(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 clap::Clap; 10 | 11 | #[derive(Debug)] 12 | enum Kind { 13 | A, 14 | B, 15 | } 16 | 17 | #[derive(Clap, Debug)] 18 | #[clap(name = "test")] 19 | pub struct Opt { 20 | #[clap(short)] 21 | number: u32, 22 | #[clap(skip)] 23 | k: Kind, 24 | } 25 | 26 | fn main() { 27 | let opt = Opt::parse(); 28 | println!("{:?}", opt); 29 | } 30 | -------------------------------------------------------------------------------- /tests/ui/skip_without_default.stderr: -------------------------------------------------------------------------------- 1 | error[E0277]: the trait bound `Kind: std::default::Default` is not satisfied 2 | --> $DIR/skip_without_default.rs:22:12 3 | | 4 | 22 | #[clap(skip)] 5 | | ^^^^ the trait `std::default::Default` is not implemented for `Kind` 6 | | 7 | = note: required by `std::default::Default::default` 8 | 9 | For more information about this error, try `rustc --explain E0277`. 10 | -------------------------------------------------------------------------------- /tests/ui/struct_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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | #[clap(name = "basic", flatten)] 13 | struct Opt { 14 | #[clap(short)] 15 | s: String, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::parse(); 20 | println!("{:?}", opt); 21 | } 22 | -------------------------------------------------------------------------------- /tests/ui/struct_flatten.stderr: -------------------------------------------------------------------------------- 1 | error: flatten is only allowed on fields 2 | --> $DIR/struct_flatten.rs:12:24 3 | | 4 | 12 | #[clap(name = "basic", flatten)] 5 | | ^^^^^^^ 6 | -------------------------------------------------------------------------------- /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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | #[clap(name = "basic", parse(from_str))] 13 | struct Opt { 14 | #[clap(short)] 15 | s: String, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::parse(); 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:24 3 | | 4 | 12 | #[clap(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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | #[clap(name = "basic", subcommand)] 13 | struct Opt { 14 | #[clap(short)] 15 | s: String, 16 | } 17 | 18 | fn main() { 19 | let opt = Opt::parse(); 20 | println!("{:?}", opt); 21 | } 22 | -------------------------------------------------------------------------------- /tests/ui/struct_subcommand.stderr: -------------------------------------------------------------------------------- 1 | error: subcommand is only allowed on fields 2 | --> $DIR/struct_subcommand.rs:12:24 3 | | 4 | 12 | #[clap(name = "basic", subcommand)] 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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | struct MakeCookie { 13 | #[clap(short)] 14 | s: String, 15 | 16 | #[clap(subcommand, flatten)] 17 | cmd: Command, 18 | } 19 | 20 | #[derive(Clap, Debug)] 21 | enum Command { 22 | /// Pound acorns into flour for cookie dough. 23 | Pound { acorns: u32 }, 24 | 25 | Sparkle { 26 | #[clap(short)] 27 | color: String, 28 | }, 29 | } 30 | 31 | fn main() { 32 | let opt = MakeCookie::parse(); 33 | println!("{:?}", opt); 34 | } 35 | -------------------------------------------------------------------------------- /tests/ui/subcommand_and_flatten.stderr: -------------------------------------------------------------------------------- 1 | error: subcommand, flatten and skip cannot be used together 2 | --> $DIR/subcommand_and_flatten.rs:17:24 3 | | 4 | 17 | #[clap(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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | struct MakeCookie { 13 | #[clap(short)] 14 | s: String, 15 | 16 | #[clap(subcommand, long)] 17 | cmd: Command, 18 | } 19 | 20 | #[derive(Clap, Debug)] 21 | enum Command { 22 | /// Pound acorns into flour for cookie dough. 23 | Pound { acorns: u32 }, 24 | 25 | Sparkle { 26 | #[clap(short)] 27 | color: String, 28 | }, 29 | } 30 | 31 | fn main() { 32 | let opt = MakeCookie::parse(); 33 | println!("{:?}", opt); 34 | } 35 | -------------------------------------------------------------------------------- /tests/ui/subcommand_and_methods.stderr: -------------------------------------------------------------------------------- 1 | error: methods in attributes are not allowed for subcommand 2 | --> $DIR/subcommand_and_methods.rs:17:12 3 | | 4 | 17 | #[clap(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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | struct MakeCookie { 13 | #[clap(short)] 14 | s: String, 15 | 16 | #[clap(subcommand, parse(from_occurrences))] 17 | cmd: Command, 18 | } 19 | 20 | #[derive(Clap, Debug)] 21 | enum Command { 22 | /// Pound acorns into flour for cookie dough. 23 | Pound { acorns: u32 }, 24 | 25 | Sparkle { 26 | #[clap(short)] 27 | color: String, 28 | }, 29 | } 30 | 31 | fn main() { 32 | let opt = MakeCookie::parse(); 33 | println!("{:?}", opt); 34 | } 35 | -------------------------------------------------------------------------------- /tests/ui/subcommand_and_parse.stderr: -------------------------------------------------------------------------------- 1 | error: parse attribute is not allowed for subcommand 2 | --> $DIR/subcommand_and_parse.rs:17:24 3 | | 4 | 17 | #[clap(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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | struct MakeCookie { 13 | #[clap(short)] 14 | s: String, 15 | 16 | #[clap(subcommand)] 17 | cmd: Option>, 18 | } 19 | 20 | #[derive(Clap, Debug)] 21 | enum Command { 22 | /// Pound acorns into flour for cookie dough. 23 | Pound { acorns: u32 }, 24 | 25 | Sparkle { 26 | #[clap(short)] 27 | color: String, 28 | }, 29 | } 30 | 31 | fn main() { 32 | let opt = MakeCookie::parse(); 33 | println!("{:?}", opt); 34 | } 35 | -------------------------------------------------------------------------------- /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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | struct MakeCookie { 13 | #[clap(short)] 14 | s: String, 15 | 16 | #[clap(subcommand)] 17 | cmd: Option>, 18 | } 19 | 20 | #[derive(Clap, Debug)] 21 | enum Command { 22 | /// Pound acorns into flour for cookie dough. 23 | Pound { acorns: u32 }, 24 | 25 | Sparkle { 26 | #[clap(short)] 27 | color: String, 28 | }, 29 | } 30 | 31 | fn main() { 32 | let opt = MakeCookie::parse(); 33 | println!("{:?}", opt); 34 | } 35 | -------------------------------------------------------------------------------- /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 clap::Clap; 10 | 11 | #[derive(Clap, Debug)] 12 | #[clap(name = "basic")] 13 | struct Opt(u32); 14 | 15 | fn main() { 16 | let opt = Opt::parse(); 17 | println!("{:?}", opt); 18 | } 19 | -------------------------------------------------------------------------------- /tests/ui/tuple_struct.stderr: -------------------------------------------------------------------------------- 1 | error: clap_derive only supports non-tuple structs and enums 2 | --> $DIR/tuple_struct.rs:11:10 3 | | 4 | 11 | #[derive(Clap, Debug)] 5 | | ^^^^ 6 | -------------------------------------------------------------------------------- /tests/utils.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused)] 2 | extern crate clap; 3 | 4 | use clap::IntoApp; 5 | 6 | pub fn get_help() -> String { 7 | let mut output = Vec::new(); 8 | ::into_app() 9 | .write_help(&mut output) 10 | .unwrap(); 11 | let output = String::from_utf8(output).unwrap(); 12 | 13 | eprintln!("\n%%% HELP %%%:=====\n{}\n=====\n", output); 14 | eprintln!("\n%%% HELP (DEBUG) %%%:=====\n{:?}\n=====\n", output); 15 | 16 | output 17 | } 18 | 19 | pub fn get_long_help() -> String { 20 | let mut output = Vec::new(); 21 | ::into_app() 22 | .write_long_help(&mut output) 23 | .unwrap(); 24 | let output = String::from_utf8(output).unwrap(); 25 | 26 | eprintln!("\n%%% LONG_HELP %%%:=====\n{}\n=====\n", output); 27 | eprintln!("\n%%% LONG_HELP (DEBUG) %%%:=====\n{:?}\n=====\n", output); 28 | 29 | output 30 | } 31 | 32 | pub fn get_subcommand_long_help(subcmd: &str) -> String { 33 | let output = ::into_app() 34 | .try_get_matches_from(vec!["test", subcmd, "--help"]) 35 | .expect_err("") 36 | .message; 37 | 38 | eprintln!( 39 | "\n%%% SUBCOMMAND `{}` HELP %%%:=====\n{}\n=====\n", 40 | subcmd, output 41 | ); 42 | eprintln!( 43 | "\n%%% SUBCOMMAND `{}` HELP (DEBUG) %%%:=====\n{:?}\n=====\n", 44 | subcmd, output 45 | ); 46 | 47 | output 48 | } 49 | --------------------------------------------------------------------------------